Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
Reason sign-in: verified names, rn1 links, invite line
Lars Talian0154a0268ec0
diff --git a/DESIGN.md b/DESIGN.mdindex 7223540..d152fa3 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -116,7 +116,20 @@ The link secret is a reusable invite in the team state (any member can show theredeem it), replaced with `reason-network link --new` and whenever someone is removed; removed machines are never sent it.The page shows one command (`curl … install.sh | sh -s -- <ticket>`); the joiner only types a name. Four-wordone-time codes (`reason-network invite --code`, ~41 bits) derive a temporary iroh key the inviting machine listens on, for-reading out loud or adding your own machines.+reading out loud or adding your own machines. A code doesn't name the team, so the joiner checks the team it is handed+holds the code's invite, signed by a member and used by the joiner. Links are `rn1-…` (older builds wrote `tincan1…`,+with the same payload; both are read). After `init` and `join` the CLI prints the invite line,+`Join the Reason Network: <team link>`, and agents get it from `list_team`.++**Sign-in proofs.** Signed in with Reason, a machine carries a proof: a compact JWS (Ed25519) from Reason saying+this endpoint id belongs to account `sub`, named `name`, until `exp` (`init`/`join --proof`, `reason-network proof`+to refresh). The engine checks it against Reason's public keys, compiled in, and never calls Reason. Proofs travel in+the team state's `attestations` (endpoint → JWS), outside the signed entries, so builds without them pass the rest+on unchanged; each machine checks every proof itself and drops the ones that don't verify. A person whose machine+has a valid proof for their name shows as verified. With a proof, the name is the proof's; a verified name can't be+taken by anyone but another computer of the same account (which any member may let in through the team link).+`--json` on `init`, `join`, `link` and `team` is for the Reason CLI, which signs people in; a taken name is+`{"error":"name_taken"}`.**Presence and directory.** Daemons keep a connection to every online member (full mesh; fine to ~50machines). On connect they exchange roster heads (anti-entropy) and full presence. On any local change adiff --git a/README.md b/README.mdindex 9fbb325..ce09014 100644--- a/README.md+++ b/README.md@@ -54,7 +54,7 @@ reason-network send alice/api-claude "did the token format change?" # messagereason-network send alice/api-claude --notify "approve the deploy?" # and pop it up on alice's screenreason-network send '*' "deploying api at 5" # everyone (or alice/*, repo:api): from you, never an agentreason-network listen --as terminal # replies to what you sent from this terminal-reason-network link # the team link again+reason-network link # the invite line again: Join the Reason Network: <link>reason-network setup # which agents are on it, and how messages are handled```@@ -70,13 +70,14 @@ computers never contact n0 at all. Only team members can connect, and a computerMessages to someone offline wait and go out when they're back.Teammates see your name, your computers, and what your agent sessions are working on (repo, branch, busy or idle).-State lives in `~/.reason/network`. Details: [DESIGN.md](DESIGN.md).+Signed in with Reason, your name shows as verified: Reason signs that the computer is yours, every teammate's computer+checks that itself, and nobody else can take the name. State lives in `~/.reason/network`. Details: [DESIGN.md](DESIGN.md).## For AI agents-If your user gave you a Reason Network team link (`https://…/network/join/#tincan1…`) and wants to join: ask them-what name teammates should see, then run this with the whole link, exactly as given (first check it ends in `#tincan1`-followed only by letters, digits, `-` and `_`). It asks no questions and needs no account:+If your user gave you a Reason Network team link (`https://…/network/join/#rn1-…`) and wants to join: ask them+what name teammates should see, then run this with the whole link, exactly as given (first check it ends in `#rn1-`,+or `#tincan1` in older links, followed only by letters, digits, `-` and `_`). It asks no questions and needs no account:```shcurl -fsSL https://github.com/reason-machines/reason-network/releases/latest/download/install.sh | sh -s -- '<the whole link>' --as <name>diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex 9a1871d..c03c181 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -273,6 +273,7 @@ impl Daemon {machine: self.machine.clone(),machines,sessions: rows,+ invite_line: self.current_link().map(|l| crate::invite_line(&l)),})}diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex 2fc06ec..20d12b8 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -153,7 +153,7 @@ struct Live {stop_gen: u64,}-fn load_key() -> Result<SecretKey> {+pub fn load_key() -> Result<SecretKey> {let path = paths::home().join("machine.key");if let Ok(bytes) = std::fs::read(&path) {let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| anyhow!("{} is corrupt", path.display()))?;@@ -295,8 +295,11 @@ impl Daemon {}Request::Hook(h) => json!(self.hook(h).await?),Request::Attach { agent, cwd } => json!(self.attach(&agent, &cwd)),- Request::CreateTeam { name, person, relay } => json!(self.create_team(&name, &person, relay).await?),- Request::Join { ticket, person } => json!(self.join_team(&ticket, &person).await?),+ Request::CreateTeam { name, person, relay, proof } => {+ json!(self.create_team(&name, &person, relay, proof).await?)+ }+ Request::Join { ticket, person, proof } => json!(self.join_team(&ticket, &person, proof).await?),+ Request::Proof { jws } => json!(self.attach_proof(&jws)?),Request::Invite { me, hours } => json!(self.invite(me, hours).await?),Request::Team => json!(self.team_info()?),Request::Link { new } => json!(self.link(new).await?),diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rsindex fa08a62..c7b20c2 100644--- a/src/daemon/teamops.rs+++ b/src/daemon/teamops.rs@@ -6,8 +6,9 @@ use crate::{config::Config,invite,net::{self, JoinRequest, Net, Remote, Wire},+ proof,proto::*,- team::{TeamState, Ticket},+ team::{self, TeamState, Ticket},util,};use anyhow::{Result, anyhow, bail};@@ -144,7 +145,9 @@ impl Daemon {/// Someone presented an invite (on the join protocol).pub fn redeem(self: &Arc<Self>, joiner: EndpointId, req: &JoinRequest) -> Result<TeamState> {- let person = util::slug(&req.person);+ // Signed in to Reason: the name is the one Reason gave.+ let proof = req.proof.as_deref().map(|p| proof::verify(p, &joiner)).transpose()?;+ let person = proof.as_ref().map_or_else(|| util::slug(&req.person), |p| p.name.clone());let machine = util::slug(&req.machine);if person.is_empty() || machine.is_empty() {bail!("a name needs letters or digits");@@ -155,7 +158,10 @@ impl Daemon {if !req.team.is_empty() && req.team != team.id {bail!("this invite is for a different team");}- team.redeem(&self.key, &req.secret, &person, joiner)?;+ team.redeem(&self.key, &req.secret, &person, joiner, proof.as_ref())?;+ if let Some(p) = &req.proof {+ team.attest(&joiner, p);+ }team.put_member(&self.key, joiner, &person, &machine, true);let state = team.clone();self.save_team(&g)?;@@ -174,15 +180,21 @@ impl Daemon {name: &str,person: &str,relay: Option<String>,+ proof: Option<String>,) -> Result<TeamInfo> {if let Some(t) = self.team_state() {bail!("already in team '{}'; run `{CLI} leave` first", t.name());}- let (name, person) = (name.trim(), util::slug(person));+ let checked = proof.as_deref().map(|p| proof::verify(p, &self.key.public())).transpose()?;+ let name = name.trim();+ let person = checked.map_or_else(|| util::slug(person), |p| p.name);if name.is_empty() || person.is_empty() {bail!("the team and your name need letters or digits");}let mut state = TeamState::found(name, &person, &self.machine, &self.key);+ if let Some(p) = &proof {+ state.attest(&self.key.public(), p);+ }if let Some(u) = &relay {net::check_relay(self.key.clone(), u).await?;state.set_relay(&self.key, relay.clone());@@ -195,6 +207,7 @@ impl Daemon {self.become_person(&person)?;self.restart_soon();Ok(TeamInfo {+ id: self.team_id().unwrap_or_default(),name: name.into(),relay,relay_connected: None,@@ -204,8 +217,16 @@ impl Daemon {})}- /// Joins with an invite code (`plum-tiger-lake-orbit`) or a long `tincan1…` ticket.- pub(super) async fn join_team(self: &Arc<Self>, invite_text: &str, person: &str) -> Result<TeamInfo> {+ /// Joins with an invite code (`plum-tiger-lake-orbit`) or a team link (`rn1-…`, or an older `tincan1…`).+ pub(super) async fn join_team(+ self: &Arc<Self>,+ invite_text: &str,+ person: &str,+ proof: Option<String>,+ ) -> Result<TeamInfo> {+ // A proof that doesn't verify here won't anywhere: say so before leaving anything.+ let checked = proof.as_deref().map(|p| proof::verify(p, &self.key.public())).transpose()?;+ let person = checked.map_or_else(|| person.to_string(), |p| p.name);let mut solo = false;if let Some(t) = self.team_state() {let me = self.key.public();@@ -225,14 +246,14 @@ impl Daemon {net.shutdown().await;}}- let res = self.join_with(invite_text, person).await;+ let res = self.join_with(invite_text, &person, proof).await;if res.is_err() && solo {let _ = self.start_net().await;}res}- async fn join_with(self: &Arc<Self>, invite_text: &str, person: &str) -> Result<TeamInfo> {+ async fn join_with(self: &Arc<Self>, invite_text: &str, person: &str, proof: Option<String>) -> Result<TeamInfo> {let person = util::slug(person);if person.is_empty() {bail!("your name needs letters or digits");@@ -242,7 +263,7 @@ impl Daemon {Some(code) => {(String::new(), invite::secret(&code), None, vec![EndpointAddr::new(invite::key(&code).public())])}- None if invite_text.contains("tincan1") => {+ None if Ticket::is_ticket(invite_text) => {let t = Ticket::decode(invite_text)?;let addrs = t.addrs();(t.team, t.secret, t.relay, addrs)@@ -250,14 +271,26 @@ impl Daemon {None => bail!("that's not an invite code (four words, like plum-tiger-lake-orbit)"),};let endpoint = net::bind(self.key.clone(), relay.as_deref(), self.cfg.lan()).await?;- let req = JoinRequest { team: team.clone(), secret, person: person.clone(), machine: self.machine.clone() };+ let req = JoinRequest {+ team: team.clone(),+ secret: secret.clone(),+ person: person.clone(),+ machine: self.machine.clone(),+ proof: proof.clone(),+ };let res = net::join(&endpoint, &peers, &req).await;endpoint.close().await;- let state = TeamState::verified(&res?)?;- if (!team.is_empty() && state.id != team) || !state.is_active(&self.key.public()) {+ let mut state = TeamState::verified(&res?)?;+ let me = self.key.public();+ if !handed_the_invited_team(&state, &team, &secret, &me) {bail!("the team did not add this machine");}+ // An inviting machine from before sign-in proofs passes ours over: it goes out with this machine's state.+ if let Some(p) = &proof {+ state.attest(&me, p);+ }let info = TeamInfo {+ id: state.id.clone(),name: state.name().into(),relay: state.meta.body.relay.clone(),relay_connected: None,@@ -275,6 +308,29 @@ impl Daemon {Ok(info)}+ /// Attaches (or refreshes) this machine's Reason sign-in proof, for its teammates to check.+ pub(super) fn attach_proof(self: &Arc<Self>, jws: &str) -> Result<String> {+ let me = self.key.public();+ let p = proof::verify(jws, &me)?;+ let state = {+ let mut g = self.inner.lock().unwrap();+ let team = g.team.as_mut().ok_or_else(|| anyhow!("not in a team yet: run `{CLI}`"))?;+ let person = team.member(&me).map(|m| m.person.clone()).unwrap_or_default();+ if p.name != person {+ bail!("this proof is for {}, but this machine is {person} in the team", p.name);+ }+ team.attest(&me, jws);+ let state = team.clone();+ self.save_team(&g)?;+ state+ };+ if let Some(net) = self.net() {+ net.broadcast(&Wire::State { state: Box::new(state) });+ }+ let days = (p.exp - util::now_ms() / 1000) / 86_400;+ Ok(format!("{} on {} is verified, for {days} more days.", p.name, self.machine))+ }+fn become_person(&self, person: &str) -> Result<()> {let mut cfg =Config::load_strict().map_err(|e| anyhow!("fix {} first: {e}", crate::paths::config().display()))?;@@ -359,11 +415,19 @@ impl Daemon {Ok(LinkInfo { team: state.name().into(), url: crate::join_url(&ticket), ticket })}+ /// The team link as it is now, without making one (for `list_team`).+ pub(super) fn current_link(&self) -> Option<String> {+ let state = self.team_state()?;+ let secret = state.link_secret()?.to_string();+ Some(crate::join_url(&self.ticket(&state, secret).encode()))+ }+pub(super) fn team_info(&self) -> Result<TeamInfo> {let team = self.team_state().ok_or_else(|| anyhow!("not in a team yet: `{CLI} init <team>` or `{CLI} join <invite>`"))?;Ok(TeamInfo {+ id: team.id.clone(),name: team.name().into(),relay: team.meta.body.relay.clone(),relay_connected: self.net().map(|n| n.relay_connected()),@@ -385,10 +449,12 @@ impl Daemon {link: None,rtt_ms: None,last_seen: None,+ verified: false,};let (Some(team), net) = (self.team_state(), self.net()) else { return vec![here] };+ let verified = team.verified_people();let remotes = net.as_ref().map(|n| n.remotes()).unwrap_or_default();- let mut out = vec![here];+ let mut out = vec![MachineInfo { verified: verified.contains_key(&here.person), ..here }];for m in team.active().filter(|m| m.endpoint != me) {let link = net.as_ref().and_then(|n| n.link_info(&m.endpoint));out.push(MachineInfo {@@ -400,6 +466,7 @@ impl Daemon {link: link.as_ref().map(|l| if l.relay { "relay" } else { "direct" }.to_string()),rtt_ms: link.map(|l| l.rtt_ms),last_seen: remotes.get(&m.endpoint).map(|r| r.last_seen).filter(|t| *t > 0),+ verified: verified.contains_key(&m.person),});}out[1..].sort_by(|a, b| (&a.person, &a.machine).cmp(&(&b.person, &b.machine)));@@ -523,3 +590,47 @@ impl Daemon {Ok(out)}}++/// Whether the team a joiner was handed is the one it was invited to: the one a team link names, holding the invite it+/// presented (for a code, the only thing that names the team), signed by a member, and letting this machine in.+fn handed_the_invited_team(state: &TeamState, team: &str, secret: &str, me: &EndpointId) -> bool {+ let invited =+ state.invites.get(&team::hash(secret)).is_some_and(|i| i.body.reusable || i.body.used_by == Some(*me));+ (team.is_empty() || state.id == team) && invited && state.is_active(me)+}++#[cfg(test)]+mod tests {+ use super::*;+ use iroh::SecretKey;++ #[test]+ fn a_code_joiner_checks_the_team_it_is_handed() {+ let (a, me) = (SecretKey::generate(), SecretKey::generate());+ let code = invite::generate();+ let secret = invite::secret(&code);+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ s.invite(&a, &secret, 24, None);+ s.redeem(&a, &secret, "sam", me.public(), None).unwrap();+ s.put_member(&a, me.public(), "sam", "nuc", true);+ let handed = TeamState::verified(&s).unwrap();+ assert!(handed_the_invited_team(&handed, "", &secret, &me.public()));+ assert!(handed_the_invited_team(&handed, &s.id, &secret, &me.public()));+ assert!(!handed_the_invited_team(&handed, "00112233445566778899aabbccddeeff", &secret, &me.public()));+ // Some other team, with this machine in it but not the invite (whoever answered on the code's key made it up).+ let mut other = TeamState::found("not yours", "mallory", "evil", &a);+ other.put_member(&a, me.public(), "sam", "nuc", true);+ let other = TeamState::verified(&other).unwrap();+ assert!(other.is_active(&me.public()));+ assert!(!handed_the_invited_team(&other, "", &secret, &me.public()), "the code's invite isn't in it");+ // The invite, but used by another machine.+ let mut used = TeamState::found("vibes", "alex", "mbp", &a);+ used.invite(&a, &secret, 24, None);+ used.redeem(&a, &secret, "eve", SecretKey::generate().public(), None).unwrap();+ used.put_member(&a, me.public(), "sam", "nuc", true);+ assert!(!handed_the_invited_team(&TeamState::verified(&used).unwrap(), "", &secret, &me.public()));+ // A team link's invite is reusable.+ let link = s.link_secret().unwrap().to_string();+ assert!(handed_the_invited_team(&handed, &s.id, &link, &me.public()));+ }+}diff --git a/src/main.rs b/src/main.rsindex b3e5b9d..9f25ba4 100644--- a/src/main.rs+++ b/src/main.rs@@ -12,6 +12,7 @@ mod mcp;mod migrate;mod net;mod paths;+mod proof;mod proto;mod render;mod setup;@@ -101,6 +102,11 @@ pub fn join_url(ticket: &str) -> String {format!("{SITE_URL}/join/#{ticket}")}+/// The invite line: what a person pastes to their agent to join the team.+pub fn invite_line(link: &str) -> String {+ format!("Join the Reason Network: {link}")+}+#[derive(Parser)]#[command(name = "reason-network",@@ -162,6 +168,12 @@ enum Cmd {/// Your own iroh relay, from the start (see `relay`)#[arg(long)]relay: Option<String>,+ /// This machine's Reason sign-in proof: your name is then the one it gives+ #[arg(long)]+ proof: Option<String>,+ /// Print the result as JSON+ #[arg(long)]+ json: bool,},/// Show the team link to send friends (or, with --me / --code, a one-time code)Invite {@@ -180,6 +192,8 @@ enum Cmd {/// Replace it: the old link stops working#[arg(long)]new: bool,+ #[arg(long)]+ json: bool,},/// Join a team with a team link (or an invite code)Join {@@ -189,9 +203,22 @@ enum Cmd {person: Option<String>,#[arg(long)]no_setup: bool,+ /// This machine's Reason sign-in proof: your name is then the one it gives+ #[arg(long)]+ proof: Option<String>,+ /// Print the result as JSON+ #[arg(long)]+ json: bool,},/// Show the team's people and machines, and how each is reached- Team,+ Team {+ #[arg(long)]+ json: bool,+ },+ /// Attach or refresh this machine's Reason sign-in proof, which verifies your name to teammates+ Proof { jws: String },+ /// Print this machine's endpoint id (what a sign-in proof names)+ Endpoint,/// Remove a person (all their machines) or one machine from the teamRemove { who: String },/// Leave the team on this machine@@ -279,6 +306,11 @@ async fn main() -> Result<()> {Some(Cmd::Mcp) => mcp::run().await,// Blocks this (the main) thread with AppKit's event loop; its daemon calls run on the runtime's workers.Some(Cmd::Tray) => tray::run(),+ Some(Cmd::Endpoint) => {+ paths::ensure_home()?;+ println!("{}", daemon::load_key()?.public());+ Ok(())+ }Some(Cmd::Hook { agent, event, session, state, doing }) => {hook::run(&agent, &event, session, state, doing).await;// Don't wait on anything left behind (a stuck stdin read): the agent is waiting on us.@@ -398,46 +430,61 @@ async fn cli(cmd: Cmd) -> Result<()> {let r: Registered = link.call(Request::SetStatus { key, doing, name }).await?;println!("You are {}.", r.address);}- Cmd::Init { team, person, no_setup, relay: None } if !no_setup && wizard::interactive() => {+ Cmd::Init { team, person, no_setup: false, relay: None, proof: None, json: false } if wizard::interactive() => {wizard::guided(wizard::onboard(Some(true), team, None, person)).await?}- Cmd::Join { invite, person, no_setup } if !no_setup && wizard::interactive() => {+ Cmd::Join { invite, person, no_setup: false, proof: None, json: false } if wizard::interactive() => {wizard::guided(wizard::onboard(Some(false), None, invite, person)).await?}Cmd::Invite { me: false, code: false, .. } if wizard::interactive() => wizard::guided(wizard::invite()).await?,- Cmd::Link { new } => {+ Cmd::Link { new, json } => {let l: LinkInfo = link.call(Request::Link { new }).await?;- let copied = wizard::interactive() && wizard::copy(&l.url);- println!("Team link for {}{}:\n\n{}\n", l.team, if copied { " (on your clipboard)" } else { "" }, l.url);+ if json {+ println!("{}", serde_json::to_string_pretty(&team_json(&link, None).await?)?);+ return Ok(());+ }+ let line = invite_line(&l.url);+ let copied = wizard::interactive() && wizard::copy(&line);+ println!("Team link for {}{}:\n\n{line}\n", l.team, if copied { " (on your clipboard)" } else { "" });println!("Anyone with it can join: it opens a page with one command. `{CLI} link --new` replaces it.");if managed() {println!("Teammates in your Reason workspace just run `reason network`; the link is for anyone else.");}}- Cmd::Invite { me: false, code: false, .. } => Box::pin(cli(Cmd::Link { new: false })).await?,+ Cmd::Invite { me: false, code: false, .. } => Box::pin(cli(Cmd::Link { new: false, json: false })).await?,Cmd::Setup { dry_run: false, remove: false, no_service: false } if wizard::interactive() => {wizard::guided(wizard::setup_agents()).await?}- Cmd::Init { team, person, no_setup, relay } => {+ Cmd::Init { team, person, no_setup, relay, proof, json } => {let Some(team) = team else {bail!("name the team: `{CLI} init <team>` (or run it in a terminal to be asked)")};- let t: TeamInfo =- link.call(Request::CreateTeam { name: team, person: default_person(person), relay }).await?;+ let req = Request::CreateTeam { name: team, person: default_person(person), relay, proof };+ let t: TeamInfo = link.call(req).await.or_else(|e| json_error(json, e))?;wait_exit(daemon_pid()).await;+ if json {+ let agents = if no_setup { None } else { Some(setup::quietly().await?) };+ println!("{}", serde_json::to_string_pretty(&team_json(&Link::new(None), agents).await?)?);+ return Ok(());+ }println!("Created team {}. You are {} on {}.", t.name, t.person, t.machine);if !no_setup {println!();setup::run(false, false, false).await?;}- println!("\nNext: `{CLI} link` prints the team link to send your teammates.");+ let l: LinkInfo = Link::new(None).call(Request::Link { new: false }).await?;+ println!("\nInvite people with this line:\n{}", invite_line(&l.url));}- Cmd::Join { invite, person, no_setup } => {+ Cmd::Join { invite, person, no_setup, proof, json } => {let Some(invite) = invite else { bail!("give the invite code: `{CLI} join <code>`") };- let t: TeamInfo = link.call(Request::Join { ticket: invite, person: default_person(person) }).await?;+ let req = Request::Join { ticket: invite, person: default_person(person), proof };+ let t: TeamInfo = link.call(req).await.or_else(|e| json_error(json, e))?;wait_exit(daemon_pid()).await;- println!("Joined team {} as {} on {}.", t.name, t.person, t.machine);- if !no_setup {+ let agents = if no_setup || !json { None } else { Some(setup::quietly().await?) };+ if !json {+ println!("Joined team {} as {} on {}.", t.name, t.person, t.machine);+ }+ if !no_setup && !json {println!();setup::run(false, false, false).await?;}@@ -451,9 +498,16 @@ async fn cli(cmd: Cmd) -> Result<()> {break;}}+ if json {+ println!("{}", serde_json::to_string_pretty(&team_json(&fresh, agents).await?)?);+ return Ok(());+ }if let Ok(t) = fresh.call::<TeamInfo>(Request::Team).await {print!("\n{}", render::team(&t));}+ if let Ok(l) = fresh.call::<LinkInfo>(Request::Link { new: false }).await {+ println!("\nInvite people with this line:\n{}", invite_line(&l.url));+ }}Cmd::Invite { me, hours, .. } => {let i: InviteInfo = link.call(Request::Invite { me, hours: hours.clamp(1, 24 * 30) }).await?;@@ -499,10 +553,12 @@ async fn cli(cmd: Cmd) -> Result<()> {let _ = cli_session(&link, &id, "prompt").await;}}- Cmd::Team => {+ Cmd::Team { json: true } => println!("{}", serde_json::to_string_pretty(&team_json(&link, None).await?)?),+ Cmd::Team { json: false } => {let t: TeamInfo = link.call(Request::Team).await?;print!("{}", render::team(&t));}+ Cmd::Proof { jws } => println!("{}", link.call::<String>(Request::Proof { jws }).await?),Cmd::Remove { who } => println!("{}", link.call::<String>(Request::Remove { who }).await?),Cmd::Leave { force } => {println!("{}", link.call::<String>(Request::Leave { force }).await?);@@ -556,11 +612,48 @@ async fn cli(cmd: Cmd) -> Result<()> {println!("The daemon is not running.");}}- Cmd::Daemon { .. } | Cmd::Mcp | Cmd::Hook { .. } | Cmd::Tray => unreachable!("handled in main"),+ Cmd::Daemon { .. } | Cmd::Mcp | Cmd::Hook { .. } | Cmd::Tray | Cmd::Endpoint => {+ unreachable!("handled in main")+ }}Ok(())}+/// The team as `--json` gives it, for the Reason CLI: `set_up_for` names the agents set up, when setup ran.+async fn team_json(link: &std::sync::Arc<Link>, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {+ let t: TeamInfo = link.call(Request::Team).await?;+ let l: LinkInfo = link.call(Request::Link { new: false }).await?;+ let endpoint = t.machines.iter().find(|m| m.is_me).map(|m| m.endpoint.clone()).unwrap_or_default();+ let members: Vec<_> = t+ .machines+ .iter()+ .map(|m| {+ serde_json::json!({"person": m.person, "machine": m.machine, "endpoint": m.endpoint,+ "verified": m.verified, "is_me": m.is_me, "online": m.is_me || m.online})+ })+ .collect();+ let mut out = serde_json::json!({+ "team_id": t.id, "team_name": t.name, "link": l.url, "invite_line": invite_line(&l.url),+ "person": t.person, "machine": t.machine, "endpoint": endpoint, "members": members,+ });+ if let Some(agents) = set_up_for {+ out["set_up_for"] = serde_json::json!(agents);+ }+ Ok(out)+}++/// With `--json`, a failure is a JSON object on stdout too: `{"error":"name_taken"}` when the name is someone else's+/// in the team (the Reason CLI then asks for another), else the message.+fn json_error<T>(json: bool, e: anyhow::Error) -> Result<T> {+ if !json {+ return Err(e);+ }+ let msg = format!("{e:#}");+ let error = if msg.contains("is already in this team") { "name_taken" } else { msg.as_str() };+ println!("{}", serde_json::json!({ "error": error }));+ std::process::exit(1)+}+/// The running daemon's pid, from its lock file.fn daemon_pid() -> Option<u32> {client::running_daemon()diff --git a/src/net.rs b/src/net.rsindex 89f0015..0bf5969 100644--- a/src/net.rs+++ b/src/net.rs@@ -61,6 +61,9 @@ pub struct JoinRequest {pub secret: String,pub person: String,pub machine: String,+ /// The joiner's Reason sign-in proof. Builds before proofs ignore it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub proof: Option<String>,}#[derive(Debug, Serialize, Deserialize)]diff --git a/src/proof.rs b/src/proof.rsnew file mode 100644index 0000000..478b92a--- /dev/null+++ b/src/proof.rs@@ -0,0 +1,230 @@+//! Reason sign-in proofs: a statement signed by Reason that a machine's key (its endpoint id) belongs to a Reason+//! account, and the name that account goes by. A compact JWS (Ed25519, `EdDSA`), checked here against Reason's public+//! keys, which are compiled in: verifying one never calls Reason. Every machine checks every proof it is shown itself.++use anyhow::{Result, anyhow, bail};+use data_encoding::BASE64URL_NOPAD;+use iroh::{EndpointId, PublicKey, Signature};+use serde::{Deserialize, Serialize};++const ISSUER: &str = "https://reasonmachines.com";+const AUDIENCE: &str = "reason-network";+const TYPE: &str = "reason-network-proof";++/// Reason's proof-signing public keys: key id, then the Ed25519 key in base64url. A placeholder until the production+/// key exists; `REASON_NETWORK_TRUST_KEYS` (a JWKS) adds keys, for tests.+const KEYS: &[(&str, &str)] = &[];++/// What a proof says.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Proof {+ /// The Reason account.+ pub sub: String,+ /// The account's name in teams: 1 to 40 of `a-z`, `0-9` and `-`.+ pub name: String,+ pub email: String,+ /// The machine's endpoint id, as the engine prints it.+ pub endpoint: String,+ /// Issued and expires, in seconds since the epoch.+ pub iat: i64,+ pub exp: i64,+}++#[derive(Deserialize)]+struct Header {+ alg: String,+ kid: String,+ typ: String,+}++#[derive(Deserialize)]+struct Claims {+ iss: String,+ aud: String,+ #[serde(flatten)]+ proof: Proof,+}++#[derive(Deserialize)]+struct Jwks {+ keys: Vec<Jwk>,+}++#[derive(Deserialize)]+struct Jwk {+ kty: String,+ crv: String,+ kid: String,+ x: String,+}++fn key(x: &str) -> Option<PublicKey> {+ let bytes = BASE64URL_NOPAD.decode(x.trim_end_matches('=').as_bytes()).ok()?;+ PublicKey::from_bytes(&bytes.try_into().ok()?).ok()+}++/// The keys a proof may be signed with: the compiled-in ones, those in `REASON_NETWORK_TRUST_KEYS`, and in tests a+/// test key.+fn trusted() -> &'static [(String, PublicKey)] {+ static KEYS_: std::sync::OnceLock<Vec<(String, PublicKey)>> = std::sync::OnceLock::new();+ KEYS_.get_or_init(|| {+ let mut out: Vec<(String, PublicKey)> =+ KEYS.iter().filter_map(|(kid, x)| Some((kid.to_string(), key(x)?))).collect();+ if let Some(jwks) = crate::paths::env_var_os("TRUST_KEYS")+ && let Ok(jwks) = serde_json::from_str::<Jwks>(&jwks.to_string_lossy())+ {+ out.extend(+ jwks.keys+ .into_iter()+ .filter(|k| k.kty == "OKP" && k.crv == "Ed25519")+ .filter_map(|k| Some((k.kid, key(&k.x)?))),+ );+ }+ #[cfg(test)]+ out.push((tests::KID.into(), tests::signer().public()));+ out+ })+}++/// Checks `jws` for the machine `endpoint`: Reason's signature, issuer, audience, expiry, and that it names this+/// machine.+pub fn verify(jws: &str, endpoint: &EndpointId) -> Result<Proof> {+ verify_with(jws, endpoint, crate::util::now_ms() / 1000, trusted())+}++fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, PublicKey)]) -> Result<Proof> {+ let bad = || anyhow!("this sign-in proof is damaged");+ 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())?;+ if header.alg != "EdDSA" || 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)");+ };+ let sig: [u8; Signature::LENGTH] = decode(s)?.try_into().map_err(|_| bad())?;+ if key.verify(format!("{h}.{c}").as_bytes(), &Signature::from_bytes(&sig)).is_err() {+ bail!("this sign-in proof's signature doesn't verify");+ }+ let claims: Claims = serde_json::from_slice(&decode(c)?).map_err(|_| bad())?;+ if claims.iss != ISSUER || claims.aud != AUDIENCE {+ bail!("this sign-in proof isn't from Reason Network");+ }+ let p = claims.proof;+ if p.exp <= now {+ bail!("this sign-in proof expired; sign in again");+ }+ if p.endpoint != endpoint.to_string() {+ bail!("this sign-in proof is for another machine");+ }+ if p.name.is_empty()+ || p.name.len() > 40+ || !p.name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')+ {+ bail!("this sign-in proof's name isn't a valid name");+ }+ Ok(p)+}++#[cfg(test)]+pub(crate) mod tests {+ use super::*;+ use iroh::SecretKey;+ use serde_json::json;++ pub const KID: &str = "test-1";++ /// The key test builds trust (see `trusted`), standing in for Reason's.+ pub fn signer() -> SecretKey {+ SecretKey::from_bytes(&[7; 32])+ }++ pub fn sign_with(key: &SecretKey, header: serde_json::Value, claims: serde_json::Value) -> String {+ let enc = |v: serde_json::Value| BASE64URL_NOPAD.encode(&serde_json::to_vec(&v).unwrap());+ let input = format!("{}.{}", enc(header), enc(claims));+ let sig = key.sign(input.as_bytes());+ format!("{input}.{}", BASE64URL_NOPAD.encode(&sig.to_bytes()))+ }++ pub fn claims(sub: &str, name: &str, endpoint: &EndpointId) -> serde_json::Value {+ let now = crate::util::now_ms() / 1000;+ json!({"iss": ISSUER, "aud": AUDIENCE, "sub": sub, "name": name, "email": format!("{name}@example.com"),+ "endpoint": endpoint.to_string(), "iat": now, "exp": now + 90 * 86_400})+ }++ /// A good proof that `endpoint` belongs to account `sub`, called `name`.+ pub fn proof(sub: &str, name: &str, endpoint: &EndpointId) -> String {+ sign_with(&signer(), json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}), claims(sub, name, endpoint))+ }++ #[test]+ fn a_good_proof_verifies() {+ let me = SecretKey::generate().public();+ let p = verify(&proof("user_1", "alex", &me), &me).unwrap();+ assert_eq!((p.sub.as_str(), p.name.as_str(), p.email.as_str()), ("user_1", "alex", "[email protected]"));+ assert!(verify(&format!(" {}\n", proof("user_1", "alex", &me)), &me).is_ok());+ }++ #[test]+ fn rejects_bad_proofs() {+ let me = SecretKey::generate().public();+ let header = json!({"alg": "EdDSA", "kid": KID, "typ": TYPE});+ let err = |jws: &str| verify(jws, &me).unwrap_err().to_string();+ let with = |change: &dyn Fn(&mut serde_json::Value)| {+ let mut c = claims("user_1", "alex", &me);+ change(&mut c);+ sign_with(&signer(), header.clone(), c)+ };++ let forged = sign_with(&SecretKey::generate(), header.clone(), claims("user_1", "alex", &me));+ assert!(err(&forged).contains("signature doesn't verify"));+ // A good signature over other claims.+ let good = proof("user_1", "alex", &me);+ let other = with(&|c| c["name"] = json!("root"));+ let mixed = format!(+ "{}.{}.{}",+ good.split('.').next().unwrap(),+ other.split('.').nth(1).unwrap(),+ good.split('.').nth(2).unwrap()+ );+ assert!(err(&mixed).contains("signature doesn't verify"));+ assert!(err(&with(&|c| c["aud"] = json!("reason"))).contains("isn't from Reason Network"));+ assert!(err(&with(&|c| c["iss"] = json!("https://evil.example"))).contains("isn't from Reason Network"));+ assert!(err(&with(&|c| c["exp"] = json!(crate::util::now_ms() / 1000 - 1))).contains("expired"));+ assert!(err(&proof("user_1", "alex", &SecretKey::generate().public())).contains("for another machine"));+ for name in ["", "Alex", "alex smith", &"a".repeat(41)] {+ assert!(err(&with(&|c| c["name"] = json!(name))).contains("valid name"), "{name:?}");+ }+ let unknown =+ sign_with(&signer(), json!({"alg": "EdDSA", "kid": "other", "typ": TYPE}), claims("user_1", "alex", &me));+ assert!(err(&unknown).contains("doesn't know"));+ let alg = sign_with(&signer(), json!({"alg": "none", "kid": KID, "typ": TYPE}), claims("user_1", "alex", &me));+ assert!(err(&alg).contains("not a Reason Network sign-in proof"));+ for damaged in ["", "a.b", "a.b.c.d", &good[..good.len() - 4]] {+ assert!(verify(damaged, &me).is_err(), "{damaged:?}");+ }+ }++ #[test]+ fn only_trusted_keys_count() {+ let me = SecretKey::generate().public();+ let jws = proof("user_1", "alex", &me);+ assert!(verify_with(&jws, &me, 0, &[]).is_err(), "no keys, nothing verifies");+ let keys = [(KID.to_string(), signer().public())];+ assert!(verify_with(&jws, &me, 0, &keys).is_ok());+ assert!(verify_with(&jws, &me, i64::MAX, &keys).is_err(), "expired by then");+ }++ #[test]+ fn reads_a_jwks_key() {+ let x = BASE64URL_NOPAD.encode(signer().public().as_bytes());+ let jwks: Jwks =+ serde_json::from_value(json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": x}]})).unwrap();+ assert_eq!(key(&jwks.keys[0].x), Some(signer().public()));+ assert_eq!(key("not base64!"), None);+ }+}diff --git a/src/proto.rs b/src/proto.rsindex 7d5f6b2..a4d5347 100644--- a/src/proto.rs+++ b/src/proto.rs@@ -157,10 +157,19 @@ pub enum Request {person: String,#[serde(default)]relay: Option<String>,+ /// A Reason sign-in proof for this machine: then the name is the proof's.+ #[serde(default)]+ proof: Option<String>,},Join {ticket: String,person: String,+ #[serde(default)]+ proof: Option<String>,+ },+ /// Attach or refresh this machine's Reason sign-in proof.+ Proof {+ jws: String,},Invite {#[serde(default)]@@ -298,6 +307,9 @@ pub struct Directory {pub machine: String,pub machines: Vec<MachineInfo>,pub sessions: Vec<SessionInfo>,+ /// `Join the Reason Network: <team link>`, for agents to pass on.+ #[serde(default)]+ pub invite_line: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -311,10 +323,15 @@ pub struct MachineInfo {pub link: Option<String>,pub rtt_ms: Option<u64>,pub last_seen: Option<i64>,+ /// The person's name is verified: a machine of theirs carries a Reason sign-in proof for it.+ #[serde(default)]+ pub verified: bool,}#[derive(Debug, Clone, Serialize, Deserialize)]pub struct TeamInfo {+ #[serde(default)]+ pub id: String,pub name: String,pub relay: Option<String>,/// Whether this machine is on its relay right now (`None` while the network isn't up).@@ -338,7 +355,7 @@ pub struct InviteInfo {/// Four words, like `plum-tiger-lake-orbit`. For a team with its own relay, the long form (a code would need n0's/// address lookup to find this machine).pub code: String,- /// The same invite as a long `tincan1…` string, for when the inviting machine will be offline.+ /// The same invite as a long `rn1-…` string, for when the inviting machine will be offline.pub ticket: String,pub hours: u64,}diff --git a/src/render.rs b/src/render.rsindex f4a61da..a30f04b 100644--- a/src/render.rs+++ b/src/render.rs@@ -76,14 +76,14 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {rows.into_iter().partition(|&i| agent && d.sessions[i].tier == Tier::None);if rows.is_empty() && unreachable.is_empty() {if agent {- quiet.push(format!("{} · {} ({})", m.person, m.machine, link(m, now)));+ quiet.push(format!("{} · {} ({})", person(m), m.machine, link(m, now)));continue;}let _ = writeln!(out, "\n{} {}", header(m, now, paint), paint.on(DIM, "no sessions"));continue;}if agent {- let _ = writeln!(out, "{} · {} · {}", m.person, m.machine, link(m, now));+ let _ = writeln!(out, "{} · {} · {}", person(m), m.machine, link(m, now));} else {let _ = writeln!(out, "\n{}", header(m, now, paint));}@@ -111,6 +111,9 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {if !quiet.is_empty() {let _ = writeln!(out, "no sessions: {}", quiet.join(", "));}+ if agent && let Some(line) = &d.invite_line {+ let _ = writeln!(out, "Invite people with this line: {line}");+ }if !d.sessions.is_empty() {if agent {out.push_str(@@ -130,7 +133,12 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {/// `● alice · xps · direct 4ms`: a green dot while the machine is online.fn header(m: &MachineInfo, now: i64, paint: Paint) -> String {let dot = if m.is_me || m.online { paint.on(GREEN, "●") } else { paint.on(DIM, "○") };- format!("{dot} {} {}", paint.on(BOLD, &format!("{} · {} ·", m.person, m.machine)), link_painted(m, now, paint))+ format!("{dot} {} {}", paint.on(BOLD, &format!("{} · {} ·", person(m), m.machine)), link_painted(m, now, paint))+}++/// The person's name, marked when Reason verified it.+fn person(m: &MachineInfo) -> String {+ if m.verified { format!("{} (verified)", m.person) } else { m.person.clone() }}struct Layout {@@ -198,10 +206,10 @@ pub fn team(t: &TeamInfo) -> String {let mut out = String::new();let relay = t.relay.as_deref().unwrap_or("n0 public relays");let _ = writeln!(out, "team {} · relay: {relay}", t.name);- let pw = t.machines.iter().map(|m| m.person.chars().count()).max().unwrap_or(0);+ let pw = t.machines.iter().map(|m| person(m).chars().count()).max().unwrap_or(0);let mw = t.machines.iter().map(|m| m.machine.chars().count()).max().unwrap_or(0);for m in &t.machines {- let _ = writeln!(out, " {:pw$} {:mw$} {}", m.person, m.machine, link(m, now));+ let _ = writeln!(out, " {:pw$} {:mw$} {}", person(m), m.machine, link(m, now));}out}diff --git a/src/setup.rs b/src/setup.rsindex c5ada56..7fc608f 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -1422,6 +1422,13 @@ pub async fn run(dry: bool, remove: bool, no_service: bool) -> Result<()> {Ok(())}+/// Setup without the report, for `--json`: the agents it set up.+pub async fn quietly() -> Result<Vec<&'static str>> {+ let exe = exe()?;+ let ids: Vec<&str> = detect(&exe).iter().map(|f| f.id).collect();+ Ok(apply(&exe, &ids, &[], Some(true), false).await.agents)+}+/// Read-only checks, one line each.pub async fn doctor() -> Result<()> {let exe = exe()?;diff --git a/src/skill.md b/src/skill.mdindex 9a6499f..26ec751 100644--- a/src/skill.md+++ b/src/skill.md@@ -15,6 +15,8 @@ ask_user); without them, you use the `reason-network` command.- `reason-network send <to> "<message>"`: `<to>` is one agent session, `person/session`. Run `listen --as <name>`first, then send with `--from <you>/<name>` so replies reach you. `--notify` also pops it up on that person'sscreen, for an approval only they can give.+- `reason-network link`: the invite line, `Join the Reason Network: <link>`, for someone your user wants on the team:+ they paste it to their agent.- `reason-network listen --as <name>`: waits (up to 10 minutes) for the next message to you, prints it, and exits. Youare reachable as `<your user>/<name>`. After handling a message and replying, run it again to keep listening.diff --git a/src/team.rs b/src/team.rsindex 5bffb2d..d3c267f 100644--- a/src/team.rs+++ b/src/team.rs@@ -2,7 +2,10 @@//! signed by a member machine's key. Any member can add or remove machines and issue invites; entries merge//! last-writer-wins by timestamp. Built for a team of friends who trust each other, not adversarial members.-use crate::util;+use crate::{+ proof::{self, Proof},+ util,+};use anyhow::{Result, anyhow, bail};use data_encoding::{BASE64URL_NOPAD, HEXLOWER};use iroh::{EndpointAddr, EndpointId, SecretKey, Signature};@@ -93,6 +96,10 @@ pub struct TeamState {pub invites: BTreeMap<String, Signed<Invite>>,#[serde(default)]pub link: Option<Signed<Link>>,+ /// Each machine's Reason sign-in proof (a JWS, see [`crate::proof`]), by endpoint id. It signs itself, so it stays+ /// out of the signed entries, and builds that don't know it pass the rest of the state on unchanged.+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub attestations: BTreeMap<String, String>,}/// Entries stamped further ahead than this are refused (a broken clock, or worse).@@ -126,6 +133,7 @@ impl TeamState {members: BTreeMap::new(),invites: BTreeMap::new(),link: None,+ attestations: BTreeMap::new(),};state.put_member(key, key.public(), person, machine, true);state.new_link(key);@@ -162,10 +170,37 @@ impl TeamState {TeamState { link: None, invites: BTreeMap::new(), ..self.clone() }}- /// Whether `endpoint` may be an active machine of `person`, on `signer`'s word.+ /// Whether `endpoint` may be an active machine of `person`, on `signer`'s word: one of the person's machines vouches+ /// for it, nobody else has the name, or Reason says it belongs to the account the name is verified for.fn may_take(&self, person: &str, endpoint: &EndpointId, signer: &EndpointId) -> bool {self.active().any(|m| m.endpoint == *signer && m.person == person)|| !self.active().any(|m| m.person == person && m.endpoint != *endpoint)+ || self+ .proof(endpoint)+ .is_some_and(|p| p.name == person && self.verified_people().get(person) == Some(&p.sub))+ }++ /// The machine's sign-in proof, if it has one that verifies now.+ pub fn proof(&self, endpoint: &EndpointId) -> Option<Proof> {+ proof::verify(self.attestations.get(&endpoint.to_string())?, endpoint).ok()+ }++ /// Verified people: each name an active machine's proof is for, with the Reason account it belongs to.+ pub fn verified_people(&self) -> HashMap<String, String> {+ self.active()+ .filter_map(|m| self.proof(&m.endpoint).filter(|p| p.name == m.person))+ .map(|p| (p.name, p.sub))+ .collect()+ }++ /// Records `endpoint`'s sign-in proof, if it verifies and is newer than the one it has; true if it was taken.+ pub fn attest(&mut self, endpoint: &EndpointId, jws: &str) -> bool {+ let Ok(p) = proof::verify(jws, endpoint) else { return false };+ if self.proof(endpoint).is_some_and(|cur| cur.iat >= p.iat) {+ return false;+ }+ self.attestations.insert(endpoint.to_string(), jws.trim().to_string());+ true}pub fn name(&self) -> &str {@@ -248,8 +283,16 @@ impl TeamState {self.invites.get(&hash(secret)).is_some_and(|i| i.body.used_by.is_none() && i.body.expires > util::now_ms())}- /// Checks that `secret` admits `person`, and marks the invite used by `joiner`.- pub fn redeem(&mut self, key: &SecretKey, secret: &str, person: &str, joiner: EndpointId) -> Result<()> {+ /// Checks that `secret` admits `person` (with the joiner's verified sign-in proof, if any), and marks the invite+ /// used by `joiner`.+ pub fn redeem(+ &mut self,+ key: &SecretKey,+ secret: &str,+ person: &str,+ joiner: EndpointId,+ proof: Option<&Proof>,+ ) -> Result<()> {let h = hash(secret);let signed = self.invites.get(&h).ok_or_else(|| anyhow!("unknown invite"))?;let (inv, signer) = (signed.body.clone(), signed.by);@@ -276,6 +319,8 @@ impl TeamState {bail!("only one of {p}'s machines can let this one in; try again while one is online")}Some(_) => {}+ // Another computer of the account the name is verified for may join under it.+ None if proof.is_some_and(|p| p.name == person && self.verified_people().get(person) == Some(&p.sub)) => {}None if self.active().any(|m| m.person == person && m.endpoint != joiner) => {bail!("'{person}' is already in this team; join with another name (--as)")}@@ -294,7 +339,16 @@ impl TeamState {bail!("state from a different team");}let mut changed = false;- // Admissions first: they decide who may sign everything else. One admission can vouch for the signer of+ // Proofs check themselves; they come before members, whose names they can vouch for (`may_take`).+ for (k, jws) in &other.attestations {+ if let Ok(id) = k.parse::<EndpointId>()+ && self.attestations.get(k) != Some(jws)+ && self.attest(&id, jws)+ {+ changed = true;+ }+ }+ // Then admissions: they decide who may sign everything else. One admission can vouch for the signer of// another, so repeat until nothing new lands.loop {let admitted = self.admitted();@@ -390,6 +444,7 @@ impl TeamState {members: BTreeMap::new(),invites: BTreeMap::new(),link: None,+ attestations: BTreeMap::new(),};s.merge(other)?;let admitted = s.admitted();@@ -428,8 +483,10 @@ pub struct Ticket {pub peers: Vec<EndpointId>,}-/// Wire format shared with every peer (and earlier builds): never change it.-const TICKET_PREFIX: &str = "tincan1";+/// What a ticket starts with. The payload after it is shared with every peer (and earlier builds): never change it.+const TICKET_PREFIX: &str = "rn1-";+/// What earlier builds wrote: still read.+const OLD_TICKET_PREFIX: &str = "tincan1";/// In place of a length: an n0 relay, given by its region (`use1-1` for `https://use1-1.relay.n0.iroh.link./`).const N0_RELAY: u8 = 0xFF;const N0_RELAY_SUFFIX: &str = ".relay.n0.iroh.link./";@@ -452,7 +509,7 @@ fn n0_relay(url: &str) -> Option<&str> {}impl Ticket {- /// `tincan1` + base64url of: team id (16 bytes), secret (16), name, team relay, first peer's relay hint (each+ /// `rn1-` + base64url of: team id (16 bytes), secret (16), name, team relay, first peer's relay hint (each/// length-prefixed, 0 for none), its address hints (count, then family 4/6, address, port), then 32 bytes per/// member key.pub fn encode(&self) -> String {@@ -493,9 +550,17 @@ impl Ticket {format!("{TICKET_PREFIX}{}", BASE64URL_NOPAD.encode(&b))}+ /// Whether `text` holds a team link or ticket (it may not be a whole one).+ pub fn is_ticket(text: &str) -> bool {+ text.contains(TICKET_PREFIX) || text.contains(OLD_TICKET_PREFIX)+ }+pub fn decode(s: &str) -> Result<Self> {let s = s.trim().rsplit('#').next().unwrap_or_default();- let data = s.strip_prefix(TICKET_PREFIX).ok_or_else(|| anyhow!("not a Reason Network invite"))?;+ let data = s+ .strip_prefix(TICKET_PREFIX)+ .or_else(|| s.strip_prefix(OLD_TICKET_PREFIX))+ .ok_or_else(|| anyhow!("not a Reason Network invite"))?;let b =BASE64URL_NOPAD.decode(data.as_bytes()).map_err(|_| anyhow!("this invite is damaged (was it cut off?)"))?;let damaged = || anyhow!("this invite is damaged (was it cut off?)");@@ -613,17 +678,17 @@ mod tests {sa.invite(&a, &secret, 24, None);// b joins through a: a redeems and adds b; b verifies what it receives.- sa.redeem(&a, &secret, "alice", b.public()).unwrap();+ sa.redeem(&a, &secret, "alice", b.public(), None).unwrap();sa.put_member(&a, b.public(), "alice", "xps", true);let mut sb = TeamState::verified(&sa).unwrap();assert_eq!(sb, sa);assert!(sb.is_active(&b.public()));- assert!(sa.redeem(&a, &secret, "eve", c.public()).is_err(), "invites are single use");+ assert!(sa.redeem(&a, &secret, "eve", c.public(), None).is_err(), "invites are single use");// b invites c; a learns about c by merging b's copy.let s2 = random_secret();sb.invite(&b, &s2, 1, None);- sb.redeem(&b, &s2, "sam", c.public()).unwrap();+ sb.redeem(&b, &s2, "sam", c.public(), None).unwrap();sb.put_member(&b, c.public(), "sam", "nuc", true);assert!(sa.merge(&sb).unwrap());assert!(sa.is_active(&c.public()));@@ -673,7 +738,7 @@ mod tests {s.put_member(&f, f.public(), "alex", "mbp", false); // founder leaveslet secret = random_secret();s.invite(&b, &secret, 24, None);- s.redeem(&b, &secret, "sam", d.public()).unwrap();+ s.redeem(&b, &secret, "sam", d.public(), None).unwrap();s.put_member(&b, d.public(), "sam", "nuc", true);let sd = TeamState::verified(&s).unwrap();assert!(sd.is_active(&d.public()) && sd.is_active(&b.public()) && !sd.is_active(&f.public()));@@ -698,7 +763,7 @@ mod tests {// A newcomer sees the same, including c (admitted by b, who is gone now).let secret = random_secret();x.invite(&f, &secret, 24, None);- x.redeem(&f, &secret, "dee", d.public()).unwrap();+ x.redeem(&f, &secret, "dee", d.public(), None).unwrap();x.put_member(&f, d.public(), "dee", "pi", true);let z = TeamState::verified(&x).unwrap();assert!(z.is_active(&c.public()) && !z.is_active(&b.public()));@@ -724,14 +789,14 @@ mod tests {let mut s = TeamState::found("vibes", "alex", "mbp", &a);let first = random_secret();s.invite(&a, &first, 24, None);- s.redeem(&a, &first, "alice", b.public()).unwrap();+ s.redeem(&a, &first, "alice", b.public(), None).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);- assert!(s.redeem(&a, &first, "alice", b.public()).is_ok(), "a retry by the same machine is fine");+ assert!(s.redeem(&a, &first, "alice", b.public(), None).is_ok(), "a retry by the same machine is fine");let from_b = random_secret();s.invite(&b, &from_b, 720, None);s.put_member(&a, b.public(), "alice", "xps", false);- assert!(s.redeem(&a, &first, "alice", b.public()).is_err(), "removed: the old invite doesn't readmit");- assert!(s.redeem(&a, &from_b, "sam", c.public()).is_err(), "invites by a removed machine are dead");+ assert!(s.redeem(&a, &first, "alice", b.public(), None).is_err(), "removed: the old invite doesn't readmit");+ assert!(s.redeem(&a, &from_b, "sam", c.public(), None).is_err(), "invites by a removed machine are dead");}#[test]@@ -753,11 +818,11 @@ mod tests {let mut s = TeamState::found("vibes", "alex", "mbp", &a);let open = random_secret();s.invite(&a, &open, 24, None);- assert!(s.redeem(&a, &open, "alex", b.public()).is_err());+ assert!(s.redeem(&a, &open, "alex", b.public(), None).is_err());let mine = random_secret();s.invite(&a, &mine, 24, Some("alex".into()));- assert!(s.redeem(&a, &mine, "alice", b.public()).is_err());- s.redeem(&a, &mine, "alex", b.public()).unwrap();+ assert!(s.redeem(&a, &mine, "alice", b.public(), None).is_err());+ s.redeem(&a, &mine, "alex", b.public(), None).unwrap();}#[test]@@ -765,7 +830,7 @@ mod tests {let (a, b, fake, mine) = (key(), key(), key(), key());let mut s = TeamState::found("vibes", "alex", "mbp", &a);let link = s.link_secret().unwrap().to_string();- s.redeem(&a, &link, "alice", b.public()).unwrap();+ s.redeem(&a, &link, "alice", b.public(), None).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);// alice's machine signs a new machine in as alex, on its copy, and sends it over.let mut evil = s.clone();@@ -803,6 +868,7 @@ mod tests {assert_eq!(Ticket::decode(&format!("https://example.com/join/#{enc}")).unwrap(), t, "a whole link works too");assert!(Ticket::decode(&enc[..enc.len() - 10]).is_err());assert!(Ticket::decode("tincan1!!!").is_err());+ assert!(Ticket::decode("rn1-!!!").is_err());assert!(Ticket::decode("hello").is_err());}@@ -828,7 +894,7 @@ mod tests {}b.push(0);b.extend(a.public().as_bytes());- let old = format!("{TICKET_PREFIX}{}", BASE64URL_NOPAD.encode(&b));+ let old = format!("{OLD_TICKET_PREFIX}{}", BASE64URL_NOPAD.encode(&b));assert!(short.len() + 30 < old.len(), "{} vs {}", short.len(), old.len());assert_eq!(Ticket::decode(&old).unwrap(), t);t.hint_relay = Some("https://relay.example.com/".into());@@ -840,19 +906,128 @@ mod tests {let (a, b, c, d) = (key(), key(), key(), key());let mut s = TeamState::found("vibes", "alex", "mbp", &a);let link = s.link_secret().unwrap().to_string();- s.redeem(&a, &link, "alice", b.public()).unwrap();+ s.redeem(&a, &link, "alice", b.public(), None).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);- s.redeem(&a, &link, "sam", c.public()).unwrap();+ s.redeem(&a, &link, "sam", c.public(), None).unwrap();s.put_member(&a, c.public(), "sam", "nuc", true);- assert!(s.redeem(&a, &link, "alice", d.public()).is_err(), "names stay unique");+ assert!(s.redeem(&a, &link, "alice", d.public(), None).is_err(), "names stay unique");// A joiner learns the link, and can show it too.let joined = TeamState::verified(&s).unwrap();assert_eq!(joined.link_secret(), Some(link.as_str()));assert_eq!(s.without_secrets().link, None);assert!(s.without_secrets().invites.is_empty());s.new_link(&b);- assert!(s.redeem(&a, &link, "dee", d.public()).is_err(), "the old link stops working");+ assert!(s.redeem(&a, &link, "dee", d.public(), None).is_err(), "the old link stops working");let fresh = s.link_secret().unwrap().to_string();- s.redeem(&a, &fresh, "dee", d.public()).unwrap();+ s.redeem(&a, &fresh, "dee", d.public(), None).unwrap();+ }++ #[test]+ fn links_are_rn1_and_tincan1_links_still_work() {+ let t = Ticket {+ team: "00112233445566778899aabbccddeeff".into(),+ name: "vibes".into(),+ secret: random_secret(),+ relay: None,+ hint_relay: None,+ hint_ips: vec![],+ peers: vec![key().public()],+ };+ let enc = t.encode();+ let payload = enc.strip_prefix("rn1-").expect("emitted as rn1-");+ for link in [+ enc.clone(),+ format!("https://reasonmachines.com/network/join/#{enc}"),+ format!("tincan1{payload}"),+ format!("https://reasonmachines.com/network/join/#tincan1{payload}"),+ ] {+ assert_eq!(Ticket::decode(&link).unwrap(), t, "{link}");+ }+ assert!(Ticket::decode(&format!("rn2-{payload}")).is_err());+ }++ fn proof(sub: &str, name: &str, k: &SecretKey) -> String {+ crate::proof::tests::proof(sub, name, &k.public())+ }++ #[test]+ fn proofs_mark_people_verified_and_travel_with_the_state() {+ let (a, b) = (key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ assert!(s.attest(&a.public(), &proof("u_alex", "alex", &a)));+ s.put_member(&a, b.public(), "alice", "xps", true);+ // A proof for another machine, or a forged one, is refused.+ assert!(!s.attest(&b.public(), &proof("u_alice", "alice", &a)));+ let forged = crate::proof::tests::sign_with(+ &key(),+ serde_json::json!({"alg": "EdDSA", "kid": crate::proof::tests::KID, "typ": "reason-network-proof"}),+ crate::proof::tests::claims("u_alice", "alice", &b.public()),+ );+ assert!(!s.attest(&b.public(), &forged));+ assert_eq!(s.verified_people().into_iter().collect::<Vec<_>>(), [("alex".into(), "u_alex".into())]);+ // A proof for a name the machine doesn't go by doesn't verify the person.+ let mut other = s.clone();+ other.attestations.insert(b.public().to_string(), proof("u_x", "bob", &b));+ assert!(s.merge(&other).unwrap());+ assert!(!s.verified_people().contains_key("alice") && !s.verified_people().contains_key("bob"));+ // Peers drop proofs that don't verify.+ let mut bad = s.clone();+ bad.attestations.insert(a.public().to_string(), forged.clone());+ assert!(!s.merge(&bad).unwrap());+ assert_eq!(s.verified_people().get("alex").map(String::as_str), Some("u_alex"));+ // A joiner gets them with the state.+ let joined = TeamState::verified(&s).unwrap();+ assert_eq!(joined.attestations, s.attestations);+ }++ #[test]+ fn state_from_builds_without_proofs_merges_both_ways() {+ let (a, b) = (key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ // Without proofs the state serializes as before them.+ assert!(!serde_json::to_string(&s).unwrap().contains("attestations"));+ s.attest(&a.public(), &proof("u_alex", "alex", &a));+ // An older build reads the state, drops what it doesn't know, signs a change, and sends it back.+ let mut json: serde_json::Value = serde_json::to_value(&s).unwrap();+ json.as_object_mut().unwrap().remove("attestations");+ let mut old: TeamState = serde_json::from_value(json).unwrap();+ assert!(old.attestations.is_empty());+ old.put_member(&a, b.public(), "alice", "xps", true);+ assert!(s.merge(&old).unwrap());+ assert!(+ s.is_active(&b.public()) && s.verified_people().contains_key("alex"),+ "the change lands, the proof stays"+ );+ // Our state, with proofs, verifies for it too: no signed entry changed.+ assert!(TeamState::verified(&s).is_ok());+ }++ #[test]+ fn a_verified_name_is_its_accounts() {+ let (a, b, c, d) = (key(), key(), key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ s.attest(&a.public(), &proof("u_alex", "alex", &a));+ let link = s.link_secret().unwrap().to_string();+ let p = |sub: &str, name: &str, k: &SecretKey| crate::proof::verify(&proof(sub, name, k), &k.public()).unwrap();+ // Another account, or no proof, can't take it.+ let err = s.redeem(&a, &link, "alex", b.public(), Some(&p("u_mallory", "alex", &b))).unwrap_err();+ assert!(err.to_string().contains("already in this team"), "{err}");+ assert!(s.redeem(&a, &link, "alex", b.public(), None).is_err());+ // Another computer of the same account can, through the team link, let in by anyone.+ s.redeem(&a, &link, "alice", c.public(), None).unwrap();+ s.put_member(&a, c.public(), "alice", "xps", true);+ s.redeem(&c, &link, "alex", d.public(), Some(&p("u_alex", "alex", &d))).unwrap();+ s.attest(&d.public(), &proof("u_alex", "alex", &d));+ s.put_member(&c, d.public(), "alex", "mini", true);+ let peer = TeamState::verified(&s).unwrap();+ assert!(peer.is_active(&d.public()), "alice's machine let in alex's second computer");+ // Without its proof, peers don't take alice's machine's word that it is alex's.+ let mut forged = s.clone();+ forged.attestations.remove(&d.public().to_string());+ assert!(!TeamState::verified(&forged).unwrap().is_active(&d.public()));+ // A name nobody verified stays with whoever has it, proof or not.+ let e = key();+ let err = s.redeem(&a, &link, "alice", e.public(), Some(&p("u_alice", "alice", &e))).unwrap_err();+ assert!(err.to_string().contains("already in this team"), "{err}");}}diff --git a/src/wizard.rs b/src/wizard.rsindex eca4778..727c25f 100644--- a/src/wizard.rs+++ b/src/wizard.rs@@ -33,7 +33,7 @@ fn name_ok(s: &str) -> Result<(), &'static str> {}fn invite_ok(s: &str) -> Result<(), &'static str> {- if s.contains("tincan1") || invite::normalize(s).is_some() {+ if crate::team::Ticket::is_ticket(s) || invite::normalize(s).is_some() {Ok(())} else {Err("paste the team link your friend sent")@@ -84,7 +84,7 @@ pub async fn onboard(let sp = spinner();sp.start("Creating the team...");let t: TeamInfo = link- .call(Request::CreateTeam { name, person, relay: None })+ .call(Request::CreateTeam { name, person, relay: None, proof: None }).await.inspect_err(|e| sp.error(format!("{e:#}")))?;crate::wait_exit(crate::daemon_pid()).await;@@ -101,7 +101,10 @@ pub async fn onboard(};let sp = spinner();sp.start("Joining...");- match link.call::<TeamInfo>(Request::Join { ticket: text.clone(), person: person.clone() }).await {+ match link+ .call::<TeamInfo>(Request::Join { ticket: text.clone(), person: person.clone(), proof: None })+ .await+ {Ok(t) => {crate::wait_exit(crate::daemon_pid()).await;sp.stop(format!("Joined team {} as {} on {}.", t.name, t.person, t.machine));diff --git a/tests/e2e/mixed_versions.py b/tests/e2e/mixed_versions.pynew file mode 100644index 0000000..fc3e30b--- /dev/null+++ b/tests/e2e/mixed_versions.py@@ -0,0 +1,112 @@+"""This build and an older one in one team: sign-in proofs and rn1 links leave older machines working.++ cargo build && REASON_NETWORK_OLD_BIN=<an older reason-network, e.g. 0.10.8> \+ env -u CLAUDE_CODE_MESSAGING_SOCKET python3 tests/e2e/mixed_versions.py++Needs internet (iroh relays/discovery).+"""+import json, os, re, subprocess, sys, tempfile, time+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from proofs import TRUST, proof++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+NEW = os.path.join(ROOT, "target", "debug", "reason-network")+OLD = os.environ["REASON_NETWORK_OLD_BIN"]+D = tempfile.mkdtemp(prefix="reason-network-mixed-")+FAKE_BIN = os.path.join(D, "bin")+UNEXPECTED = os.path.join(D, "unexpected.log")+# alex and nina run this build, olga the older one.+WHO = {"alex": (NEW, "laptop"), "olga": (OLD, "oldbox"), "nina": (NEW, "desk"), "mal": (NEW, "evil")}+results = []+++def check(name, ok, detail=""):+ results.append(ok)+ print(f"{'PASS' if ok else 'FAIL'}: {name}" + ("" if ok else f"\n {detail}"))+++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][1], 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)+ return e+++def cli(who, *args):+ r = subprocess.run([WHO[who][0], *args], env=env(who), capture_output=True, text=True, timeout=90)+ return (r.stdout + r.stderr).strip()+++def link_of(out):+ m = re.search(r"https://\S+/join/#\S+", out)+ return m.group(0) if m 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:+ print(f"this build: {cli('alex', '--version')} · older: {cli('olga', '--version')}")+ ep = {w: cli(w, "endpoint") for w in ("alex", "nina", "mal")}+ out = cli("alex", "init", "mixed", "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")+ check("this build starts a team, signed in", "You are alex on laptop." in out, out)+ link = link_of(cli("alex", "link"))+ out = cli("olga", "join", link, "--as", "olga", "--no-setup")+ check("the older build can't read an rn1 link", "Joined" not in out, out)+ out = cli("olga", "join", link.replace("#rn1-", "#tincan1"), "--as", "olga", "--no-setup")+ check("…but joins with the same link as tincan1", "Joined team mixed as olga on oldbox." in out, out)+ time.sleep(5)+ out = cli("alex", "team")+ check("the older machine is connected, and alex still verified after its state came back",+ re.search(r"olga\s+oldbox\s+(direct|relay)", out) is not None and "alex (verified)" in out, out)+ out = cli("olga", "team")+ check("the older machine sees alex, connected", re.search(r"alex\s+laptop\s+(direct|relay)", out) is not None, out)++ # A machine of this build joins through the older one, which knows nothing of proofs.+ old_link = link_of(cli("olga", "link"))+ out = cli("nina", "join", old_link, "--proof", proof("u_nina", "nina", ep["nina"]), "--no-setup")+ check("this build joins, signed in, through the older machine", "Joined team mixed as nina on desk." in out, out)+ check("…and its proof goes along anyway", "nina (verified)" in out, out)+ time.sleep(6)+ out = cli("alex", "team")+ check("alex's machine sees nina verified", re.search(r"nina \(verified\)\s+desk\s+(direct|relay)", out) is not None, out)+ out = cli("olga", "team")+ check("the older machine has all three, every signed entry checking out",+ all(re.search(rf"{p}\s+{m}\s+(direct|relay|this machine)", out) for p, m in [("alex", "laptop"), ("olga", "oldbox"), ("nina", "desk")]), out)+ out = subprocess.run([NEW, "join", old_link, "--proof", proof("u_mal", "alex", ep["mal"]), "--no-setup", "--json"],+ env=env("mal"), capture_output=True, text=True, timeout=90).stdout.strip()+ check("a taken name through the older machine is name_taken", out == '{"error":"name_taken"}', out)++ # Messages both ways, and the state kept across restarts.+ cli("olga", "listen", "--as", "t", "--wait", "0")+ cli("alex", "listen", "--as", "t", "--wait", "0")+ time.sleep(3)+ out = cli("alex", "send", "olga/t", "--from", "alex/t", "hello old friend")+ check("this build sends to the older one", "→ olga/t" in out, out)+ out = cli("olga", "listen", "--as", "t", "--wait", "10")+ check("…which gets it", "hello old friend" in out, out)+ cli("olga", "send", "alex/t", "--from", "olga/t", "hello back")+ out = cli("alex", "listen", "--as", "t", "--wait", "10")+ check("and back", "hello back" in out, out)+ for w in ("alex", "olga"):+ cli(w, "stop")+ time.sleep(1)+ cli("olga", "team")+ cli("alex", "team")+ time.sleep(8)+ out = cli("alex", "team")+ check("after both restart, people stay verified", "alex (verified)" in out and "nina (verified)" in out+ and re.search(r"olga\s+oldbox\s+(direct|relay)", out) is not None, out)+finally:+ for w in WHO:+ subprocess.run([WHO[w][0], "stop"], env=env(w), capture_output=True, timeout=30)+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/proofs.py b/tests/e2e/proofs.pynew file mode 100644index 0000000..4eaaebc--- /dev/null+++ b/tests/e2e/proofs.py@@ -0,0 +1,83 @@+"""Reason sign-in proofs for the e2e tests: a stand-in for Reason's signing key, trusted through+REASON_NETWORK_TRUST_KEYS. Ed25519 from RFC 8032's reference code, so the tests need nothing installed."""+import base64, hashlib, json, os, time++p = 2**255 - 19+d = -121665 * pow(121666, p - 2, p) % p+q = 2**252 + 27742317777372353535851937790883648493+++def _add(P, Q):+ A, B = (P[1] - P[0]) * (Q[1] - Q[0]) % p, (P[1] + P[0]) * (Q[1] + Q[0]) % p+ C, D = 2 * P[3] * Q[3] * d % p, 2 * P[2] * Q[2] % p+ E, F, G, H = B - A, D - C, D + C, B + A+ return (E * F, G * H, F * G, E * H)+++def _mul(s, P):+ Q = (0, 1, 1, 0)+ while s > 0:+ if s & 1:+ Q = _add(Q, P)+ P, s = _add(P, P), s >> 1+ return Q+++def _compress(P):+ zinv = pow(P[2], p - 2, p)+ x, y = P[0] * zinv % p, P[1] * zinv % p+ return int.to_bytes(y | ((x & 1) << 255), 32, "little")+++def _base():+ y = 4 * pow(5, p - 2, p) % p+ x2 = (y * y - 1) * pow(d * y * y + 1, p - 2, p)+ x = pow(x2, (p + 3) // 8, p)+ if (x * x - x2) % p:+ x = x * pow(2, (p - 1) // 4, p) % p+ if x & 1:+ x = p - x+ return (x, y, 1, x * y % p)+++G = _base()+++def _expand(seed):+ h = hashlib.sha512(seed).digest()+ a = int.from_bytes(h[:32], "little")+ a &= (1 << 254) - 8+ a |= 1 << 254+ return a, h[32:]+++def public(seed):+ return _compress(_mul(_expand(seed)[0], G))+++def sign(seed, msg):+ a, prefix = _expand(seed)+ A = _compress(_mul(a, G))+ r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % q+ R = _compress(_mul(r, G))+ h = int.from_bytes(hashlib.sha512(R + A + msg).digest(), "little") % q+ return R + int.to_bytes((r + h * a) % q, 32, "little")+++def b64(b):+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode()+++REASON = os.urandom(32) # stands in for Reason's signing key+KID = "e2e-1"+TRUST = json.dumps({"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": b64(public(REASON))}]})+++def proof(sub, name, endpoint, key=None, **claims):+ """A proof that `endpoint` belongs to account `sub`, called `name`; signed with `key` it's a forgery."""+ now = int(time.time())+ body = {"iss": "https://reasonmachines.com", "aud": "reason-network", "sub": sub, "name": name,+ "email": f"{name}@example.com", "endpoint": endpoint, "iat": now, "exp": now + 90 * 86400, **claims}+ head = {"alg": "EdDSA", "kid": KID, "typ": "reason-network-proof"}+ signing = f"{b64(json.dumps(head).encode())}.{b64(json.dumps(body).encode())}"+ return f"{signing}.{b64(sign(key or REASON, signing.encode()))}"diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex a33d568..955cb37 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -1,11 +1,13 @@"""Two 'machines' (two REASON_NETWORK_HOMEs) on one box, talking over iroh, with simulated agent sessions.- cargo build && python3 tests/e2e/two_machines.py+ cargo build && env -u CLAUDE_CODE_MESSAGING_SOCKET python3 tests/e2e/two_machines.pyNeeds internet (iroh relays/discovery). Run inside a Claude Code session, the simulated Claude session pushes itstest messages into that real session (they say "ignore this")."""-import json, os, re, subprocess, tempfile, time+import json, os, re, subprocess, sys, tempfile, time+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from proofs import TRUST, proofROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))BIN = os.path.join(ROOT, "target", "debug", "reason-network")@@ -17,6 +19,9 @@ QUEUE_LOG = os.path.join(D, "codex-queue.log")# Stands in for osascript / notify-send, so the test shows nothing on screen: each machine logs what it would show.FAKE_NOTIFY = os.path.join(D, "fake-notify.sh")IN_CLAUDE = "CLAUDE_CODE_MESSAGING_SOCKET" in os.environ+# First on PATH: nothing here may open a browser or reach this machine's real notifications.+FAKE_BIN = os.path.join(D, "bin")+UNEXPECTED = os.path.join(D, "unexpected.log")results = []@@ -27,6 +32,8 @@ def check(name, ok, detail=""):def env(who, strip_claude=True):e = dict(os.environ, REASON_NETWORK_HOME=H[who], REASON_NETWORK_MACHINE=MACHINE[who], REASON_NETWORK_NO_MDNS="1", REASON_NETWORK_NO_SERVICE="1", REASON_NETWORK_CODEX_BIN=FAKE_CODEX)+ e.update({"HOME": os.path.join(D, "home"), "PATH": FAKE_BIN + os.pathsep + os.environ["PATH"], "REASON_NETWORK_NO_UPDATE": "1",+ "REASON_NETWORK_NO_TRAY": "1", "REASON_NETWORK_TRUST_KEYS": TRUST})e.update({"REASON_NETWORK_OSASCRIPT_BIN": FAKE_NOTIFY, "REASON_NETWORK_NOTIFY-SEND_BIN": FAKE_NOTIFY, "DBUS_SESSION_BUS_ADDRESS": "test","NOTIFY_LOG": os.path.join(D, f"notify-{who}.log")})if strip_claude:@@ -43,6 +50,18 @@ def cli(who, *args):return (r.stdout + r.stderr).strip()+def run(e, *args):+ r = subprocess.run([BIN, *args], env=e, capture_output=True, text=True, timeout=90)+ return r.stdout.strip(), (r.stdout + r.stderr).strip()+++def as_json(text):+ try:+ return json.loads(text)+ except ValueError:+ return {}++def hook(who, agent, event, payload):r = subprocess.run([BIN, "hook", agent, event], env=env(who), capture_output=True, text=True,input=json.dumps(payload), timeout=30)@@ -83,6 +102,12 @@ os.chmod(FAKE_CODEX, 0o755)with open(FAKE_NOTIFY, "w") as f:f.write('#!/bin/sh\nprintf "%s\\n" "$*" >> "$NOTIFY_LOG"\n')os.chmod(FAKE_NOTIFY, 0o755)+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)def shown(who):@@ -91,25 +116,80 @@ def shown(who):return open(p).read() if os.path.exists(p) else ""os.makedirs(os.path.join(D, "work"), exist_ok=True)-# --- team formation ----out = cli("alex", "init", "vibes", "--as", "alex", "--no-setup")-check("init creates team", "Created team vibes. You are alex on laptop." in out, out)+# --- team formation, signed in with Reason ---+ep = {who: cli(who, "endpoint") for who in H}+check("endpoint prints this machine's id, before any team", all(re.fullmatch(r"[0-9a-f]{64}", e) for e in ep.values()), ep)+check("…the same one each time", cli("alex", "endpoint") == ep["alex"], ep)+out = cli("alex", "init", "vibes", "--as", "whoever", "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")+check("init with a proof: the name is the proof's", "Created team vibes. You are alex on laptop." in out, out)+check("…and prints the invite line", re.search(r"Invite people with this line:\nJoin the Reason Network: https://reasonmachines.com/network/join/#rn1-\S+", out) is not None, out)out = cli("alex", "invite")-link = re.search(r"(https://\S+/join/#tincan1\S+)", out)-check("invite prints the team link", bool(link), out)-out = cli("alice", "join", link.group(1), "--as", "alice", "--no-setup")-check("join with the team link succeeds", "Joined team vibes as alice on desktop." in out, out)-check("joiner sees alex connected", re.search(r"alex\s+laptop\s+(direct|relay)", out) is not None, out)+link = re.search(r"(https://\S+/join/#rn1-\S+)", out)+check("invite prints the team link, as an rn1 link", bool(link), out)+check("…in the invite line", f"Join the Reason Network: {link.group(1) if link else '?'}" in out, out)+out, _ = run(env("alice"), "join", link.group(1), "--as", "alice", "--proof", proof("u_alice", "alice", ep["alice"]), "--no-setup", "--json")+j = as_json(out)+check("join with a proof and --json gives the team", j.get("team_name") == "vibes" and j.get("person") == "alice" and j.get("machine") == "desktop"+ and j.get("endpoint") == ep["alice"] and re.fullmatch(r"[0-9a-f]{32}", j.get("team_id", "")) is not None, out)+check("…with the link and invite line", j.get("link", "").startswith("https://reasonmachines.com/network/join/#rn1-")+ and j.get("invite_line") == f"Join the Reason Network: {j.get('link')}", out)+members = {m["person"]: m for m in j.get("members", [])}+check("…and both people verified", members.get("alex", {}).get("verified") is True and members.get("alice", {}).get("verified") is True, out)+time.sleep(3)+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)+j = as_json(cli("alex", "team", "--json"))+check("team --json marks people verified", [m["verified"] for m in j.get("members", [])] == [True, True] and j.get("link", "").startswith("https://"), j)+j = as_json(cli("alex", "link", "--json"))+check("link --json gives the invite line", j.get("invite_line", "").startswith("Join the Reason Network: https://reasonmachines.com/network/join/#rn1-"), j)+out = cli("alex", "link")+check("link prints the invite line", "Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)+j = as_json(cli("alex", "who", "--json"))+check("who --json marks machines verified", all(m.get("verified") for m in j.get("machines", [])) and len(j.get("machines", [])) == 2, j)+out = cli("alice", "proof", proof("u_alice", "alice", ep["alice"]))+check("proof refreshes this machine's proof", "alice on desktop is verified, for 89 more days." in out or "for 90 more days." in out, out)+out = cli("alice", "proof", proof("u_alice", "alicia", ep["alice"]))+check("…but not one for another name", "this proof is for alicia, but this machine is alice in the team" in out, out)+# Someone else signed in, or not at all, can't be alex or alice; a proof Reason didn't sign, or for another machine, gets nobody in.+mal = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "mallory"), REASON_NETWORK_MACHINE="evil")+mal_ep = run(mal, "endpoint")[0]+out, both = run(mal, "join", link.group(1), "--proof", proof("u_mallory", "alex", mal_ep), "--no-setup", "--json")+check("a name verified by another account is taken: name_taken", as_json(out) == {"error": "name_taken"}, both)+out, both = run(mal, "join", link.group(1), "--as", "alice", "--no-setup", "--json")+check("…and without a proof too", as_json(out) == {"error": "name_taken"}, both)+_, out = run(mal, "join", link.group(1), "--proof", proof("u_mallory", "mallory", mal_ep, key=os.urandom(32)), "--no-setup")+check("a forged proof is refused", "signature doesn't verify" in out and "Joined" not in out, out)+_, out = run(mal, "join", link.group(1), "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")+check("someone else's proof is refused", "for another machine" in out and "Joined" not in out, out)+_, out = run(mal, "init", "x", "--proof", proof("u_mallory", "mallory", mal_ep, aud="reason"), "--no-setup")+check("init refuses a proof for something else", "isn't from Reason Network" in out and "Created" not in out, out)+run(mal, "stop")+check("alex's team still has just the two", len(as_json(cli("alex", "team", "--json")).get("members", [])) == 2)+# alex signed in on a second computer: the same account takes its name there, let in by anyone's machine.+mini = dict(env("alex"), REASON_NETWORK_HOME=os.path.join(D, "alex-mini"), REASON_NETWORK_MACHINE="mini")+mini_ep = run(mini, "endpoint")[0]+alice_link = re.search(r"(https://\S+#rn1-\S+)", cli("alice", "link")).group(1)+_, out = run(mini, "join", alice_link, "--proof", proof("u_alex", "alex", mini_ep), "--no-setup")+check("another computer of the same account joins under its verified name", "Joined team vibes as alex on mini." in out, out)+check("…and gets the invite line", "Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)+time.sleep(3)out = cli("alex", "team")-check("founder sees alice connected", re.search(r"alice\s+desktop\s+(direct|relay)", out) is not None, out)+check("…which every machine takes", re.search(r"alex \(verified\)\s+mini", out) is not None, out)+run(mini, "leave")+run(mini, "stop")out = cli("alice", "join", link.group(1), "--as", "bob", "--no-setup")check("joining a second team is refused while yours has others, and says how to switch","already in team 'vibes' (with alex)" in out and "reason-network leave" in out, out)# Installed on its own and started a team by itself first: the team link still just works.sam = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "sam"), REASON_NETWORK_MACHINE="mini")r = subprocess.run([BIN, "init", "solo", "--as", "sam", "--no-setup"], env=sam, capture_output=True, text=True, timeout=90)-r = subprocess.run([BIN, "join", link.group(1), "--as", "sam", "--no-setup"], env=sam, capture_output=True, text=True, timeout=90)-check("a team of one is swapped for the team you join", "Joined team vibes as sam on mini." in r.stdout, r.stdout + r.stderr)+# (With a link as earlier builds wrote it.)+old_link = link.group(1).replace("#rn1-", "#tincan1")+r = subprocess.run([BIN, "join", old_link, "--as", "sam", "--no-setup"], env=sam, capture_output=True, text=True, timeout=90)+check("a team of one is swapped for the team you join (a tincan1 link)", "Joined team vibes as sam on mini." in r.stdout, r.stdout + r.stderr)+check("…unverified, without a proof", re.search(r"sam\s+mini", r.stdout) is not None and "sam (verified)" not in r.stdout, r.stdout)subprocess.run([BIN, "leave"], env=sam, capture_output=True, timeout=60)subprocess.run([BIN, "stop"], env=sam, capture_output=True)os.makedirs(os.path.join(D, "bob"), exist_ok=True)@@ -135,7 +215,8 @@ meta = {"sessionId": "11111111-aaaa", "threadId": "11111111-aaaa"}time.sleep(7) # Claude's session registers after 3s; presence propagates every 2sout = codex.tool("list_team", {}, meta)claude_name = os.path.basename(ROOT).lower() + "-claude"-check("alice's agent sees alex's session across machines", claude_name in out and "alex · laptop" in out, out)+check("alice's agent sees alex's session across machines", claude_name in out and "alex (verified) · laptop" in out, out)+check("list_team gives the invite line", "Invite people with this line: Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)# (After Codex's first tool call registered it.) Nobody reports a status: Reason Network reads the plan step in progress from Codex's own transcript.rollout = os.path.join(D, "rollout.jsonl")plan = {"plan": [{"step": "set up fixtures", "status": "completed"}, {"step": "testing cross-machine Reason Network", "status": "in_progress"}]}@@ -259,6 +340,7 @@ check("remove alice (while her machine is off)", "Removed alice on desktop" in ocheck("removing someone replaces the team link", "team link changed" in out, out)out = cli("alex", "link")check("the new link differs from the old one", link.group(1) not in out, out)+check("…and is still an rn1 link", "#rn1-" in out, out)cli("alice", "team") # alice's machine comes back and dials alextime.sleep(10)out = cli("alice", "team")@@ -267,5 +349,7 @@ check("alice's machine learns it was removed when it reconnects", "not in a teamclaude.close()cli("alex", "stop")cli("alice", "stop")+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)