Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

Reason's relays come from a signed list, so each machine homes on the nearest

Lars Talian3722b9f63b36
diff --git a/DESIGN.md b/DESIGN.md
index c26fd3f..50a20cf 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -87,11 +87,20 @@ SDK) both exist and work today. Zig has neither, which is why agent-rpc's MCP sh
**Transport: iroh 1.3.** Each daemon is an iroh `Endpoint` with a persistent secret key
(`~/.reason/network/machine.key`). Peers are dialed by `EndpointId`; iroh resolves addresses via n0 DNS/pkarr, finds
LAN peers with `iroh-mdns-address-lookup` (works with no internet), hole-punches, and falls back to a relay
-over HTTPS. Relays only see encrypted QUIC. The default relay is Reason's (`DEFAULT_RELAYS` in `src/net.rs`, a list
-so more regions can join), as n0's public relays are rate-limited and meant for development. A team without its own
+over HTTPS. Relays only see encrypted QUIC. The default relays are Reason's, one per region, as Reason lists them at
+`https://reasonmachines.com/network/relays.json` (`src/relays.rs`), as n0's public relays are rate-limited and meant
+for development. Each machine makes the one with the lowest latency its home relay; relays don't talk to each other,
+but iroh reaches a peer through the peer's home relay, so machines homed on different ones still find each other. The
+list steers relay traffic (end-to-end encrypted, but a bad list could cut machines off or show who talks to whom), so
+it is taken only signed with the same key as sign-in proofs (its own `typ`, `reason-network-relays`, and `iss`),
+fetched only over HTTPS from that address without following redirects, and rejected whole on any fault (an http
+relay, a duplicate, more than 16, over 64 KiB, expired). The daemon fetches it at start (waiting briefly for it on a
+machine's first network start) and every 6 hours, keeps the last good one in the state folder (`relays.json`, used
+even once expired while no newer comes), and applies a new one at the next network start. Without any, sfo1
+(`DEFAULT_RELAYS` in `src/net.rs`). A team without its own
relay still looks addresses up on n0's DNS, where each machine publishes its home relay: that is how a machine on
Reason's relay and one of an older build, on n0's, find each other (iroh dials a peer through whichever relay it is
-on), and what a four-word code needs. Teammates are also dialed through the default relay itself, so machines of this
+on), and what a four-word code needs. Teammates are also dialed through each of the default relays, so machines of this
build find each other even without that lookup. A team can set its own relay
(`reason-network relay <url>` or `reason-network init --relay <url>`; the `iroh-relay` binary on any VPS, Let's Encrypt on :443,
access limited to the roster's endpoint ids). Then its machines never contact n0: they use only that relay
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index 6629014..80eab98 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -71,6 +71,7 @@ pub async fn run(service: bool) -> Result<()> {
tokio::spawn(daemon.clone().relay_loop());
}
tokio::spawn(crate::migrate::run(log));
+ tokio::spawn(daemon.clone().relays_loop());
if update::allowed(daemon.cfg.auto_update) {
tokio::spawn(daemon.clone().update_loop());
}
@@ -321,6 +322,16 @@ impl Daemon {
})
}
+ /// Keeps Reason's relay list fresh, unless the team runs its own relay. A new list applies at the next start.
+ async fn relays_loop(self: Arc<Self>) {
+ loop {
+ if self.team_state().is_none_or(|t| t.meta.body.relay.is_none()) {
+ crate::relays::refresh().await;
+ }
+ tokio::time::sleep(crate::relays::EVERY).await;
+ }
+ }
+
/// Exits shortly (after the reply goes out). The service manager, or the next client, starts a fresh
/// daemon, which picks up changed config and team state.
fn restart_soon(self: &Arc<Self>) {
diff --git a/src/main.rs b/src/main.rs
index 1a5876e..f0fadef 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -15,6 +15,7 @@ mod net;
mod paths;
mod proof;
mod proto;
+mod relays;
mod render;
mod setup;
mod store;
@@ -231,7 +232,7 @@ enum Cmd {
#[arg(long)]
force: bool,
},
- /// Use your own iroh relay for the team, so its machines never contact n0 (or `default` for Reason's relay)
+ /// Use your own iroh relay for the team, so its machines never contact n0 (or `default` for Reason's relays)
Relay { url: String },
/// List messages waiting for your approval (when `inbound` is `hold`)
Held,
diff --git a/src/net.rs b/src/net.rs
index a8a5ab5..add6545 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -36,7 +36,8 @@ const MAX_FRAME: usize = 4 << 20;
const ACK_TIMEOUT: Duration = Duration::from_secs(5);
/// Two machines that dial each other at once open their connections within this long of each other.
const DIALED_TOGETHER: Duration = Duration::from_secs(5);
-/// The relays of a team that doesn't run its own: Reason's. n0's public ones are rate-limited and meant for testing.
+/// The relay of a team that doesn't run its own while this machine has no list of Reason's relays (see `relays`).
+/// n0's public ones are rate-limited and meant for testing.
pub const DEFAULT_RELAYS: &[&str] = &["https://relay-sfo1.compute.reasonmachines.com"];
pub fn default_relays() -> Vec<RelayUrl> {
@@ -140,7 +141,8 @@ pub async fn bind(key: SecretKey, relay: Option<&str>, lan: bool) -> Result<Endp
let Some(url) = relay else {
// The default relays, with n0's address lookup still: that is how a teammate on an older Reason Network (on
// n0's relays) and this machine find each other, and what four-word codes need.
- let mut b = Endpoint::builder(presets::N0).secret_key(key).relay_mode(RelayMode::custom(default_relays()));
+ let relays = crate::relays::current_or_fetch().await;
+ let mut b = Endpoint::builder(presets::N0).secret_key(key).relay_mode(RelayMode::custom(relays));
if lan {
b = b.address_lookup(MdnsAddressLookup::builder());
}
@@ -392,7 +394,7 @@ impl Net {
)),
invites: Default::default(),
endpoint,
- relays: relay.map_or_else(default_relays, |u| u.parse().into_iter().collect()),
+ relays: relay.map_or_else(crate::relays::current, |u| u.parse().into_iter().collect()),
daemon: Arc::downgrade(daemon),
links: Default::default(),
remote: Mutex::new(remote),
diff --git a/src/proof.rs b/src/proof.rs
index 1b88fb9..2c7d403 100644
--- a/src/proof.rs
+++ b/src/proof.rs
@@ -133,27 +133,8 @@ pub fn verify_ignoring_expiry(jws: &str, endpoint: &EndpointId) -> Result<Proof>
}
fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, Key)], expiry: bool) -> Result<Proof> {
- let bad = || anyhow!("this sign-in proof is damaged");
- if jws.len() > MAX_LEN {
- bail!("this sign-in proof is too long");
- }
- let mut parts = jws.trim().split('.');
- let (Some(h), Some(c), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
- return Err(bad());
- };
- let decode = |p: &str| BASE64URL_NOPAD.decode(p.as_bytes()).map_err(|_| bad());
- let header: Header = serde_json::from_slice(&decode(h)?).map_err(|_| bad())?;
- // RS256 only: never `none`, nor HS256 with the public key taken for a shared secret.
- if header.alg != "RS256" || header.typ != TYPE {
- bail!("not a Reason Network sign-in proof");
- }
- let Some((_, key)) = keys.iter().find(|(kid, _)| *kid == header.kid) else {
- bail!("this sign-in proof is signed with a key this version doesn't know (update Reason Network)");
- };
- if key.verify(&RSA_PKCS1_2048_8192_SHA256, format!("{h}.{c}").as_bytes(), &decode(s)?).is_err() {
- bail!("this sign-in proof's signature doesn't verify");
- }
- let claims: Claims = serde_json::from_slice(&decode(c)?).map_err(|_| bad())?;
+ let claims: Claims = serde_json::from_slice(&signed_claims(jws, TYPE, "sign-in proof", MAX_LEN, keys)?)
+ .map_err(|_| anyhow!("this sign-in proof is damaged"))?;
if claims.iss != ISSUER || claims.aud != AUDIENCE {
bail!("this sign-in proof isn't from Reason Network");
}
@@ -176,6 +157,36 @@ fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, Key)
Ok(p)
}
+/// The claims of `jws`, a compact JWS of type `typ` (a `what`, in errors) that one of Reason's keys signed, unparsed.
+/// What else they must say is the caller's to check.
+pub fn verify_signed(jws: &str, typ: &str, what: &str, max_len: usize) -> Result<Vec<u8>> {
+ signed_claims(jws, typ, what, max_len, trusted())
+}
+
+fn signed_claims(jws: &str, typ: &str, what: &str, max_len: usize, keys: &[(String, Key)]) -> Result<Vec<u8>> {
+ let bad = || anyhow!("this {what} is damaged");
+ if jws.len() > max_len {
+ bail!("this {what} is too long");
+ }
+ let mut parts = jws.trim().split('.');
+ let (Some(h), Some(c), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
+ return Err(bad());
+ };
+ let decode = |p: &str| BASE64URL_NOPAD.decode(p.as_bytes()).map_err(|_| bad());
+ let header: Header = serde_json::from_slice(&decode(h)?).map_err(|_| bad())?;
+ // RS256 only: never `none`, nor HS256 with the public key taken for a shared secret.
+ if header.alg != "RS256" || header.typ != typ {
+ bail!("not a Reason Network {what}");
+ }
+ let Some((_, key)) = keys.iter().find(|(kid, _)| *kid == header.kid) else {
+ bail!("this {what} is signed with a key this version doesn't know (update Reason Network)");
+ };
+ if key.verify(&RSA_PKCS1_2048_8192_SHA256, format!("{h}.{c}").as_bytes(), &decode(s)?).is_err() {
+ bail!("this {what}'s signature doesn't verify");
+ }
+ decode(c)
+}
+
#[cfg(test)]
pub(crate) mod tests {
use super::*;
diff --git a/src/relays.rs b/src/relays.rs
new file mode 100644
index 0000000..470eac2
--- /dev/null
+++ b/src/relays.rs
@@ -0,0 +1,327 @@
+//! The relays of a team that doesn't run its own: Reason's, one per region, as Reason lists them at [`URL`]. Each
+//! machine makes the nearest its home relay, and is reached there by teammates on any of them (relays don't talk to
+//! each other; iroh dials a peer through the peer's home relay).
+//!
+//! The list steers every such machine's relay traffic. That traffic is end-to-end encrypted, but a list of someone
+//! else's relays could cut machines off or show who talks to whom, so it is taken only signed with Reason's proof key
+//! (`typ` `reason-network-relays`, its own `iss`: neither a sign-in proof nor anything else signed with that key passes
+//! for one) and fetched only over HTTPS from [`URL`], following no redirect. Any fault rejects the whole list.
+//!
+//! The last good list is kept in the state folder (`relays.json`, the document as served) and used from then on, even
+//! once it has expired, until a newer one comes. Without one, [`net::DEFAULT_RELAYS`](crate::net::DEFAULT_RELAYS).
+//! The daemon fetches it at start and every 6 hours; a new list applies when the network next starts (a restart, a
+//! join, a relay change), not to the running endpoint.
+
+use anyhow::{Result, anyhow, bail};
+use iroh::RelayUrl;
+use serde::Deserialize;
+use std::{path::Path, time::Duration};
+
+pub const URL: &str = "https://reasonmachines.com/network/relays.json";
+const TYPE: &str = "reason-network-relays";
+const ISSUER: &str = "https://reasonmachines.com/network/relays";
+const AUDIENCE: &str = "reason-network";
+/// Refused beyond this, served or cached.
+const MAX_BYTES: usize = 64 << 10;
+const MAX_RELAYS: usize = 16;
+/// A list fetched this long after it expired is still taken (clocks differ).
+const LEEWAY_SECS: i64 = 300;
+pub const EVERY: Duration = Duration::from_secs(6 * 3600);
+
+/// What is served: the list for people to read (ignored here), and the same list signed, which is what counts.
+#[derive(Deserialize)]
+struct Served {
+ signed: String,
+}
+
+#[derive(Deserialize)]
+struct Claims {
+ iss: String,
+ aud: String,
+ exp: i64,
+ relays: Vec<Entry>,
+}
+
+#[derive(Deserialize)]
+struct Entry {
+ url: String,
+}
+
+/// The relays in a served (or cached) document, checked; `now` (seconds) also checks it hasn't expired.
+fn parse(doc: &[u8], now: Option<i64>) -> Result<Vec<RelayUrl>> {
+ if doc.len() > MAX_BYTES {
+ bail!("the relay list is over {MAX_BYTES} bytes");
+ }
+ let served: Served = serde_json::from_slice(doc).map_err(|e| anyhow!("the relay list isn't one: {e}"))?;
+ let claims = crate::proof::verify_signed(&served.signed, TYPE, "relay list", MAX_BYTES)?;
+ let c: Claims = serde_json::from_slice(&claims).map_err(|e| anyhow!("the relay list is damaged: {e}"))?;
+ if c.iss != ISSUER || c.aud != AUDIENCE {
+ bail!("the relay list isn't Reason Network's");
+ }
+ if now.is_some_and(|now| c.exp.saturating_add(LEEWAY_SECS) <= now) {
+ bail!("the relay list expired");
+ }
+ if c.relays.is_empty() || c.relays.len() > MAX_RELAYS {
+ bail!("the relay list has {} relays (1 to {MAX_RELAYS} expected)", c.relays.len());
+ }
+ let mut out: Vec<RelayUrl> = Vec::new();
+ for e in c.relays {
+ let url: RelayUrl = e.url.parse().map_err(|_| anyhow!("not a relay url: {}", e.url))?;
+ if url.scheme() != "https" || url.host_str().is_none() {
+ bail!("not an https relay: {url}");
+ }
+ if out.contains(&url) {
+ bail!("{url} is in the relay list twice");
+ }
+ out.push(url);
+ }
+ Ok(out)
+}
+
+fn cache(home: &Path) -> std::path::PathBuf {
+ home.join("relays.json")
+}
+
+/// The cached list, if there is a good one (expired or not).
+fn cached(home: &Path) -> Option<Vec<RelayUrl>> {
+ parse(&std::fs::read(cache(home)).ok()?, None).ok()
+}
+
+/// The relays to use: the cached list, else the built-in default.
+pub fn current() -> Vec<RelayUrl> {
+ current_in(&crate::paths::home())
+}
+
+fn current_in(home: &Path) -> Vec<RelayUrl> {
+ cached(home).unwrap_or_else(crate::net::default_relays)
+}
+
+/// The same, fetching the list first (briefly) if none is cached yet: a machine's first network start.
+pub async fn current_or_fetch() -> Vec<RelayUrl> {
+ let home = crate::paths::home();
+ if cached(&home).is_none() {
+ match tokio::time::timeout(Duration::from_secs(10), refresh_in(&home, &url())).await {
+ Ok(Ok(())) => {}
+ Ok(Err(e)) => log(&format!("{e:#}")),
+ Err(_) => log("fetching the relay list timed out"),
+ }
+ }
+ current_in(&home)
+}
+
+/// Fetches the list and, if good, keeps it; says why not otherwise.
+pub async fn refresh() {
+ if let Err(e) = refresh_in(&crate::paths::home(), &url()).await {
+ log(&format!("{e:#}; keeping the relays this machine has"));
+ }
+}
+
+fn log(msg: &str) {
+ eprintln!("[{}] relays: {msg}", crate::util::now_ms());
+}
+
+async fn refresh_in(home: &Path, url: &str) -> Result<()> {
+ let doc = fetch(url).await?;
+ parse(&doc, Some(crate::util::now_ms() / 1000))?;
+ if std::fs::read(cache(home)).ok().as_deref() == Some(doc.as_slice()) {
+ return Ok(());
+ }
+ let tmp = home.join(format!("relays.json.{}.tmp", ulid::Ulid::new()));
+ std::fs::write(&tmp, &doc)?;
+ std::fs::rename(&tmp, cache(home))?;
+ Ok(())
+}
+
+/// [`URL`]; in debug builds, `REASON_NETWORK_RELAYS_URL` instead, for tests (release builds only ever fetch `URL`).
+fn url() -> String {
+ #[cfg(debug_assertions)]
+ if let Ok(u) = crate::paths::env_var("RELAYS_URL") {
+ return u;
+ }
+ URL.to_string()
+}
+
+/// The body at `url`, over HTTPS only (or plain HTTP for a debug build's test URL), following no redirect, of at most
+/// `MAX_BYTES`.
+async fn fetch(url: &str) -> Result<Vec<u8>> {
+ let proto = if cfg!(debug_assertions) && url != URL && !url.starts_with("https:") { "=http" } else { "=https" };
+ let max = MAX_BYTES.to_string();
+ let out = tokio::process::Command::new("curl")
+ .args(["-fsS", "--proto", proto, "--max-redirs", "0", "--max-time", "30", "--max-filesize", &max, "-w"])
+ .args(["%{response_code}", url])
+ .stdin(std::process::Stdio::null())
+ .kill_on_drop(true)
+ .output();
+ let out = tokio::time::timeout(Duration::from_secs(40), out).await??;
+ if !out.status.success() {
+ bail!("fetching {url}: {}", String::from_utf8_lossy(&out.stderr).trim());
+ }
+ // The status comes last: anything but 200 (a redirect, which isn't followed) is no list.
+ let mut body = out.stdout;
+ let code = body.split_off(body.len().saturating_sub(3));
+ if code != b"200" {
+ bail!("fetching {url}: HTTP {}", String::from_utf8_lossy(&code));
+ }
+ Ok(body)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::proof::tests::{KID, forger, sign_with, signer};
+ use serde_json::{Value, json};
+
+ fn now() -> i64 {
+ crate::util::now_ms() / 1000
+ }
+
+ fn region(r: &str) -> String {
+ format!("https://relay-{r}.compute.reasonmachines.com")
+ }
+
+ fn claims(urls: &[String]) -> Value {
+ let relays: Vec<Value> = urls.iter().map(|u| json!({"url": u, "region": "x"})).collect();
+ json!({"iss": ISSUER, "aud": AUDIENCE, "relays": relays, "iat": now(), "exp": now() + 30 * 86_400})
+ }
+
+ fn doc_with(header: Value, claims: Value) -> Vec<u8> {
+ let signed = sign_with(signer(), header, claims.clone());
+ serde_json::to_vec(&json!({"relays": claims["relays"], "signed": signed, "note": "extra fields are fine"}))
+ .unwrap()
+ }
+
+ fn doc(claims: Value) -> Vec<u8> {
+ doc_with(json!({"alg": "RS256", "kid": KID, "typ": TYPE}), claims)
+ }
+
+ fn four() -> Vec<String> {
+ ["sfo1", "iad1", "fra1", "sin1"].map(region).to_vec()
+ }
+
+ fn home() -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("reason-network-relays-{}", ulid::Ulid::new()));
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn a_signed_list_gives_its_relays_in_order() {
+ let got = parse(&doc(claims(&four())), Some(now())).unwrap();
+ assert_eq!(
+ got.iter().map(|u| u.to_string()).collect::<Vec<_>>(),
+ four().iter().map(|u| format!("{u}/")).collect::<Vec<_>>()
+ );
+ }
+
+ #[test]
+ fn any_fault_rejects_the_whole_list() {
+ let bad = |d: Vec<u8>| parse(&d, Some(now())).unwrap_err().to_string();
+ let with = |f: &dyn Fn(&mut Value)| {
+ let mut c = claims(&four());
+ f(&mut c);
+ doc(c)
+ };
+ let mut http = four();
+ http[2] = "http://relay-fra1.compute.reasonmachines.com".into();
+ assert!(bad(doc(claims(&http))).contains("not an https relay"));
+ assert!(bad(doc(claims(&["not a url".into()]))).contains("not a relay url"));
+ assert!(bad(doc(claims(&[]))).contains("has 0 relays"));
+ let many: Vec<String> = (0..17).map(|i| region(&format!("r{i}"))).collect();
+ assert!(bad(doc(claims(&many))).contains("has 17 relays"));
+ assert!(parse(&doc(claims(&many[..16])), Some(now())).is_ok(), "16 is fine");
+ let dup = [region("sfo1"), region("iad1"), format!("{}/", region("sfo1"))];
+ assert!(bad(doc(claims(&dup))).contains("twice"));
+ assert!(bad(b"{not json".to_vec()).contains("isn't one"));
+ assert!(bad(br#"{"relays":[{"url":"https://relay.example.com"}]}"#.to_vec()).contains("isn't one"), "unsigned");
+ let mut big = doc(claims(&four()));
+ big.splice(1..1, std::iter::repeat_n(b' ', MAX_BYTES));
+ assert!(bad(big).contains("over"));
+ assert!(bad(with(&|c| c["exp"] = json!(now() - LEEWAY_SECS - 1))).contains("expired"));
+ assert!(
+ bad(with(&|c| c["iss"] = json!("https://reasonmachines.com/network"))).contains("isn't Reason Network's")
+ );
+ assert!(bad(with(&|c| c["aud"] = json!("other"))).contains("isn't Reason Network's"));
+ // Signed by someone else, or the signed part swapped for another.
+ let forged = sign_with(forger(), json!({"alg": "RS256", "kid": KID, "typ": TYPE}), claims(&four()));
+ assert!(bad(serde_json::to_vec(&json!({"signed": forged})).unwrap()).contains("doesn't verify"));
+ }
+
+ #[test]
+ fn a_sign_in_proof_is_no_relay_list_nor_the_other_way_round() {
+ let me = iroh::SecretKey::generate().public();
+ let proof = crate::proof::tests::proof("u_1", "alex", &me);
+ let as_list = serde_json::to_vec(&json!({"signed": proof})).unwrap();
+ assert!(parse(&as_list, Some(now())).unwrap_err().to_string().contains("not a Reason Network relay list"));
+ // A relay list's signed part isn't a proof, even with a proof's claims in it; and those claims (the proof's
+ // issuer) make no relay list.
+ let mut c = crate::proof::tests::claims("u_1", "alex", &me);
+ c["relays"] = json!([{"url": region("sfo1")}]);
+ let list = sign_with(signer(), json!({"alg": "RS256", "kid": KID, "typ": TYPE}), c);
+ let err = crate::proof::verify(&list, &me).unwrap_err().to_string();
+ assert!(err.contains("not a Reason Network sign-in proof"), "{err}");
+ let err = parse(&serde_json::to_vec(&json!({"signed": list})).unwrap(), Some(now())).unwrap_err();
+ assert!(err.to_string().contains("isn't Reason Network's"), "{err}");
+ // Nor does a list signed as a proof pass as one.
+ let typ_proof = doc_with(json!({"alg": "RS256", "kid": KID, "typ": "reason-network-proof"}), claims(&four()));
+ assert!(parse(&typ_proof, Some(now())).unwrap_err().to_string().contains("not a Reason Network relay list"));
+ }
+
+ #[test]
+ fn the_cached_list_is_used_even_expired_and_the_default_without_one() {
+ let h = home();
+ assert_eq!(current_in(&h), crate::net::default_relays(), "nothing cached: the built-in default");
+ let mut c = claims(&four());
+ c["exp"] = json!(now() - 86_400);
+ std::fs::write(cache(&h), doc(c)).unwrap();
+ assert_eq!(current_in(&h).len(), 4, "expired, but the last good one");
+ std::fs::write(cache(&h), b"garbage").unwrap();
+ assert_eq!(current_in(&h), crate::net::default_relays(), "a damaged cache counts for nothing");
+ let _ = std::fs::remove_dir_all(&h);
+ }
+
+ /// Serves `responses` in turn on a local port, one connection each, as HTTP/1.0; its URL.
+ async fn serve(responses: Vec<(&'static str, Vec<u8>)>) -> String {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/network/relays.json", l.local_addr().unwrap());
+ tokio::spawn(async move {
+ for (status, body) in responses {
+ let (mut s, _) = l.accept().await.unwrap();
+ let _ = s.read(&mut [0; 4096]).await;
+ let head = format!(
+ "HTTP/1.0 {status}\r\nContent-Length: {}\r\nLocation: https://example.com/\r\n\r\n",
+ body.len()
+ );
+ let _ = s.write_all(&[head.as_bytes(), &body].concat()).await;
+ }
+ });
+ url
+ }
+
+ #[tokio::test]
+ async fn fetches_keeps_and_falls_back() {
+ let h = home();
+ let good = doc(claims(&four()));
+ let mut only_fra = claims(&[region("fra1")]);
+ only_fra["exp"] = json!(now() - 3600);
+ let url = serve(vec![
+ ("200 OK", good.clone()),
+ ("500 Oops", Vec::new()),
+ ("301 Moved", good.clone()),
+ ("200 OK", doc(claims(&[region("sfo1"), "http://relay.example.com".into()]))),
+ ("200 OK", doc(only_fra)),
+ ])
+ .await;
+ refresh_in(&h, &url).await.unwrap();
+ assert_eq!(std::fs::read(cache(&h)).unwrap(), good, "kept as served");
+ assert_eq!(current_in(&h).len(), 4);
+ assert!(refresh_in(&h, &url).await.is_err(), "a server error");
+ assert!(refresh_in(&h, &url).await.unwrap_err().to_string().contains("HTTP 301"), "no redirect followed");
+ assert!(refresh_in(&h, &url).await.unwrap_err().to_string().contains("https"), "a bad list");
+ assert!(refresh_in(&h, &url).await.unwrap_err().to_string().contains("expired"), "an expired one, fresh");
+ assert!(refresh_in(&h, &url).await.is_err(), "nobody there");
+ assert_eq!(std::fs::read(cache(&h)).unwrap(), good, "the last good list stays");
+ assert_eq!(std::fs::read_dir(&h).unwrap().count(), 1, "nothing but the list left behind");
+ let _ = std::fs::remove_dir_all(&h);
+ }
+}
diff --git a/src/render.rs b/src/render.rs
index 80026e5..7c5eb55 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -201,9 +201,9 @@ fn link(m: &MachineInfo, now: i64) -> String {
m.last_seen.map_or_else(|| "not seen yet".to_string(), |t| format!("offline {}", util::ago(t, now)))
}
-/// What a team that doesn't run its own relay uses.
+/// What a team that doesn't run its own relay uses: the nearest of Reason's (see `relays`).
pub fn default_relays() -> String {
- format!("{} (Reason's, the default)", crate::net::DEFAULT_RELAYS.join(", "))
+ "Reason's (the default)".into()
}
pub fn team(t: &TeamInfo) -> String {
@@ -410,10 +410,7 @@ mod tests {
machines: Vec::new(),
features: Vec::new(),
};
- assert_eq!(
- team(&t),
- "team vibes · relay: https://relay-sfo1.compute.reasonmachines.com (Reason's, the default)\n"
- );
+ assert_eq!(team(&t), "team vibes · relay: Reason's (the default)\n");
t.relay = Some("https://relay.example.com".into());
assert_eq!(team(&t), "team vibes · relay: https://relay.example.com\n");
}
diff --git a/src/team.rs b/src/team.rs
index 0bbe409..e46dada 100644
--- a/src/team.rs
+++ b/src/team.rs
@@ -46,7 +46,7 @@ impl<T: Serialize> Signed<T> {
pub struct Meta {
pub name: String,
/// A self-hosted iroh relay for the team (`https://relay.example.com`), which is then all its machines use: they
- /// never contact n0. The default relays otherwise (`net::DEFAULT_RELAYS`; an older Reason Network uses n0's).
+ /// never contact n0. Reason's otherwise (see `relays`; an older Reason Network uses n0's).
pub relay: Option<String>,
pub ts: i64,
}
diff --git a/tests/e2e/regional_relays.py b/tests/e2e/regional_relays.py
new file mode 100644
index 0000000..c46845d
--- /dev/null
+++ b/tests/e2e/regional_relays.py
@@ -0,0 +1,144 @@
+"""Reason's relay list: two machines homed on different regional relays still join and talk, and a team's own relay
+still wins over the list. Each machine gets its own signed list from a local server (REASON_NETWORK_RELAYS_URL, which
+debug builds honor), so alex knows only sfo1 and bea only fra1.
+
+ cargo build && env -u CLAUDE_CODE_MESSAGING_SOCKET python3 tests/e2e/regional_relays.py
+
+Needs internet (Reason's live relays, n0's address lookup).
+"""
+import base64, http.server, json, os, re, subprocess, sys, tempfile, threading, time
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from proofs import KID, REASON, TRUST, b64, proof, sign
+
+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+BIN = os.environ.get("REASON_NETWORK_TEST_BIN", os.path.join(ROOT, "target", "debug", "reason-network"))
+D = tempfile.mkdtemp(prefix="reason-network-relays-")
+FAKE_BIN = os.path.join(D, "bin")
+UNEXPECTED = os.path.join(D, "unexpected.log")
+RELAY = {r: f"https://relay-{r}.compute.reasonmachines.com" for r in ("sfo1", "iad1", "fra1", "sin1")}
+# Who knows which relays; carl's team runs its own (sin1), which must win over his list (fra1).
+WHO = {"alex": ("laptop", ["sfo1"]), "bea": ("desk", ["fra1"]), "carl": ("box", ["fra1"])}
+results = []
+
+
+def check(name, ok, detail=""):
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'}: {name}" + ("" if ok else f"\n {detail}"))
+
+
+def relay_list(regions):
+ """relays.json as Reason serves it: the list, and the same list signed."""
+ relays = [{"url": RELAY[r], "region": r} for r in regions]
+ now = int(time.time())
+ claims = {"iss": "https://reasonmachines.com/network/relays", "aud": "reason-network", "relays": relays,
+ "iat": now, "exp": now + 30 * 86400}
+ head = {"alg": "RS256", "kid": KID, "typ": "reason-network-relays"}
+ signing = f"{b64(json.dumps(head).encode())}.{b64(json.dumps(claims).encode())}"
+ return json.dumps({"relays": relays, "signed": f"{signing}.{b64(sign(REASON, signing.encode()))}"}).encode()
+
+
+LISTS = {f"/{w}.json": relay_list(regions) for w, (_, regions) in WHO.items()}
+
+
+class Lists(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ body = LISTS.get(self.path)
+ self.send_response(200 if body else 404)
+ self.send_header("Content-Length", str(len(body or b"")))
+ self.end_headers()
+ self.wfile.write(body or b"")
+
+ def log_message(self, *args):
+ pass
+
+
+server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Lists)
+threading.Thread(target=server.serve_forever, daemon=True).start()
+
+
+def env(who):
+ e = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE")}
+ e.update(HOME=os.path.join(D, "home"), PATH=FAKE_BIN + os.pathsep + os.environ["PATH"], CLAUDE_CONFIG_DIR=os.path.join(D, "claude"),
+ REASON_NETWORK_HOME=os.path.join(D, who), REASON_NETWORK_MACHINE=WHO[who][0], REASON_NETWORK_NO_MDNS="1",
+ REASON_NETWORK_NO_SERVICE="1", REASON_NETWORK_NO_UPDATE="1", REASON_NETWORK_NO_TRAY="1",
+ REASON_NETWORK_TRUST_KEYS=TRUST, REASON_NETWORK_RELAYS_URL=f"http://127.0.0.1:{server.server_port}/{who}.json")
+ return e
+
+
+def cli(who, *args):
+ r = subprocess.run([BIN, *args], env=env(who), capture_output=True, text=True, timeout=90)
+ return (r.stdout + r.stderr).strip()
+
+
+def until(who, args, ok, secs=60):
+ deadline = time.time() + secs
+ while True:
+ out = cli(who, *args)
+ if ok(out) or time.time() > deadline:
+ return out
+ time.sleep(1)
+
+
+def link_relays(out):
+ """A team link's relay fields: the team's own, and the inviting machine's home relay."""
+ t = re.search(r"#rn1-(\S+)", out).group(1)
+ raw, at, fields = base64.urlsafe_b64decode(t + "=" * (-len(t) % 4)), 32, []
+ for _ in range(3): # the team name first
+ short = raw[at] == 0xFF
+ at += short
+ fields.append(raw[at + 1:at + 1 + raw[at]].decode())
+ at += 1 + raw[at]
+ return fields[1:]
+
+
+def logged(who):
+ p = os.path.join(D, who, "daemon.log")
+ return open(p, errors="replace").read() if os.path.exists(p) else ""
+
+
+os.makedirs(FAKE_BIN)
+os.makedirs(os.path.join(D, "home"))
+for name in ("open", "xdg-open", "osascript", "notify-send"):
+ with open(os.path.join(FAKE_BIN, name), "w") as f:
+ f.write(f'#!/bin/sh\nprintf "{name} %s\\n" "$*" >> {UNEXPECTED}\n')
+ os.chmod(os.path.join(FAKE_BIN, name), 0o755)
+
+try:
+ ep = {w: cli(w, "endpoint") for w in WHO}
+ out = cli("alex", "init", "regions", "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")
+ check("alex starts a team", "You are alex on laptop." in out, out)
+ check("…and keeps the list he was served", os.path.exists(os.path.join(D, "alex", "relays.json")), os.listdir(os.path.join(D, "alex")))
+ out = cli("alex", "link")
+ check("alex is homed on sfo1, the only relay his list has", link_relays(out) == ["", RELAY["sfo1"] + "/"], out)
+ out = cli("bea", "join", re.search(r"https://\S+/join/#\S+", out).group(0), "--proof", proof("u_bea", "bea", ep["bea"]), "--no-setup")
+ check("bea, who knows only fra1, joins through alex on sfo1", "Joined team regions as bea on desk." in out, out)
+ out = until("bea", ["link"], lambda o: link_relays(o)[1] == RELAY["fra1"] + "/")
+ check("bea is homed on fra1", link_relays(out) == ["", RELAY["fra1"] + "/"], out)
+ out = until("alex", ["team"], lambda o: re.search(r"bea \(verified\)\s+desk\s+(direct|relay)", o))
+ check("alex sees bea connected", re.search(r"bea \(verified\)\s+desk\s+(direct|relay)", out) is not None, out)
+ out = until("bea", ["team"], lambda o: re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", o))
+ check("bea sees alex connected", re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", out) is not None, out)
+ cli("alex", "listen", "--as", "t", "--wait", "0")
+ cli("bea", "listen", "--as", "t", "--wait", "0")
+ out = until("alex", ["send", "bea/t", "--from", "alex/t", "hello from sfo1"], lambda o: "→ bea/t" in o and "no session" not in o)
+ check("alex sends to bea", "→ bea/t" in out, out)
+ out = cli("bea", "listen", "--as", "t", "--wait", "15")
+ check("…who gets it", "hello from sfo1" in out, out)
+ cli("bea", "send", "alex/t", "--from", "bea/t", "hello from fra1")
+ out = cli("alex", "listen", "--as", "t", "--wait", "15")
+ check("and back", "hello from fra1" in out, out)
+
+ # A team's own relay wins: carl's list says fra1, his team says sin1.
+ out = cli("carl", "init", "own", "--relay", RELAY["sin1"], "--proof", proof("u_carl", "carl", ep["carl"]), "--no-setup")
+ check("carl starts a team on its own relay", "You are carl on box." in out, out)
+ out = until("carl", ["link"], lambda o: link_relays(o)[1] != "")
+ check("…which is where he is, not on his list's", link_relays(out) == [RELAY["sin1"], RELAY["sin1"] + "/"], out)
+ check("no list was turned down", all("relays:" not in logged(w) for w in WHO), [logged(w)[-1500:] for w in WHO])
+finally:
+ for w in WHO:
+ subprocess.run([BIN, "stop"], env=env(w), capture_output=True, timeout=30)
+ server.shutdown()
+log = open(UNEXPECTED).read() if os.path.exists(UNEXPECTED) else ""
+check("nothing opened a browser or reached the real notifications", log == "", log)
+print(f"\n{sum(results)}/{len(results)} checks passed (state in {D})")
+raise SystemExit(0 if all(results) else 1)
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index cff5029..b3f4788 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -160,8 +160,9 @@ out = cli("alice", "team")
check("joiner sees alex connected, verified", re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", out) is not None, out)
out = cli("alex", "team")
check("founder sees alice connected, verified", re.search(r"alice \(verified\)\s+desktop\s+(direct|relay)", out) is not None, out)
-check("a team without a relay of its own is on Reason's: the link names it as where alex is",
- link_relays(link.group(1)) == ["", "https://relay-sfo1.compute.reasonmachines.com/"] and "(Reason's, the default)" in out, out)
+check("a team without a relay of its own is on Reason's: the link names the one alex is on",
+ link_relays(link.group(1))[0] == "" and re.fullmatch(r"https://relay-\w+\.compute\.reasonmachines\.com/", link_relays(link.group(1))[1])
+ and "relay: Reason's (the default)" in out, out)
j = as_json(cli("alex", "team", "--json"))
check("team --json marks people verified, and each machine's proof", [(m["verified"], m["has_proof"]) for m in j.get("members", [])] == [(True, True)] * 2
and j.get("link", "").startswith("https://") and j.get("team_name") == "vibes" and len(j.get("team_id", "")) == 32, j)