mcpmesh_local_api/protocol.rs
1//! mcpmesh-local/1 protocol types. Shared vocabulary between the daemon
2//! and its clients (porcelain, connect proxy, later the host shell). Wire framing
3//! is the family NDJSON codec — carried by the caller, not defined here.
4//!
5//! Request/response asymmetry: requests are one typed, closed enum (`Request`);
6//! responses are per-method typed structs deserialized from the JSON-RPC `result`
7//! Value — `Status` → [`StatusResult`], `RegisterService` → an ack, `OpenSession` →
8//! no JSON-RPC result at all: the socket STOPS being JSON-RPC and becomes a raw
9//! byte pipe.
10//!
11//! Additive-only: new fields (capabilities on `Hello`, groups/user_id on
12//! `PeerInfo`, device on `OpenSession`) MUST land as
13//! `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
14use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18/// The first exchange on any `*-local/N` socket (the family's hello convention).
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Hello {
21 pub api: String, // "mcpmesh-local/1"
22 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
23 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
24 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
25 /// release train). Additive: an older daemon omits it and it defaults to 0.
26 #[serde(default)]
27 pub api_minor: u32,
28 pub stack_version: String,
29}
30
31/// The kind of backend answering a service — the two valid values, enforced at the
32/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
33/// kind only, never the command/path (no transport vocabulary).
34///
35/// **`Default` is a construction convenience, not a claim (#148).** Neither value means "no
36/// backend" — a service has one or the other — so `Run` is chosen because it is the common config
37/// shape, and for no deeper reason. It exists so [`ServiceInfo`] can derive `Default` and a
38/// downstream test fixture stops breaking on every additive field we add.
39///
40/// It cannot mislead a reader of live data: the daemon sets `backend` explicitly on every
41/// `ServiceInfo` it builds, so a defaulted value only ever exists in a fixture whose author
42/// wrote it.
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum BackendKind {
46 #[default]
47 Run,
48 Socket,
49}
50
51/// A registered service as reported by `status` (no transport vocabulary).
52#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
53pub struct ServiceInfo {
54 pub name: String,
55 pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
56 /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
57 /// display nickname by the daemon (which owns the store); an unresolvable stable
58 /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
59 /// ids (surface discipline). Additive: default + skip-if-empty.
60 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 pub allow_display: Vec<String>,
62 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
63 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
64 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
65 /// daemon omits it and it reads as `false` (the persistent default).
66 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
67 pub ephemeral: bool,
68}
69
70/// A known peer as reported by `status` (nickname only — never the EndpointId).
71#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
72pub struct PeerInfo {
73 pub name: String,
74 pub services: Vec<String>,
75 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
76 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
77 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
78 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub user_id: Option<String>,
81 /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
82 /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
83 /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
84 /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
85 /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
86 /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
87 /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
88 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub principal: Option<String>,
91}
92
93/// HOW a peer is reached (#64): a direct/hole-punched QUIC path, or through a relay.
94///
95/// `rtt_ms` is NOT a proxy for this — a fast relay beats a slow direct path — and iroh's own
96/// distinction was being dropped at the mcpmesh boundary. Three things depend on it: a truthful
97/// locality claim ("this traffic never left the building"), honest disclosure that a relayed path
98/// depends on third-party infrastructure, and diagnostics, since "slow" has a different cause and
99/// fix in each case.
100///
101/// **Only `Direct` supports a locality claim.** `Unknown` means "we do not know", NOT "private" —
102/// rendering it as private is the one misuse that turns this field into a false privacy statement.
103/// The daemon errs the same way: when a relay path is active it reports [`Relay`](Self::Relay) even
104/// if a direct path is live too, because overstating privacy is worse than understating it.
105///
106/// `#[non_exhaustive]`: iroh already has a third address kind (a custom transport) that could
107/// warrant a variant, and adding one to a public enum later breaks every downstream exhaustive
108/// `match` — the lesson #58 paid for.
109#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
110#[serde(tag = "kind", rename_all = "snake_case")]
111#[non_exhaustive]
112pub enum PeerPath {
113 /// A direct or hole-punched QUIC path: the bytes did not transit a relay.
114 Direct,
115 /// Through a relay server. `url` is the relay in use when known.
116 Relay {
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 url: Option<String>,
119 },
120 /// Not known: never probed, no selected path, or a transport mcpmesh does not model.
121 ///
122 /// `#[serde(other)]` makes this the landing spot for a `kind` a client has never heard of. That
123 /// is what actually buys wire-additivity: `#[non_exhaustive]` only protects the Rust `match`,
124 /// and without this an older client hits `unknown variant` and fails to deserialize the WHOLE
125 /// `PeerReachability` — one new path kind would break every `status` response it reads.
126 #[default]
127 #[serde(other)]
128 Unknown,
129}
130
131/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean: a nickname, a
132/// bool, latency/age NUMBERS, the stable `eid:` principal (#42), and since #64 the PATH KIND —
133/// direct vs relay, plus the relay URL when relayed. Never a socket address, an IP, or a key: the
134/// path field says WHICH KIND of route is in use, never where the peer is.
135#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
136pub struct PeerReachability {
137 pub name: String, // the peer's nickname
138 pub reachable: bool, // result of the last probe (false if never probed)
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 /// Last measured round-trip, if reachable: dial + ping/pong, stamped AT THE PONG.
141 ///
142 /// It EXCLUDES the window the daemon spends afterwards determining which path the connection
143 /// settled on. Before 0.20.1 it included that window, so a relayed peer could never report
144 /// under 600ms and most of the figure was a deliberate wait rather than time on the wire —
145 /// an embedder read ~820ms across one LAN hop and reported it as a 66x latency regression
146 /// (#123). It is a wire-latency measurement now, so "relayed AND low rtt_ms" is a reachable
147 /// state and a usable diagnostic.
148 pub rtt_ms: Option<u64>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
151 /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
152 /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
153 /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
154 /// display data; never an authz input. Near-real-time when `status` is read (the probe
155 /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
156 #[serde(default, skip_serializing_if = "String::is_empty")]
157 pub meta: String,
158 /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
159 /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
160 /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
161 /// for a real row (`Option` only for additive round-trip). Machine-surface authz
162 /// vocabulary — the human `status` reachability line is unchanged. Additive:
163 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub principal: Option<String>,
166 /// HOW this peer is reached (#64) — see [`PeerPath`]. Captured by the same probe that sets
167 /// `reachable`/`rtt_ms`, so it shares their freshness: one TTL, one `age_secs`. `Unknown` for a
168 /// peer never probed. Additive (`#[serde(default)]`), so older rows and clients are unaffected.
169 #[serde(default)]
170 pub path: PeerPath,
171}
172
173/// WHICH producer emitted a [`StreamFrame::Reachability`] (#150). The two say different things
174/// about the world and license different user-facing statements, and until API 1.30 the frame
175/// carried no way to tell them apart.
176///
177/// Advisory attribution, never an authz input: it says where an observation CAME FROM, never who a
178/// peer is.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
180#[serde(rename_all = "snake_case")]
181#[non_exhaustive]
182pub enum ReachabilitySource {
183 /// A **probe** completed — a fresh throwaway dial (`status`/`subscribe` refreshing a stale
184 /// entry). It describes that dial and nothing else: a `Probe` frame saying `Relay` does NOT
185 /// mean any live connection is relayed.
186 Probe,
187 /// A **live session**'s selected path changed under it (#92 item 2). This is a claim about the
188 /// link a peer's traffic is actually on — the frame an embedder wants when warning that a call
189 /// which WAS direct silently is not any more.
190 Session,
191 /// The daemon did not say (`api_minor < 30`), or it named a producer this client predates.
192 ///
193 /// The DEFAULT, deliberately — see [`StreamFrame::Reachability`]. Like [`PeerPath::Unknown`] it
194 /// means "we do not know" and must never be collapsed into either confident case.
195 #[default]
196 Unknown,
197}
198
199/// Hand-written so an unrecognized producer lands on [`ReachabilitySource::Unknown`] instead of
200/// failing the whole frame. [`PeerPath`] gets this from `#[serde(other)]`, which serde allows only
201/// on an internally/adjacently tagged enum; this one is a plain string, so it is spelled out. The
202/// stakes are the same as there: without it, adding a third producer later would break every
203/// `Reachability` frame an older pinned client reads, not just the new field.
204///
205/// It accepts ANY input, not just an unrecognized string — `null`, a number, an object all read as
206/// `Unknown`. `#[serde(default)]` covers an ABSENT key and nothing else, so without this a proxy or
207/// non-Rust daemon that normalizes optional fields to `null` would fail every reachability frame
208/// while this module's doc promised the field could not break a parse. A degraded attribution is
209/// the fail-safe: `Unknown` already means "we do not know", which is exactly true of a value we
210/// could not read.
211impl<'de> Deserialize<'de> for ReachabilitySource {
212 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
213 struct AnySource;
214
215 /// Every hook answers `Unknown` except `visit_str`, so a shape we do not model degrades
216 /// instead of erroring. `visit_map`/`visit_seq` must DRAIN their input — leaving it
217 /// unconsumed desynchronizes the parser and fails the enclosing frame, which is the
218 /// failure this impl exists to avoid.
219 impl<'de> serde::de::Visitor<'de> for AnySource {
220 type Value = ReachabilitySource;
221
222 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
223 f.write_str("a reachability producer name")
224 }
225
226 fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
227 Ok(match s {
228 "probe" => ReachabilitySource::Probe,
229 "session" => ReachabilitySource::Session,
230 _ => ReachabilitySource::Unknown,
231 })
232 }
233
234 fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
235 Ok(ReachabilitySource::Unknown)
236 }
237
238 fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
239 Ok(ReachabilitySource::Unknown)
240 }
241
242 fn visit_some<D: serde::Deserializer<'de>>(
243 self,
244 d: D,
245 ) -> Result<Self::Value, D::Error> {
246 d.deserialize_any(AnySource)
247 }
248
249 fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<Self::Value, E> {
250 Ok(ReachabilitySource::Unknown)
251 }
252
253 fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<Self::Value, E> {
254 Ok(ReachabilitySource::Unknown)
255 }
256
257 fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<Self::Value, E> {
258 Ok(ReachabilitySource::Unknown)
259 }
260
261 fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<Self::Value, E> {
262 Ok(ReachabilitySource::Unknown)
263 }
264
265 fn visit_map<A: serde::de::MapAccess<'de>>(
266 self,
267 mut m: A,
268 ) -> Result<Self::Value, A::Error> {
269 while m
270 .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
271 .is_some()
272 {}
273 Ok(ReachabilitySource::Unknown)
274 }
275
276 fn visit_seq<A: serde::de::SeqAccess<'de>>(
277 self,
278 mut s: A,
279 ) -> Result<Self::Value, A::Error> {
280 while s.next_element::<serde::de::IgnoredAny>()?.is_some() {}
281 Ok(ReachabilitySource::Unknown)
282 }
283 }
284
285 d.deserialize_any(AnySource)
286 }
287}
288
289/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
290/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
291/// as-transport-vocab. Absent in a pure-pairing daemon.
292#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
293pub struct RosterStatus {
294 pub org_id: String,
295 pub serial: u64,
296 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
297 pub org_root_fingerprint: String, // short-word form
298}
299
300/// One reachable roster peer device as reported by `status` (the advisory presence read).
301/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
302/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
303/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
304#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
305pub struct PresencePeer {
306 pub user_id: String,
307 pub device_label: String,
308 pub role: String, // "primary" | "mirror" (roster vocabulary)
309 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
310 pub online: bool,
311 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
312 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
313 /// data; never an authz input. Additive: default + skip-if-empty.
314 #[serde(default, skip_serializing_if = "String::is_empty")]
315 pub meta: String,
316}
317
318/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
319/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
320/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
321/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
322/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
323/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
324/// an epoch — never an EndpointId.
325#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
326pub struct RecentPairing {
327 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
328 pub peer_nickname: String,
329 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
330 /// `PairResult.sas_code` carried. Never checked programmatically.
331 pub sas_code: String,
332 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
333 pub paired_at_epoch: u64,
334}
335
336#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
337pub struct StatusResult {
338 pub stack_version: String,
339 pub services: Vec<ServiceInfo>,
340 pub peers: Vec<PeerInfo>,
341 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
342 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
343 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub roster: Option<RosterStatus>,
345 /// The reachable roster peer devices (the advisory presence read), each with an `online`
346 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
347 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
348 #[serde(default, skip_serializing_if = "Vec::is_empty")]
349 pub presence: Vec<PresencePeer>,
350 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
351 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
352 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
353 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
354 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub self_user_id: Option<String>,
356 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
357 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
358 /// that has accepted no pairing since it started. Additive:
359 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
360 #[serde(default, skip_serializing_if = "Vec::is_empty")]
361 pub recent_pairings: Vec<RecentPairing>,
362 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
363 /// first probe completes. Additive: default + skip-if-empty.
364 #[serde(default, skip_serializing_if = "Vec::is_empty")]
365 pub reachability: Vec<PeerReachability>,
366 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
367 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
368 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
369 /// skip-if-empty so an older payload round-trips.
370 #[serde(default, skip_serializing_if = "String::is_empty")]
371 pub self_nickname: String,
372 /// On-disk footprint of this node's own state (#88), so an embedder can warn a user before
373 /// ENOSPC rather than after — the audit log's write rate is driven by inbound peer traffic,
374 /// and it shares a filesystem with `state.redb` and the device key. A LIVE read (computed
375 /// per `status` call), not a boot-time snapshot. `None` only in mesh-less control-only mode.
376 /// Additive: default + skip-if-none so an older payload round-trips.
377 #[serde(default, skip_serializing_if = "Option::is_none")]
378 pub storage: Option<StorageInfo>,
379 /// THIS node's own reachability posture (#90) — see [`SelfNetwork`]. Computed live per
380 /// call; `None` in mesh-less control-only mode. Additive: default + skip-if-none.
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 pub self_network: Option<SelfNetwork>,
383}
384
385/// The `status.self_network` block (#90): THIS node's own reachability posture — the first
386/// question in every "my message never arrived" investigation, previously unanswerable from
387/// either side of the API. Self-facing only: everything here is the node's own information
388/// (relay URLs come from its own config, sanitized; direct addresses already ride its invites).
389///
390/// `online` is iroh's own semantics — a home-relay connection is established. In
391/// `relay_mode = "disabled"` it is ALWAYS `false` with an empty `relays` list: that is a
392/// configuration, not an outage — render it as "LAN-only", never as a health warning.
393///
394/// Additive-only.
395///
396/// **`Default` is `{online: false, relays: []}` — which is exactly the shape above meaning
397/// "deliberately LAN-only" (#148).** The porcelain reads it that way and SUPPRESSES the "no relay
398/// connection" line for it. So a fixture built with `..Default::default()` claims a healthy
399/// LAN-only posture, not an unknown one. There is no third value for a `bool`; the honest way to
400/// say "nobody looked" is `StatusResult.self_network: None`, which is what a defaulted
401/// `StatusResult` gives you.
402#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
403pub struct SelfNetwork {
404 /// A home-relay connection is established (iroh's `online` definition). The signal #53's
405 /// `set_relays` never had: when this goes false on a relay-enabled node, the relay set is
406 /// the thing to look at.
407 pub online: bool,
408 /// The CONNECTED home relay's URL, sanitized to scheme + host + port (operator-supplied
409 /// relay URLs can carry userinfo tokens; `status` output gets screenshotted). `None` when
410 /// no relay is connected.
411 #[serde(default, skip_serializing_if = "Option::is_none")]
412 pub home_relay: Option<String>,
413 /// Every known home relay and its current connection state. Empty when no relays are
414 /// configured, or before the endpoint has selected any.
415 #[serde(default, skip_serializing_if = "Vec::is_empty")]
416 pub relays: Vec<RelayInfo>,
417 /// This endpoint's direct (non-relay) socket addresses — its own dialable coordinates.
418 #[serde(default, skip_serializing_if = "Vec::is_empty")]
419 pub direct_addrs: Vec<String>,
420 /// When the daemon's watcher last observed a TRANSITION (epoch seconds) — a change of
421 /// `online`, `home_relay`, or a relay's connection state; `direct_addrs` drift alone does
422 /// not stamp (nor emit a frame). OMITTED (not `null`) until the first observed transition
423 /// after boot, and from a point-in-time computation with no watcher running.
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 pub last_change_epoch: Option<i64>,
426 /// This node's `[network].presence_mode` (#89): `"paired"` | `"granted"` | `"off"` — who
427 /// currently gets an answer to the `mcpmesh/ping/1` reachability probe.
428 ///
429 /// Reported because the setting was otherwise **unobservable**: an operator who set it had no
430 /// way to confirm it took effect, and a product backing a privacy switch with it could not show
431 /// the user its real state. Always present from `api_minor >= 38`.
432 ///
433 /// **It is not "appear offline".** It withholds the pong payload and makes our own probe report
434 /// this node unreachable; it does not hide that the node is running (a QUIC application close
435 /// implies a completed handshake, and `mcpmesh/pair/1` answers any stranger by design). Do not
436 /// render it to users as invisibility.
437 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub presence_mode: Option<String>,
439 /// When the relay last reported that ANOTHER endpoint is presenting this node's identity
440 /// (#134, epoch seconds), or absent if never — the overwhelmingly common case.
441 ///
442 /// Two nodes booted from COPIES of one mesh root share an endpoint id. The relay can serve only
443 /// one, so the displaced node's peers simply go unreachable with nothing saying why; diagnosing
444 /// that cost a downstream real time. This is that missing "why".
445 ///
446 /// **Sticky, and a timestamp rather than a flag.** The condition is announced once, as the
447 /// displaced connection is dropped — it is not a state the relay keeps reporting — so a
448 /// self-clearing flag would read false by the time anyone called `status`. Judge staleness from
449 /// the epoch, exactly as with `last_change_epoch`.
450 ///
451 /// **Absence is not proof of uniqueness.** Detection needs an
452 /// `IdentityConflictLayer` in the process's `tracing` subscriber: the standalone daemon
453 /// installs one at boot, but an EMBEDDED node cannot (a subscriber is global and the host owns
454 /// it) and reports `None` until the host installs it. Never render absence as "identity
455 /// verified unique".
456 ///
457 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`. `api_minor >= 32`.
458 #[serde(default, skip_serializing_if = "Option::is_none")]
459 pub identity_conflict_epoch: Option<i64>,
460}
461
462/// One home relay's connection state (#90). No latency — per-relay RTT needs iroh's
463/// `net_report`, which is unstable-feature-gated as of 1.0.3; `connected` is the stable truth.
464#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
465pub struct RelayInfo {
466 /// Sanitized (scheme + host + port), like `home_relay`.
467 pub url: String,
468 pub connected: bool,
469}
470
471/// The `status.storage` block (#88): bytes actually on disk, by subsystem. Counts, never
472/// content. Additive-only.
473///
474/// **`Default` is all zeros, which reads as "measured, and found empty" (#148).** It is here so a
475/// fixture can build one field and elide the rest; it is not a way to say "unmeasured". For that,
476/// leave `StatusResult.storage` as `None` — a defaulted `StatusResult` does exactly that.
477#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
478pub struct StorageInfo {
479 /// Summed sizes of the monthly audit files (`<state>/audit/*.jsonl`).
480 pub audit_bytes: u64,
481 /// Size of the peer/trust state store (`state.redb`).
482 pub redb_bytes: u64,
483 /// Total size under the app-blob store directory; 0 when no blob store exists.
484 pub blobs_bytes: u64,
485}
486
487/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
488#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
489#[serde(deny_unknown_fields)]
490pub struct RegisterServiceParams {
491 pub name: String,
492 pub backend: BackendSpec,
493 pub allow: Vec<String>,
494 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
495 /// to the on-disk config, and automatically unregistered when the control connection that
496 /// registered it closes (and gone on daemon restart). For an embedder that serves a
497 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
498 /// socket path solely to keep a persisted registration valid, and the stale-registration
499 /// accumulation that comes with no unregister. Default false = the persistent behavior.
500 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
501 pub ephemeral: bool,
502 /// Per-service proxied-request rate (#63), falling back to `[limits].rate_limit_per_min`.
503 ///
504 /// **CLAMPED, never honoured upward.** `[limits].rate_limit_per_min` is a hard ceiling: a
505 /// larger value here is reduced to it, so a control call cannot uncap a service. Before #63
506 /// every service a peer could reach drew from one shared bucket, so a noisy service starved a
507 /// quiet one; buckets are now per `(service, endpoint)`.
508 ///
509 /// `0` is rejected rather than silently blocking every request. `api_minor >= 40`.
510 #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub rate_limit_per_min: Option<u32>,
512}
513
514/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
515/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
516/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
517/// list (an invite that grants nothing is useless — #34).
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct InviteParams {
521 #[serde(default)]
522 pub services: Vec<String>,
523 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
524 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
525 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
526 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub app_label: Option<String>,
528 /// How many times this invite may be redeemed (#87). Absent = **1**, the single-use behaviour
529 /// every existing caller already gets.
530 ///
531 /// Each redemption runs its OWN SAS ceremony and writes its own mutual peer rows — this is not
532 /// a shared or group identity, it is N independent pairings that happen to share one secret.
533 /// Onboarding a team stops being N mint-and-send rounds.
534 ///
535 /// Clamped to [`MAX_INVITE_USES`]; `0` is rejected rather than silently meaning "unusable". A
536 /// bearer credential's blast radius is `max_uses` × TTL, so it is opt-in and capped on purpose.
537 /// The value actually applied comes back in [`InviteResult::uses_remaining`] — read that rather
538 /// than assuming you got what you asked for.
539 ///
540 /// **`api_minor >= 35`, and sending it to an older daemon FAILS rather than degrading.**
541 /// `InviteParams` is `deny_unknown_fields`, so an `api_minor < 35` daemon answers `-32602
542 /// unknown field 'max_uses'` — it does not quietly mint a single-use invite. Loud is the right
543 /// behaviour; omit the field entirely when talking to one.
544 #[serde(default, skip_serializing_if = "Option::is_none")]
545 pub max_uses: Option<u32>,
546 /// YOUR local name for whoever redeems this invite (#87), overriding the nickname they claim
547 /// for themselves in the ceremony.
548 ///
549 /// The redeemer's self-claimed name is usually its hostname, so two same-model laptops collide
550 /// and the pairing is refused with [`ERR_NICKNAME_TAKEN`]. Before this field the only fixes
551 /// were to ask the other person to rename their machine, or to unpair whoever holds the name.
552 /// This lets you just call them something else.
553 ///
554 /// Local only: it is never sent to the peer and never affects what they call themselves or
555 /// you. It does **not** bypass the collision check — an alias that itself collides is refused
556 /// identically, because a duplicate display name makes your own `<peer>/<service>` routing
557 /// ambiguous whoever chose it.
558 ///
559 /// **Rejected with `max_uses > 1`:** one alias applied to every redeemer of a multi-use invite
560 /// would collide on the second redemption, so it is refused at MINT rather than producing an
561 /// invite that works exactly once. `api_minor >= 39`.
562 #[serde(default, skip_serializing_if = "Option::is_none")]
563 pub peer_nickname: Option<String>,
564 /// Mint a SELF-ENROLLMENT invite (#86): the redeemer becomes another device of **you**, not a
565 /// peer.
566 ///
567 /// The ceremony is the ordinary one — same secret, same SAS. What differs is the outcome:
568 /// neither side writes a peer row and nothing is granted, and the inviter signs a device→user
569 /// binding for the redeemer's authenticated endpoint. Both devices then present the same
570 /// `user_pk`, so every peer resolves them to ONE `user_id`.
571 ///
572 /// **The private key never moves.** The enrolling device signs a binding for the new device's
573 /// endpoint and hands over only that signature, so a second copy of the identity never exists.
574 /// The consequence: an enrolled device cannot enroll a third — enroll every device from the one
575 /// that holds the key.
576 ///
577 /// **The SAS matters more here than anywhere else.** The inviter signs a binding for whichever
578 /// endpoint redeems, so a redemption by an impostor mints *that impostor* a binding for your
579 /// identity. Requires `max_uses = 1` and an empty `services`, both refused otherwise.
580 /// `api_minor >= 43`.
581 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
582 pub as_self: bool,
583}
584
585/// The ceiling on [`InviteParams::max_uses`] (#87). Comfortably above "a team", far below "a
586/// fleet": one leaked invite line must not be able to enroll an unbounded number of devices for the
587/// whole 24h TTL.
588pub const MAX_INVITE_USES: u32 = 64;
589
590/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
591/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
592#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
593#[serde(deny_unknown_fields)]
594pub struct PairParams {
595 #[serde(default)]
596 pub invite_line: String,
597 /// YOUR local name for the inviter (#87), overriding the nickname their invite suggests.
598 ///
599 /// An invite carries the inviter's suggestion for what you should call them — usually their
600 /// hostname. If you already use that name for a different peer, the pairing is refused with
601 /// [`ERR_INVITE_NAME_CONFLICT`] and the message tells you to go ask them for a new invite.
602 /// This lets you resolve it yourself, without `set_nickname` (which rewrites your own GLOBAL
603 /// self-name — not what anyone wants in order to add one colleague).
604 ///
605 /// Local only: never sent to the inviter. It does **not** bypass the collision check — an alias
606 /// that itself collides is refused identically, because a duplicate display name makes your own
607 /// `<peer>/<service>` routing ambiguous whoever chose it. `api_minor >= 39`.
608 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub as_nickname: Option<String>,
610 /// Consent to complete a SELF-ENROLLMENT (#178): a `mcpmesh-enroll:` line is refused with
611 /// [`ERR_SELF_ENROLL_NOT_OFFERED`] unless this is set.
612 ///
613 /// Defaults to `false`, which is the whole point. #86 gave self-enrollment its own scheme so a
614 /// version-skewed redeemer refuses rather than pairing wrongly — but a CURRENT caller that only
615 /// ever meant to pair still ran the ceremony to completion, and learned which one it had run
616 /// from [`PairResult::enrolled_as_self`] only AFTER the device→user binding was written. That
617 /// binding admits this device to everyone who trusts the inviter's `user_id`, and it is
618 /// irrevocable short of rotating that user key — so "observe it afterwards" is not a place a
619 /// caller can refuse from.
620 ///
621 /// Set it when the ceremony is one your UI actually OFFERED ("add another of my devices"). Leave
622 /// it unset on an ordinary "join / add a contact" field: the refusal costs nothing, the invite is
623 /// untouched (nothing is dialled and nothing is burned), and the same line still works if the
624 /// person is then offered the real choice.
625 ///
626 /// To decide BEFORE calling — to show the right prompt rather than recover from a refusal — use
627 /// `mcpmesh_node::pairing::is_enrollment_line`. `api_minor >= 45`.
628 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
629 pub allow_self_enroll: bool,
630}
631
632/// Params of [`Request::PeerRemove`]: the nickname to unpair.
633#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
634#[serde(deny_unknown_fields)]
635pub struct PeerRemoveParams {
636 pub nickname: String,
637}
638
639/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
640/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
641#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
642#[serde(deny_unknown_fields)]
643pub struct PeerRenameParams {
644 #[serde(default)]
645 pub user_id: Option<String>,
646 #[serde(default)]
647 pub nickname: Option<String>,
648 pub to: String,
649}
650
651/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
652/// (iroh base32) plus the nickname and service allow list to install it under.
653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
654#[serde(deny_unknown_fields)]
655pub struct PeerAddParams {
656 pub nickname: String,
657 pub endpoint_id: String,
658 #[serde(default)]
659 pub allow: Vec<String>,
660}
661
662/// Params of [`Request::PeerEndorse`] (#65): vouch for a peer so a third party can install them.
663#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
664#[serde(deny_unknown_fields)]
665pub struct PeerEndorseParams {
666 /// The subject's endpoint id, `eid:<hex>` — usually a peer you are paired with, though the
667 /// daemon does not require that: an endorsement is YOUR statement, and the recipient decides
668 /// what it is worth.
669 pub subject: String,
670 /// The subject's user key, `b64u:`, when you are also vouching for that. The recipient will
671 /// additionally require the SUBJECT's own device binding before trusting it — see
672 /// [`PeerIntroduceParams::subject_binding`].
673 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub subject_user_id: Option<String>,
675}
676
677/// Result of [`Request::PeerEndorse`] (#65) — hand both fields to the recipient.
678#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
679pub struct PeerEndorseResult {
680 /// YOUR user id, `b64u:` — what the recipient passes as `endorsed_by`. They must already be
681 /// paired with you for it to resolve.
682 pub endorsed_by: String,
683 /// The signature, `b64u:` — what the recipient passes as `evidence`.
684 pub evidence: String,
685}
686
687/// Params of [`Request::PeerIntroduce`] (#65): install a peer vouched for by someone you are
688/// already paired with.
689///
690/// The endorsement replaces pairing's SAS with the endorser's signature, so you are trusting that
691/// endorser's judgment and key hygiene as well as their identity. It buys identity resolution only
692/// — see [`Request::PeerIntroduce`].
693#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
694#[serde(deny_unknown_fields)]
695pub struct PeerIntroduceParams {
696 /// The subject's endpoint id, `eid:<hex>` — who is being introduced.
697 pub subject: String,
698 /// The endorser's user public key, `b64u:`. MUST be the `user_id` of a CURRENTLY paired peer:
699 /// the chain has to terminate at someone you paired with yourself, so an endorsement from a
700 /// stranger — or from someone you have since unpaired — is refused.
701 pub endorsed_by: String,
702 /// The endorser's signature over the domain-separated preimage, `b64u:`.
703 pub evidence: String,
704 /// The subject's OWN user key, `b64u:`, so several of the subject's devices resolve to one
705 /// person. Part of the endorser's signed statement, so it cannot be added or removed after
706 /// the fact.
707 ///
708 /// **Requires `subject_binding` too, and is REFUSED without it.** A `user_id` is
709 /// authorization-bearing — service `allow` lists match on it — so the endorser vouching for it
710 /// is not enough: an endorser could otherwise name a *victim's* `user_id` (which is public, on
711 /// `status` and every audit record) for an attacker's endpoint, and the attacker would inherit
712 /// that victim's grants. The subject must prove the key is theirs.
713 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub subject_user_id: Option<String>,
715 /// The SUBJECT's own device→user binding for `subject_user_id`, `b64u:` — the same signature a
716 /// peer presents at pairing (`mcpmesh/join/device-binding/1`), proving *it* controls that user
717 /// key and that the key is bound to *this* endpoint.
718 ///
719 /// Two independent signatures are required for a `user_id`, and they say different things: the
720 /// endorser's says "I vouch for this endpoint", the subject's says "this user key is mine".
721 /// Neither alone is sufficient.
722 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub subject_binding: Option<String>,
724 /// YOUR local name for the subject. Same rules and the same collision guard as pairing (#87).
725 pub nickname: String,
726}
727
728/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
729/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
730#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
731#[serde(deny_unknown_fields)]
732pub struct OpenSessionParams {
733 #[serde(default)]
734 pub peer: String,
735 #[serde(default)]
736 pub service: String,
737}
738
739/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
740/// on FIRST install (`b64u:`; omit once pinned — config carries it).
741#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742#[serde(deny_unknown_fields)]
743pub struct RosterInstallParams {
744 pub path: String,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
746 pub org_root_pk: Option<String>,
747}
748
749/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
750/// never crosses the API.
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
752#[serde(deny_unknown_fields)]
753pub struct OrgJoinParams {
754 pub org_id: String,
755 pub org_root_pk: String,
756 pub user_id: String,
757 pub user_key: String,
758}
759
760/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
761/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
762/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
763/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
765#[serde(deny_unknown_fields)]
766pub struct SetAppMetadataParams {
767 pub metadata: String,
768}
769
770/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
771/// principal, or a `b64u:` user_id.
772#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
773#[serde(deny_unknown_fields)]
774pub struct PeerServicesParams {
775 pub peer: String,
776}
777
778/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
779/// caller — computed authoritatively on the peer (which owns the truth), always current, only
780/// the caller's own admitted services (never the peer's full registry).
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
782pub struct PeerServicesResult {
783 pub services: Vec<String>,
784}
785
786/// Params of [`Request::PeerDiagnostics`] (#140): the peer to dump — a nickname or an `eid:`
787/// device principal.
788#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
789#[serde(deny_unknown_fields)]
790pub struct PeerDiagnosticsParams {
791 pub peer: String,
792}
793
794/// Result of [`Request::PeerDiagnostics`] (#140): the DURABLE per-peer state this node carries,
795/// for diagnosing why a specific long-lived pairing behaves differently from a fresh one.
796///
797/// **This surface carries a PEER's transport coordinates on purpose.** The rendered porcelain is
798/// address-free everywhere — nicknames and path KINDS — because that discipline keeps a peer's
799/// coordinates out of screenshots. (`SelfNetwork.direct_addrs` already returns this node's OWN
800/// addresses on `status`; what is new here is another endpoint's.) The question this answers is
801/// "what address is this node about to dial, and where did it come from", which has no answer
802/// without the address. It is your own store's record of your own paired peers. Do not render it
803/// in ordinary porcelain, and read it before pasting it anywhere public.
804///
805/// The intended use is a paired capture: run it on BOTH ends of a stuck pairing and compare the
806/// stored hint against the live path each side reports.
807#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
808pub struct PeerDiagnosticsResult {
809 /// The peer's nickname as this node stores it.
810 pub nickname: String,
811 /// The peer's stable `eid:` device principal.
812 pub principal: String,
813 /// The peer's `b64u:` user_id if it proved a device→user binding at pairing.
814 #[serde(default, skip_serializing_if = "Option::is_none")]
815 pub user_id: Option<String>,
816 /// When the pairing was written (epoch seconds as a string), if recorded. A LONG-LIVED pairing
817 /// is exactly what #140 is about, so the age is part of the evidence.
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub paired_at: Option<String>,
820 /// The persisted dial HINT, verbatim as stored — the durable state a freshly paired identity
821 /// does not have. `None` for a peer added without one.
822 ///
823 /// It is MERGED with discovery rather than replacing it — iroh inserts it as one more
824 /// candidate path (`Source::App`) and then triggers address lookup.
825 ///
826 /// **But that lookup is skipped when a path is already selected.** iroh's
827 /// `trigger_address_lookup` returns early if `selected_path.is_some()`, and a selected path is
828 /// cleared only when the last connection to that peer closes. So on a pair that already holds
829 /// an open RELAYED connection — live sessions, dial-backs, a working relay — discovery does
830 /// NOT re-run, and this hint is the only addressing the dial contributes. Do not read "merged,
831 /// so a stale hint is harmless" as unconditional; it is least true in exactly the state a
832 /// stuck pairing is in.
833 ///
834 /// It is the only durable per-peer state ON THIS NODE'S DISK that the dial path reads, which
835 /// is what makes it the first thing to compare between two ends. It is not the only durable
836 /// state a long-lived identity carries — a published discovery record under the same key, and
837 /// [`SelfNetwork::identity_conflict_epoch`], live elsewhere.
838 #[serde(default, skip_serializing_if = "Option::is_none")]
839 pub last_addr: Option<String>,
840 /// The addresses parsed out of `last_addr`, for reading without a JSON round trip: IP
841 /// addresses verbatim, relay URLs as `relay <url>` and SANITIZED to scheme+host+port (an
842 /// operator's relay URL can carry a userinfo token, and this output is meant to be pasted into
843 /// an issue). Empty when the hint is absent, unparseable, or for a different endpoint — all of
844 /// which degrade to an id-only dial.
845 ///
846 /// A `relay …` entry with no IP alongside it is worth noticing: that hint can never punch.
847 #[serde(default, skip_serializing_if = "Vec::is_empty")]
848 pub hint_addrs: Vec<String>,
849 /// Whether `last_addr` parses AND its embedded id matches this peer. A `false` here with a
850 /// present `last_addr` means the hint is being silently discarded at every dial.
851 pub hint_usable: bool,
852 /// This node's LIVE view of the peer, read straight from the reachability cache — the same
853 /// values `status` reports, repeated here so one capture holds both the durable and the live
854 /// side. `None` when this peer has **never been probed**, which is the honest answer on a
855 /// freshly restarted daemon; it is not the same as unreachable.
856 ///
857 /// Read from the cache rather than through `status`'s projection deliberately: that projection
858 /// spawns a background probe for every stale peer, which would make this diagnostic a
859 /// participant in the reproduction it is meant to observe.
860 #[serde(default, skip_serializing_if = "Option::is_none")]
861 pub reachability: Option<PeerReachability>,
862}
863
864/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
865/// to remove — the deregistration mirror of `register_service`.
866#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
867#[serde(deny_unknown_fields)]
868pub struct UnregisterServiceParams {
869 pub name: String,
870}
871
872/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
873/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
874/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
875#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
876#[serde(deny_unknown_fields)]
877pub struct ServiceAllowParams {
878 pub service: String,
879 pub principal: String,
880}
881
882/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
883/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
884/// they stored at pairing time until a re-invite.
885#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
886#[serde(deny_unknown_fields)]
887pub struct SetNicknameParams {
888 pub nickname: String,
889}
890
891/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
892#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
893#[serde(deny_unknown_fields)]
894pub struct SetRosterUrlParams {
895 pub url: String,
896}
897
898/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
899/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
900/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
901/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
902/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
903/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
904/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
905/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
906#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
907#[serde(deny_unknown_fields)]
908pub struct SetRelaysParams {
909 pub relay_urls: Vec<String>,
910}
911
912/// Result of [`Request::SetRelays`] (#53).
913#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
914pub struct SetRelaysResult {
915 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
916 pub changed: bool,
917 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
918 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
919 /// live custom→custom path (already applied to the running endpoint).
920 pub restart_required: bool,
921}
922
923/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
924#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
925#[serde(deny_unknown_fields)]
926pub struct BlobPublishParams {
927 pub scope: String,
928 pub path: String,
929}
930
931/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
933#[serde(deny_unknown_fields)]
934pub struct BlobGrantParams {
935 pub scope: String,
936 pub principal: String,
937}
938
939/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
940///
941/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
942/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
943/// access to everything else.
944#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
945#[serde(deny_unknown_fields)]
946pub struct BlobRevokeParams {
947 pub scope: String,
948 pub principals: Vec<String>,
949}
950
951/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
952///
953/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
954/// this takes effect immediately for authorization — but the bytes stay in the local store, and
955/// there is no reclaim verb yet. Do not surface this to a user as deletion.
956#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
957#[serde(deny_unknown_fields)]
958pub struct BlobUnpublishParams {
959 pub scope: String,
960 pub hash: String,
961}
962
963/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
964///
965/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
966/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
967/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
968/// turn the original publisher going offline into a hang at every fetcher.
969///
970/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
971/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
972#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
973#[serde(deny_unknown_fields)]
974pub struct BlobRepublishParams {
975 pub scope: String,
976 pub hash: String,
977}
978
979/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
980#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
981#[serde(deny_unknown_fields)]
982pub struct BlobFetchParams {
983 pub ticket: String,
984 pub dest_path: String,
985}
986
987/// Params of [`Request::BlobFetchCancel`] (#172): stop every in-flight [`Request::BlobFetch`] of
988/// this blob.
989///
990/// Keyed by HASH, not by JSON-RPC id, and the reason is not aesthetic: [`crate::ControlClient`]
991/// borrows `&mut self` for a request's whole duration, so a client physically cannot send an
992/// id-keyed cancel down the connection whose request it would name. A hash is reachable from
993/// anywhere — including a fresh connection — and it is already the key a consumer holds, since
994/// every [`crate::StreamFrame::BlobTransfer`] carries it.
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
996#[serde(deny_unknown_fields)]
997pub struct BlobFetchCancelParams {
998 /// The blob's BLAKE3 hash, hex — as it appears on `BlobTransfer` frames and `BlobFetchResult`.
999 pub hash: String,
1000}
1001
1002/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
1003/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
1004///
1005/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
1006/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
1007/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
1008/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
1009/// identical to inline variant bodies.
1010///
1011/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
1012/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
1013/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
1014/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
1015/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
1016#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1017#[serde(tag = "method", content = "params", rename_all = "snake_case")]
1018pub enum Request {
1019 /// Register/update a `[services.*]` entry idempotently.
1020 RegisterService(RegisterServiceParams),
1021 Status,
1022 /// Mint a pairing invite granting `services` — single-use unless `max_uses` says otherwise
1023 /// (#87). The daemon
1024 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
1025 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
1026 /// `method` string generically; the tag comes from `rename_all`.
1027 Invite(InviteParams),
1028 /// Redeem a pairing invite. The daemon dials the inviter named by
1029 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
1030 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
1031 /// (snake_case); `method_of` reads the `method` string generically.
1032 ///
1033 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1034 Pair(PairParams),
1035 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
1036 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
1037 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
1038 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
1039 /// NOT severed here: existing sessions run to completion; the peer only loses the
1040 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
1041 /// `method_of` reads the `method` string generically (no per-variant arm).
1042 ///
1043 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1044 PeerRemove(PeerRemoveParams),
1045 /// Rename a contact's nickname (nickname) authoritatively. Renames the
1046 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
1047 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
1048 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
1049 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
1050 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
1051 /// host-privileged like the other pair ops.
1052 PeerRename(PeerRenameParams),
1053 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
1054 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
1055 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
1056 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
1057 /// vocabulary — do not build on it. Tag `"peer_add"`.
1058 PeerAdd(PeerAddParams),
1059 /// Install a peer from a SIGNED endorsement by someone you are already paired with (#65) —
1060 /// O(N) onboarding for a small group, without a fresh two-human SAS ceremony per pair.
1061 ///
1062 /// **It installs IDENTITY, never AUTHORIZATION.** The subject becomes resolvable; it is granted
1063 /// nothing. Service access stays principal-keyed in config (#38) and an explicit, separate act.
1064 /// That is what bounds the feature: a compromised endorser can make you KNOW about an attacker,
1065 /// it cannot make you SERVE one.
1066 ///
1067 /// Unlike [`PeerAdd`](Self::PeerAdd) — which is reserved precisely because the caller merely
1068 /// ASSERTS an id — this is verifiable: the endorsement is checked against a user key you
1069 /// already hold from pairing with the endorser. Tag `"peer_introduce"`.
1070 PeerIntroduce(PeerIntroduceParams),
1071 /// PRODUCE an endorsement of a peer, for someone else to redeem with
1072 /// [`PeerIntroduce`](Self::PeerIntroduce) (#65). The other half of an introduction: without it
1073 /// nothing can generate `evidence`, and the install half is unusable.
1074 ///
1075 /// Signs with THIS node's user key, so the result is only meaningful to someone who has paired
1076 /// with you. Endorsing does not change your own trust in the subject. Tag `"peer_endorse"`.
1077 PeerEndorse(PeerEndorseParams),
1078 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
1079 /// Distinct from the proxy's job: this returns a session the client streams.
1080 /// Named `open_session` rather than `connect` to avoid colliding
1081 /// with the `connect` porcelain.
1082 OpenSession(OpenSessionParams),
1083 /// Install a signed roster from a local file (the manual `internal roster install` path).
1084 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
1085 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
1086 /// pins the org root on FIRST install (`b64u:`); omit it
1087 /// once pinned (config carries it). Tag `"roster_install"`.
1088 RosterInstall(RosterInstallParams),
1089 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
1090 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
1091 /// `user_key` is a LOCAL path
1092 /// (the key never crosses the API). Tag `"org_join"`.
1093 OrgJoin(OrgJoinParams),
1094 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
1095 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
1096 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
1097 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
1098 /// `"set_roster_url"`.
1099 SetRosterUrl(SetRosterUrlParams),
1100 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
1101 /// daemon's own serialized config-write path (no lost-update window against a
1102 /// concurrent grant/registration) and update the in-memory name future invites
1103 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
1104 SetNickname(SetNicknameParams),
1105 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
1106 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
1107 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
1108 /// on restart; the embedder re-sets on startup).
1109 SetAppMetadata(SetAppMetadataParams),
1110 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
1111 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
1112 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
1113 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
1114 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
1115 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
1116 /// [`SetRelaysResult`]. Tag `"set_relays"`.
1117 SetRelays(SetRelaysParams),
1118 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
1119 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
1120 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
1121 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
1122 /// hot-reloads. Idempotent. Ack result.
1123 UnregisterService(UnregisterServiceParams),
1124 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
1125 /// and returns the service names whose allow admits the caller's principal. Answers
1126 /// [`PeerServicesResult`].
1127 PeerServices(PeerServicesParams),
1128 /// Dump the DURABLE per-peer state this node carries for one peer (#140) — the persisted dial
1129 /// hint, the pairing stamp, and the live reachability row, in one capture. A DIAGNOSTIC verb:
1130 /// unlike every other surface it carries transport vocabulary on purpose. Answers with
1131 /// [`PeerDiagnosticsResult`]. `api_minor >= 33`.
1132 PeerDiagnostics(PeerDiagnosticsParams),
1133 ServiceAllowGrant(ServiceAllowParams),
1134 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
1135 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
1136 /// Idempotent. Ack result.
1137 ServiceAllowRevoke(ServiceAllowParams),
1138 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
1139 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
1140 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
1141 /// Tag `"blob_publish"`.
1142 BlobPublish(BlobPublishParams),
1143 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
1144 /// nickname (the shared `principal_set` expansion). Tag
1145 /// `"blob_grant"`.
1146 BlobGrant(BlobGrantParams),
1147 /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
1148 BlobRevoke(BlobRevokeParams),
1149 /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
1150 /// bytes.
1151 BlobUnpublish(BlobUnpublishParams),
1152 /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
1153 /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
1154 /// two interchangeably after a fetch.
1155 BlobRepublish(BlobRepublishParams),
1156 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
1157 BlobList(BlobListParams),
1158 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
1159 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
1160 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
1161 BlobFetch(BlobFetchParams),
1162 /// Cancel every in-flight [`BlobFetch`](Self::BlobFetch) of one hash (#172). Answers a
1163 /// [`BlobFetchCancelResult`]; the cancelled fetches themselves answer [`ERR_CANCELLED`].
1164 /// Tag `"blob_fetch_cancel"`.
1165 BlobFetchCancel(BlobFetchCancelParams),
1166 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
1167 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
1168 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
1169 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
1170 /// `method_of` reads the `method` string generically (no per-variant arm).
1171 AuditSummary,
1172 /// Delete audit months strictly older than `before` (#88) — the retention lever the log
1173 /// never had. Local-only and owner-only (the control socket is the daemon owner's). Answers
1174 /// [`AuditPruneResult`]. Tag `"audit_prune"`.
1175 AuditPrune(AuditPruneParams),
1176 /// Read this node's LOCAL audit records, filtered and paged (#88) — the "show me everything
1177 /// you hold about me" verb. Local-only; nothing is transmitted. Answers
1178 /// [`AuditListResult`]. Tag `"audit_list"`.
1179 AuditList(AuditListParams),
1180 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
1181 /// connection STOPS being request/response after this call and becomes a one-way push stream
1182 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
1183 Subscribe,
1184}
1185
1186/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
1187/// computed porcelain-side from the invite's org_root_pk). Additive-only.
1188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1189pub struct OrgJoinResult {
1190 pub org_id: String,
1191}
1192
1193/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
1194/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
1195/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
1196///
1197/// Additive-only: any future field MUST land as
1198/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1200pub struct RosterInstallResult {
1201 pub org_id: String,
1202 pub serial: u64,
1203 /// How many live sessions were severed, for the porcelain's confirmation line.
1204 #[serde(default)]
1205 pub severed: u32,
1206}
1207
1208/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
1209/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
1210/// carve-out as the pairing invite line). Additive-only.
1211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1212pub struct BlobPublishResult {
1213 pub ticket: String,
1214 pub hash: String, // bare blake3 hex
1215}
1216
1217/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
1218/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
1219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1220pub struct ScopeInfo {
1221 pub name: String,
1222 pub hashes: Vec<String>,
1223 pub grants: Vec<String>,
1224 /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
1225 /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
1226 /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
1227 /// pre-`api_minor` 19 client sees exactly what it saw before.
1228 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1229 pub withdrawn: Vec<String>,
1230 /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
1231 #[serde(default)]
1232 pub hash_count: usize,
1233 /// Size of `grants`.
1234 #[serde(default)]
1235 pub grant_count: usize,
1236 /// Size of `withdrawn`.
1237 #[serde(default)]
1238 pub withdrawn_count: usize,
1239}
1240
1241/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
1242/// matters because the verb took no params before `api_minor` 20.
1243///
1244/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
1245/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
1246/// The control surface carries no strike bound, so the connection survives — but the caller gets an
1247/// opaque failure with no way to page, which is unusable rather than merely large.
1248#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1249#[serde(default, deny_unknown_fields)]
1250pub struct BlobListParams {
1251 /// EXACT scope name, never a prefix.
1252 pub scope: Option<String>,
1253 /// Only scopes containing this hash; the rendering you send is normalized first.
1254 pub hash: Option<String>,
1255 pub limit: Option<usize>,
1256 pub offset: Option<usize>,
1257 /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
1258 pub counts_only: bool,
1259}
1260
1261/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
1262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1263pub struct BlobScopeList {
1264 pub scopes: Vec<ScopeInfo>,
1265 /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
1266 /// complete answer from a clipped one.
1267 #[serde(default)]
1268 pub total: usize,
1269 /// True when more scopes matched than were returned. Page with `offset` to see the rest.
1270 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1271 pub truncated: bool,
1272}
1273
1274/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
1275/// Additive-only.
1276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1277pub struct BlobFetchResult {
1278 pub hash: String,
1279 pub bytes_len: u64,
1280}
1281
1282/// Result of [`Request::BlobFetchCancel`] (#172).
1283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1284pub struct BlobFetchCancelResult {
1285 /// True when a fetch of that hash was in flight and has been told to stop. False is NOT an
1286 /// error — it means nothing was fetching that blob here, which is also what a caller sees when
1287 /// it races a fetch that just finished.
1288 pub cancelled: bool,
1289}
1290
1291/// Params of [`Request::AuditPrune`] (#88): delete monthly audit files STRICTLY older than
1292/// `before` (that month itself is kept — delete-before, not delete-including). Rejects unknown
1293/// fields, and the daemon validates the `YYYY-MM` shape up front: a malformed month errors
1294/// loudly instead of string-comparing to nothing and reporting a clean no-op.
1295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1296#[serde(deny_unknown_fields)]
1297pub struct AuditPruneParams {
1298 /// A zero-padded `YYYY-MM` month key.
1299 pub before: String,
1300}
1301
1302/// Result of [`Request::AuditPrune`]: the month keys actually deleted, ascending. Empty when
1303/// nothing was older than `before` (idempotent).
1304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1305pub struct AuditPruneResult {
1306 pub deleted_months: Vec<String>,
1307}
1308
1309/// Params of [`Request::AuditList`] (#88). All filters optional and AND-combined; every field
1310/// absent lists everything (paged). Rejects unknown fields — a typo'd filter that silently
1311/// matched everything would let a "what do you hold about X" answer overclaim.
1312#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1313#[serde(deny_unknown_fields)]
1314pub struct AuditListParams {
1315 /// Inclusive `YYYY-MM` lower bound — month-file granularity (the rotation unit), so an
1316 /// out-of-range month is skipped without parsing it.
1317 #[serde(default, skip_serializing_if = "Option::is_none")]
1318 pub since: Option<String>,
1319 /// Inclusive `YYYY-MM` upper bound.
1320 #[serde(default, skip_serializing_if = "Option::is_none")]
1321 pub until: Option<String>,
1322 /// One of the wire kind strings (`session_open` / `session_close` / `request` /
1323 /// `blob_fetch` / `trust`). An UNKNOWN string is an error, never silently-all.
1324 #[serde(default, skip_serializing_if = "Option::is_none")]
1325 pub kind: Option<String>,
1326 /// The record's attributed peer nickname.
1327 #[serde(default, skip_serializing_if = "Option::is_none")]
1328 pub peer: Option<String>,
1329 /// Page size, default 500, clamped to 1000 — a month file can be arbitrarily large and the
1330 /// response is ONE JSON frame under the transport's frame cap, so the clamp is load-bearing
1331 /// (the same lesson as `blob_list`'s, minor 20).
1332 #[serde(default, skip_serializing_if = "Option::is_none")]
1333 pub limit: Option<u32>,
1334 /// Records to skip (after filtering), for paging.
1335 #[serde(default, skip_serializing_if = "Option::is_none")]
1336 pub offset: Option<u32>,
1337}
1338
1339/// Result of [`Request::AuditList`]: one page of matching records in chronological order
1340/// (oldest month first, in-file order within a month), plus the TOTAL match count so a caller
1341/// can page without a second counting call. `total` counts ALL matches, not the page.
1342#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1343pub struct AuditListResult {
1344 pub records: Vec<AuditRecord>,
1345 pub total: u64,
1346}
1347
1348/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
1349/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
1350/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
1351/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
1352/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
1353/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
1354///
1355/// Additive-only: any future field MUST land as
1356/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1357#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1358pub struct AuditSummaryResult {
1359 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
1360 /// peer to attribute) but IS in `total_sessions`.
1361 pub per_peer: Vec<(String, u64)>,
1362 /// Sessions opened per registered service name.
1363 pub per_service: Vec<(String, u64)>,
1364 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
1365 #[serde(default)]
1366 pub total_sessions: u64,
1367}
1368
1369/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
1370/// (the ONE pairing artifact deliberately carved out of the
1371/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
1372/// absolute expiry in epoch seconds (≤ now + 24h).
1373///
1374/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
1375/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
1376/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
1377/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
1378/// ceremony" note in `docs/local-protocol.md` (#35).
1379///
1380/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
1381/// so older payloads still deserialize.
1382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1383pub struct InviteResult {
1384 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
1385 pub invite_line: String,
1386 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
1387 pub expires_at_epoch: u64,
1388 /// How many redemptions this invite has left (#87) — **the value actually applied**, after the
1389 /// [`MAX_INVITE_USES`] clamp. `1` for an ordinary single-use invite.
1390 ///
1391 /// Reported so a caller that asked for more than the cap is told what it got rather than
1392 /// discovering it when the fourth colleague fails. Additive: `#[serde(default = "one")]`, so a
1393 /// response from an older daemon reads as single-use. `api_minor >= 35`.
1394 #[serde(default = "one_use")]
1395 pub uses_remaining: u32,
1396}
1397
1398/// The serde default for a `uses_remaining` field absent from an older payload or invite line: one
1399/// redemption, which is what every pre-#87 invite is.
1400pub fn one_use() -> u32 {
1401 1
1402}
1403
1404/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
1405/// redeemer's local name for the new peer) plus the display-only short authentication
1406/// code (SAS) — a few words the human reads aloud to a second channel to
1407/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
1408/// artifact (like the invite line), NOT a transport-vocabulary leak.
1409///
1410/// Additive-only: any future field MUST land as
1411/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1413pub struct PairResult {
1414 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
1415 pub peer_nickname: String,
1416 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
1417 /// sides for the out-of-band human check. Never sent on the wire, never checked
1418 /// programmatically.
1419 pub sas_code: String,
1420 /// TRUE when this redemption was a SELF-ENROLLMENT (#86): you are now another device of the
1421 /// inviter's person, not their peer. No peer row was written and nothing was granted.
1422 ///
1423 /// Reported so a caller can tell the two outcomes apart without inspecting its own store.
1424 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1425 pub enrolled_as_self: bool,
1426 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
1427 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
1428 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
1429 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
1430 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
1431 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1432 pub services: Vec<String>,
1433 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
1434 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
1435 #[serde(default, skip_serializing_if = "Option::is_none")]
1436 pub app_label: Option<String>,
1437 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
1438 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
1439 /// can align with its own — and the same value it may later pass to `open_session` to dial
1440 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
1441 /// binding (a legacy/keyless peer). Additive.
1442 #[serde(default, skip_serializing_if = "Option::is_none")]
1443 pub peer_user_id: Option<String>,
1444}
1445
1446/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
1447/// top of the base record schema: it removes no field and makes the JSONL self-describing so
1448/// a consumer can filter by class without guessing from which optional fields are present.
1449#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1450#[serde(rename_all = "snake_case")]
1451pub enum AuditKind {
1452 /// A mesh session opened (a backend was selected for an authenticated peer).
1453 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
1454 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
1455 SessionOpen,
1456 /// A mesh session closed (the backend returned / the session tore down).
1457 SessionClose,
1458 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
1459 Request,
1460 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
1461 BlobFetch,
1462 /// A trust mutation (pair, unpair, roster install/swap, revoke).
1463 Trust,
1464}
1465
1466/// One audit record — the union of the event classes, and the `record` payload of a
1467/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
1468/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
1469/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
1470/// `bytes_out`).
1471///
1472/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
1473/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
1474/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
1475#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1476pub struct AuditRecord {
1477 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
1478 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
1479 pub ts: String,
1480 pub kind: AuditKind,
1481 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
1482 /// local-only events with no remote peer (a manual roster install).
1483 #[serde(skip_serializing_if = "Option::is_none")]
1484 pub peer: Option<String>,
1485 #[serde(skip_serializing_if = "Option::is_none")]
1486 pub service: Option<String>,
1487 #[serde(skip_serializing_if = "Option::is_none")]
1488 pub method: Option<String>,
1489 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
1490 #[serde(skip_serializing_if = "Option::is_none")]
1491 pub tool: Option<String>,
1492 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
1493 #[serde(skip_serializing_if = "Option::is_none")]
1494 pub args_hash: Option<String>,
1495 /// Byte COUNT of the response sent back to the peer — a count, never the content.
1496 #[serde(skip_serializing_if = "Option::is_none")]
1497 pub bytes_out: Option<u64>,
1498 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
1499 #[serde(skip_serializing_if = "Option::is_none")]
1500 pub status: Option<String>,
1501 #[serde(skip_serializing_if = "Option::is_none")]
1502 pub latency_ms: Option<u64>,
1503 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
1504 #[serde(skip_serializing_if = "Option::is_none")]
1505 pub event: Option<String>,
1506 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
1507 /// nickname or `org/serial` (`Trust`).
1508 #[serde(skip_serializing_if = "Option::is_none")]
1509 pub target: Option<String>,
1510 /// The subject's STABLE principal, from the same gate resolution that produced `peer`
1511 /// (#57, `api_minor >= 29`). `peer` is a display name and collides — two devices under one
1512 /// nickname were indistinguishable in the stream and the on-disk log. Same argument and
1513 /// shape as `PeerInfo` (#41), `PeerReachability` (#42), and `ActiveSession` (#73).
1514 ///
1515 /// TWO NAMESPACES, deliberately: session/request/blob records attribute the DEVICE
1516 /// (`eid:<hex>`, like `ActiveSession` — the exact authenticated endpoint), while the trust
1517 /// `pair` record carries the value the grant appended to the allow (`b64u:<pk>` when the
1518 /// device presented a user binding, else `eid:`, #38). Joining a bound peer's sessions to
1519 /// its allow entry therefore goes through the `status` peers list (which carries BOTH the
1520 /// device principal and the `user_id`), not string equality on this field alone.
1521 ///
1522 /// **`peer_introduce` (#65) is the one exception, deliberately:** it carries the ENDORSER, not
1523 /// the subject. An introduction's whole security question is *who vouched for this peer*, and
1524 /// the subject is already in `target`. So `audit_list --peer <endorser>` finds the
1525 /// introductions that endorser caused, which is the query an operator actually runs.
1526 ///
1527 /// Deliberately absent on: `unpair` (may tear down several devices — no single subject),
1528 /// `roster_install` (purely local), and the failed-outbound-dial session record (our own
1529 /// dial, not a gate-resolved caller). Absent on every record written before 0.24.0.
1530 #[serde(default, skip_serializing_if = "Option::is_none")]
1531 pub principal: Option<String>,
1532}
1533
1534impl AuditRecord {
1535 fn base(ts: String, kind: AuditKind) -> Self {
1536 Self {
1537 ts,
1538 kind,
1539 peer: None,
1540 service: None,
1541 method: None,
1542 tool: None,
1543 args_hash: None,
1544 bytes_out: None,
1545 status: None,
1546 latency_ms: None,
1547 event: None,
1548 target: None,
1549 principal: None,
1550 }
1551 }
1552
1553 /// `principal` is an EXPLICIT parameter on every constructor (#57, kept from the original
1554 /// #72 design): a builder would let a call site silently omit it and reintroduce the
1555 /// collapsed-identity bug for that one event class. Pass `None` only for the documented
1556 /// no-single-subject records (see the field doc).
1557 pub fn session_open(
1558 ts: String,
1559 peer: Option<String>,
1560 service: String,
1561 principal: Option<String>,
1562 ) -> Self {
1563 let mut r = Self::base(ts, AuditKind::SessionOpen);
1564 r.peer = peer;
1565 r.service = Some(service);
1566 r.principal = principal;
1567 r
1568 }
1569
1570 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
1571 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
1572 /// reaches no backend and so is never audited by the far side's session guard — without a
1573 /// dedicated constructor. DRY: reuses the existing optional `status` field.
1574 pub fn with_status(mut self, status: &str) -> Self {
1575 self.status = Some(status.into());
1576 self
1577 }
1578
1579 pub fn session_close(
1580 ts: String,
1581 peer: Option<String>,
1582 service: String,
1583 principal: Option<String>,
1584 ) -> Self {
1585 let mut r = Self::base(ts, AuditKind::SessionClose);
1586 r.peer = peer;
1587 r.service = Some(service);
1588 r.principal = principal;
1589 r
1590 }
1591
1592 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
1593 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
1594 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
1595 #[allow(clippy::too_many_arguments)]
1596 pub fn proxied_request(
1597 ts: String,
1598 peer: Option<String>,
1599 service: String,
1600 method: String,
1601 tool: Option<String>,
1602 args_hash: String,
1603 bytes_out: u64,
1604 status: String,
1605 latency_ms: u64,
1606 principal: Option<String>,
1607 ) -> Self {
1608 let mut r = Self::base(ts, AuditKind::Request);
1609 r.peer = peer;
1610 r.service = Some(service);
1611 r.method = Some(method);
1612 r.tool = tool;
1613 r.args_hash = Some(args_hash);
1614 r.bytes_out = Some(bytes_out);
1615 r.status = Some(status);
1616 r.latency_ms = Some(latency_ms);
1617 r.principal = principal;
1618 r
1619 }
1620
1621 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
1622 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
1623 pub fn proxied_notification(
1624 ts: String,
1625 peer: Option<String>,
1626 service: String,
1627 method: String,
1628 tool: Option<String>,
1629 args_hash: String,
1630 principal: Option<String>,
1631 ) -> Self {
1632 let mut r = Self::base(ts, AuditKind::Request);
1633 r.peer = peer;
1634 r.service = Some(service);
1635 r.method = Some(method);
1636 r.tool = tool;
1637 r.args_hash = Some(args_hash);
1638 r.principal = principal;
1639 r
1640 }
1641
1642 pub fn blob_fetch(
1643 ts: String,
1644 peer: Option<String>,
1645 hash: String,
1646 status: String,
1647 principal: Option<String>,
1648 ) -> Self {
1649 let mut r = Self::base(ts, AuditKind::BlobFetch);
1650 r.peer = peer;
1651 r.target = Some(hash);
1652 r.status = Some(status);
1653 r.principal = principal;
1654 r
1655 }
1656
1657 pub fn trust(
1658 ts: String,
1659 event: String,
1660 target: Option<String>,
1661 principal: Option<String>,
1662 ) -> Self {
1663 let mut r = Self::base(ts, AuditKind::Trust);
1664 r.event = Some(event);
1665 r.target = target;
1666 r.principal = principal;
1667 r
1668 }
1669}
1670
1671/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
1672/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
1673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1674pub struct ActiveSession {
1675 pub peer: String,
1676 pub service: String,
1677 pub opened_at: i64,
1678 /// The caller's STABLE device principal, `eid:<hex>` (#73).
1679 ///
1680 /// `peer` is a display nickname and collides: two devices under one nickname, or two contacts
1681 /// sharing a display name, are indistinguishable in the live-session view. So "who is using my
1682 /// service right now", per-peer session counts, and any UI that lets a user act on a live
1683 /// session (revoke, disconnect, inspect) were all keyed on a collidable string.
1684 ///
1685 /// Same argument and same shape as [`PeerInfo`] (#41) and [`PeerReachability`] (#42).
1686 /// Nicknames NEVER authorize; this is the value to key on.
1687 ///
1688 /// **Snapshot only, for now.** `ActiveSession` appears in [`StreamFrame::Snapshot`] — there is
1689 /// no `active_sessions` on `StatusResult`. A client that keeps its view current by applying
1690 /// subsequent `session_open`/`session_close` events still has a collision problem: those are
1691 /// [`AuditRecord`]s and carry no principal (#57, unmerged). So the snapshot distinguishes two
1692 /// same-nickname devices and the next `session_close` for that nickname does not say which row
1693 /// to drop. Re-subscribe for an authoritative view until #57 lands.
1694 ///
1695 /// Always present for a real row — `Option` only so an older client round-trips. Additive.
1696 #[serde(default, skip_serializing_if = "Option::is_none")]
1697 pub principal: Option<String>,
1698}
1699
1700/// Which side of an app-blob transfer a [`StreamFrame::BlobTransfer`] describes (#82).
1701#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1702#[serde(rename_all = "snake_case")]
1703pub enum BlobDirection {
1704 /// We are SERVING bytes to a peer that dialed our app-blob ALPN.
1705 Serve,
1706 /// We are FETCHING bytes from a peer, via `blob_fetch`.
1707 Fetch,
1708}
1709
1710/// Where an app-blob transfer is in its life (#82).
1711#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1712#[serde(rename_all = "snake_case")]
1713pub enum BlobTransferState {
1714 /// The transfer began; `bytes_total` is known from here on.
1715 Started,
1716 /// Bytes advanced. COALESCED — see [`StreamFrame::BlobTransfer`].
1717 Progress,
1718 /// Finished successfully. Carries the FINAL byte count.
1719 Completed,
1720 /// Ended without completing (peer went away, refused, or the store errored).
1721 Aborted,
1722}
1723
1724/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
1725/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
1726/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
1727/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
1728/// them (see `docs/local-protocol.md` "Live event stream").
1729///
1730/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
1731/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
1732/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
1733/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
1734#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1735#[serde(tag = "type", rename_all = "snake_case")]
1736#[non_exhaustive]
1737pub enum StreamFrame {
1738 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
1739 /// reachability) so a fresh subscriber renders immediately without replaying history.
1740 Snapshot {
1741 active_sessions: Vec<ActiveSession>,
1742 reachability: Vec<PeerReachability>,
1743 /// THIS node's own reachability posture (#90), so a fresh subscriber renders it without
1744 /// a `status` poll. `None` in mesh-less control-only mode. Additive: default +
1745 /// skip-if-none so an older payload round-trips.
1746 #[serde(default, skip_serializing_if = "Option::is_none")]
1747 self_network: Option<SelfNetwork>,
1748 },
1749 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
1750 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
1751 /// `Box`, so the wire shape is the record's fields verbatim.
1752 Event { record: Box<AuditRecord> },
1753 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
1754 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
1755 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
1756 /// it returns, rather than on the next poll tick.
1757 ///
1758 /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
1759 /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
1760 /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
1761 /// `0` — the observation just completed.
1762 ///
1763 /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
1764 /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
1765 /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
1766 /// frames were impossible was reading a stale guarantee.
1767 ///
1768 /// Two producers, as of API 1.22 — and since 1.30 `source` says WHICH ONE, so the distinction
1769 /// is readable rather than inferred:
1770 ///
1771 /// - [`ReachabilitySource::Probe`] — a probe completing (`status`/`subscribe` refreshing a
1772 /// stale entry). It describes a throwaway dial, not anyone's live connection.
1773 /// - [`ReachabilitySource::Session`] — a live session whose selected path changed under it
1774 /// (#92 item 2). A claim about the link in use.
1775 ///
1776 /// The second producer is why `path` is trustworthy for a long-lived session: a session that
1777 /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
1778 /// mislabelled until something probes. `path` is a truth claim about where user data went, so
1779 /// `Unknown` means "we do not know" and must never be rendered as private.
1780 ///
1781 /// **`rtt_ms` is not a discriminator, and never was** (#150). Until 1.30 this doc said a
1782 /// session-sourced frame carries `rtt_ms: None` — true only of a FIRST observation, where no
1783 /// round trip was measured and none is invented. A session-sourced frame for an
1784 /// already-probed peer carries that probe's `rtt_ms: Some(..)`, because the path watcher
1785 /// deliberately leaves `rtt_ms`/`meta`/`probed_at` alone (refreshing them would stamp a stale
1786 /// RTT as fresh and suppress the corrective probe — #92 review). That is the common case for a
1787 /// peer probed at pairing time and then watched through a long call. Read `source`.
1788 Reachability {
1789 peer: PeerReachability,
1790 /// Which producer emitted this frame (#150). `api_minor >= 30`.
1791 ///
1792 /// Additive: `#[serde(default)]`, landing on [`ReachabilitySource::Unknown`] — NOT on
1793 /// `Probe`. A daemon at `api_minor` 22–29 already has both producers, so an absent field
1794 /// genuinely does not say which one ran; defaulting to `Probe` would assert the wrong
1795 /// producer for every session-sourced frame such a daemon emits, which is the exact
1796 /// ambiguity this field exists to remove.
1797 #[serde(default)]
1798 source: ReachabilitySource,
1799 },
1800 /// THIS node's own network posture CHANGED (#90): `online` flipped, the home relay moved,
1801 /// or a relay's connection state changed — pushed so an embedder learns "you just went
1802 /// unreachable" the moment it happens instead of on a poll tick, and so #53's `set_relays`
1803 /// finally has a signal telling someone to use it. `direct_addrs` drift alone does not
1804 /// emit (address churn is chatty and not a decision point; it rides the next frame).
1805 /// `api_minor >= 28`.
1806 SelfNetwork { self_network: SelfNetwork },
1807 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
1808 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
1809 Lagged { dropped: u64 },
1810 /// An app-blob transfer advanced (#82). Emitted on BOTH sides: `Serve` while we send bytes to
1811 /// a peer, `Fetch` while `blob_fetch` pulls them.
1812 ///
1813 /// **`Progress` is COALESCED, deliberately.** iroh-blobs reports progress per ~16 KiB chunk, so
1814 /// a 4 GiB transfer would push ~262k frames through a bounded ring and every subscriber would
1815 /// see `Lagged` — losing the audit events that share it. A frame is emitted on `Started`, on
1816 /// `Completed`/`Aborted`, and on `Progress` only after at least `max(1 MiB, total/100)` more
1817 /// bytes, so a transfer costs at most ~102 frames whatever its size.
1818 ///
1819 /// **Do not treat the last `Progress` as the total** — the final stride is usually skipped.
1820 /// `Completed` carries the final `bytes_done`.
1821 BlobTransfer {
1822 direction: BlobDirection,
1823 /// The blob's hash, hex.
1824 hash: String,
1825 bytes_done: u64,
1826 /// Known from `Started` onward; `None` only if the size was never reported.
1827 #[serde(default, skip_serializing_if = "Option::is_none")]
1828 bytes_total: Option<u64>,
1829 state: BlobTransferState,
1830 /// SERVING side only: the STABLE `eid:` device principal we are serving (#38 — never a
1831 /// display nickname). Always `eid:<hex>`: this comes from the authenticated endpoint, so it
1832 /// is NOT the same namespace as a grant written as a user_id or roster name. Absent when fetching, where the counterparty is named
1833 /// by the ticket rather than by a resolved identity.
1834 #[serde(default, skip_serializing_if = "Option::is_none")]
1835 peer: Option<String>,
1836 },
1837}
1838
1839/// Extract the `method` tag from a raw request value without deserializing the whole
1840/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
1841/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
1842/// methods (adjacent tagging rejects `params:{}` on unit variants).
1843pub fn method_of(v: &serde_json::Value) -> Option<&str> {
1844 v.get("method").and_then(serde_json::Value::as_str)
1845}
1846
1847/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
1848/// Config→BackendSpec is a hand-written match, not a serde passthrough.
1849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1850#[serde(rename_all = "snake_case")]
1851pub enum BackendSpec {
1852 Run {
1853 cmd: Vec<String>,
1854 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
1855 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
1856 /// these (identity is not spoofable by a service definition). Default empty.
1857 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1858 env: BTreeMap<String, String>,
1859 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
1860 #[serde(default, skip_serializing_if = "Option::is_none")]
1861 cwd: Option<String>,
1862 },
1863 Socket {
1864 path: String,
1865 },
1866}
1867
1868/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
1869/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
1870/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
1871/// `{}` (success) for an unknown name, which silently included every ephemeral service.
1872pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
1873/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
1874/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
1875pub const ERR_NO_SUCH_BLOB: i64 = -32041;
1876/// The blob was deliberately withdrawn from this scope (#107). Distinct from
1877/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
1878/// purpose — `blob_publish` from the file if the re-share is intended".
1879pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
1880/// `pair` was refused because the redeemer's nickname is already held by a DIFFERENT paired peer
1881/// (#87), so an embedder can branch on the one refusal that has a self-service remedy — rename and
1882/// redeem the same invite again — without reading the prose (#147).
1883///
1884/// Reading the prose was the only option before this code, and it does not survive translation: the
1885/// message is generated on the INVITER's side and travels to the redeemer, so the embedder that
1886/// DISPLAYS it cannot rewrite it into its own vocabulary except by substring-matching our copy.
1887/// Branch on this and write your own sentence naming your own rename affordance.
1888///
1889/// Deliberately narrow. It rides ONLY this refusal, which is sent exclusively to a caller that
1890/// proved possession of a live invite secret. The generic refusal keeps `-32000` and its opaque
1891/// reason: distinguishing unknown-vs-expired-vs-wrong-secret would be a redemption oracle.
1892pub const ERR_NICKNAME_TAKEN: i64 = -32043;
1893
1894/// The invite line's own `expires_at_epoch` has passed (#159). Decided LOCALLY, before dialing —
1895/// this says nothing about the inviter's state. Remedy: ask for a fresh invite.
1896pub const ERR_INVITE_EXPIRED: i64 = -32044;
1897
1898/// The inviter has **no outstanding invite at all** — its accept gate fast-closed the dial (#159).
1899///
1900/// This is as close to "expired or already used" as we can safely get, and the distinction matters:
1901/// it is a fact about the INVITER, not about the secret presented. Answering per-secret would be a
1902/// redemption oracle — a prober would learn which guessed secrets were ever real — which is why
1903/// [`ERR_INVITE_REFUSED`] stays deliberately undifferentiated. Remedy: ask for a fresh invite.
1904pub const ERR_INVITE_NOT_LIVE: i64 = -32045;
1905
1906/// The inviter's address could not be dialed at all (#159) — offline, asleep, or unroutable.
1907/// Remedy: check they are running, then retry the same invite; it is untouched.
1908pub const ERR_INVITER_UNREACHABLE: i64 = -32046;
1909
1910/// **The address-swap defense fired**: the TLS-authenticated peer is not the endpoint the invite
1911/// names (#159).
1912///
1913/// The one refusal here that must NOT be rendered as "try again". Something answered in place of
1914/// the machine the invite identifies — a substituted address, or a forged invite. An embedder that
1915/// treats every pairing failure as a friendly retry papers over exactly the attack this check
1916/// exists to catch. Remedy: do not retry; get the invite again through a channel you trust.
1917pub const ERR_INVITER_MISMATCH: i64 = -32047;
1918
1919/// The invite asks to be called a name this node already uses for a DIFFERENT peer (#159).
1920///
1921/// The redeemer-side mirror of [`ERR_NICKNAME_TAKEN`], and a distinct condition: that one is the
1922/// inviter refusing the redeemer's name, this is the redeemer refusing the inviter's suggestion.
1923/// Nothing is granted either way — a name confers no access (#38) — so this protects this node's
1924/// own display and routing clarity. Remedy: ask for an invite suggesting a different name.
1925pub const ERR_INVITE_NAME_CONFLICT: i64 = -32048;
1926
1927/// The inviter refused, and the cause is **deliberately withheld** (#159).
1928///
1929/// Unknown secret, expired secret, and wrong secret are one answer on purpose: telling them apart
1930/// is a redemption oracle. The code carries exactly as much as the prose already did — "that invite
1931/// did not work" — so a consumer can branch without parsing, and without learning anything a
1932/// prober could use. Remedy: ask for a fresh invite.
1933pub const ERR_INVITE_REFUSED: i64 = -32049;
1934
1935/// The request was stopped on purpose before it finished (#172) — today, a `blob_fetch` that
1936/// [`Request::BlobFetchCancel`] tripped.
1937///
1938/// A cancelled request still ANSWERS. Cancellation is cooperative rather than a task abort
1939/// precisely so this code can be delivered: an aborted task returns nothing, and the caller waits
1940/// forever on work that already stopped. Distinct from `-32000` because it is not a failure — the
1941/// caller (or its user) asked for it. Remedy: none; retry the fetch if the cancel was a mistake.
1942///
1943/// **What it does not promise:** partial chunks already streamed into the blob store stay there,
1944/// unlisted and unreclaimable, exactly as they do when a fetch fails. That is #80's reclaim gap,
1945/// unchanged by cancellation.
1946pub const ERR_CANCELLED: i64 = -32050;
1947
1948/// This control connection already has [`MAX_INFLIGHT`] requests running, so this one was refused
1949/// without being started (#172).
1950///
1951/// **Retryable, and cheap to retry** — retry after any response lands, or spread the load over a
1952/// second control connection. It is refused rather than queued deliberately: a queue is invisible
1953/// backpressure that a caller cannot tell apart from a slow daemon, and waiting for a permit inside
1954/// the read loop would reintroduce the head-of-line blocking concurrent dispatch exists to remove.
1955///
1956/// Not a security boundary — the control socket is the daemon owner's. It bounds the work one
1957/// connection can have outstanding so a buggy client cannot spawn unboundedly.
1958pub const ERR_TOO_MANY_INFLIGHT: i64 = -32051;
1959
1960/// The invite line is a SELF-ENROLLMENT (`mcpmesh-enroll:`) and the caller did not offer that
1961/// ceremony — [`PairParams::allow_self_enroll`] was unset (#178).
1962///
1963/// Decided from the line in hand, BEFORE any dial: nothing was contacted, no secret was revealed,
1964/// and the invite is untouched. Like [`ERR_INVITE_EXPIRED`] it therefore reveals nothing about the
1965/// inviter and is safe to name precisely.
1966///
1967/// Distinct from [`ERR_INVITE_REFUSED`] in the direction it points: that one is the inviter turning
1968/// US down, this one is US declining a ceremony we were never asked to run. Remedy: if the person
1969/// meant to add another of their OWN devices, offer that explicitly and retry the SAME line with
1970/// `allow_self_enroll`; otherwise they pasted the wrong link and want an ordinary
1971/// `mcpmesh-invite:` one.
1972pub const ERR_SELF_ENROLL_NOT_OFFERED: i64 = -32052;
1973
1974/// How many requests one control connection may have in flight at once (#172), after which it
1975/// answers [`ERR_TOO_MANY_INFLIGHT`]. Per connection, not per daemon.
1976pub const MAX_INFLIGHT: usize = 32;
1977
1978pub const API_NAME: &str = "mcpmesh-local/1";
1979/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
1980///
1981/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
1982/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
1983/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
1984/// methods, or a strictness change like params validation — bumped in the same change that makes
1985/// it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
1986/// than a minor it requires. It never resets except on a MAJOR bump.
1987///
1988/// It also bumps for a change to what a field MEANS with no change to its shape — six of the
1989/// thirty have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
1990/// to claim, and it was wrong in both directions: minor 9's entry records surface changes that
1991/// shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
1992pub const API_VERSION: &str = "1.45";
1993/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
1994/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
1995/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
1996/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
1997/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
1998/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
1999/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
2000/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
2001/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
2002/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
2003/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
2004/// observable contract did: a revoked principal's next session is refused even on a connection it
2005/// already holds, and its live connections are severed. Previously both waited for the peer to
2006/// disconnect on its own, which is unbounded (#54). A consumer can guard on
2007/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
2008/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
2009/// about an unknown service name — a name in neither the config nor the ephemeral registry now
2010/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
2011/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
2012/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
2013/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
2014/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
2015/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
2016/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
2017/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
2018/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
2019/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
2020/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
2021/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
2022/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
2023/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
2024/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
2025/// unpublish now survives a later republish via a per-scope withdrawal set, and
2026/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
2027/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
2028/// daemon with more scopes than that previously answered with
2029/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
2030/// the caller an opaque failure with no way to page. The connection survived: the control surface
2031/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
2032/// `total`/`truncated` (#84b); to 21 when a
2033/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
2034/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
2035/// that frame: a live per-session watcher that pushes when a session's selected path changes,
2036/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
2037/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
2038/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
2039/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
2040/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128); to 25
2041/// with [`ActiveSession::principal`] — the live-session view was keyed on a display nickname, so
2042/// two devices under one nickname were indistinguishable and any UI acting on a session (revoke,
2043/// disconnect, inspect) keyed on a collidable string (#73); to 26 when a
2044/// rate-limited inbound NOTIFICATION stopped being silently dropped and became a recorded audit
2045/// event — no type changed; the observable audit stream did (#76, #139); to 27 with the `audit_prune` /
2046/// `audit_list` verbs, `StatusResult::storage`, and the opt-in `[limits].audit_retain_months`
2047/// boot retention — the audit log stopped being a permanent, unbounded, unreadable record (#88);
2048/// to 28 with `StatusResult::self_network` / `StreamFrame::SelfNetwork` / the snapshot's copy —
2049/// the node's OWN reachability posture, previously unanswerable from either side of the API
2050/// (#90); to 29 with [`AuditRecord::principal`] — stable identity on the event stream and the
2051/// on-disk log, resolving #57's parked docs conflict in favour of the #41/#42/#73 line (the
2052/// audit surface bans secrets and raw hex, not the prefixed principal rendering); to 30 with
2053/// [`StreamFrame::Reachability`]'s `source` — the frame has had TWO producers since 22 with no way
2054/// to tell them apart, so an embedder could not distinguish "a throwaway dial went via a relay"
2055/// from "the link this call is on just degraded", and had to hedge every message down to the
2056/// weaker claim. `rtt_ms: None` was never the discriminator the doc implied (#150); to 31 with
2057/// [`ERR_NICKNAME_TAKEN`] — the nickname-collision `pair` refusal is branchable instead of
2058/// `-32000`, so an embedder writes its own recovery copy rather than substring-matching ours. The
2059/// prose changed with it: it named the `set_nickname` CONTROL VERB as the remedy, which a GUI user
2060/// cannot type, and the refusal is generated inviter-side so the embedder displaying it could not
2061/// rewrite it (#147); to 32 with [`SelfNetwork::identity_conflict_epoch`] — two nodes booted from
2062/// COPIES of one mesh root share an endpoint id, and the displaced one's peers went unreachable
2063/// with nothing saying why. The relay reports it and iroh only `warn!`s it, so the fact existed
2064/// and was unreadable (#134); to 33 with the `peer_diagnostics` verb — a long-lived pairing that
2065/// cannot hole-punch while a fresh identity on the same hardware can differs only in DURABLE
2066/// per-peer state, and none of it was readable from outside the daemon (#140); to 34 when
2067/// outstanding invites became DURABLE — `invite.expires_at_epoch` changed meaning from an upper
2068/// bound on the daemon's process lifetime to the real lifetime, and `invite` gained an error where
2069/// it previously always succeeded. No shape changed, which is exactly the class minor 10 records:
2070/// guard on `api_minor >= 34` before telling a user their invite will still be good tomorrow
2071/// (#87b); to 35 with `InviteParams.max_uses` + `InviteResult.uses_remaining` — a bounded
2072/// multi-use invite, so onboarding a team is one link rather than one ceremony per person. Each
2073/// redemption still runs its own SAS and writes its own peer rows; it is N pairings sharing a
2074/// secret, never a group identity (#87); to 36 with branchable codes for the rest of the ONBOARDING
2075/// refusals — expired line, no live invite, inviter unreachable, id mismatch, name conflict, and
2076/// the deliberately-opaque refusal. `ERR_NICKNAME_TAKEN` had been the only coded pairing failure,
2077/// so every other one arrived as `-32000` and an embedder could either forward our prose to end
2078/// users or substring-match it (#159); to 45 with [`PairParams::allow_self_enroll`] +
2079/// [`ERR_SELF_ENROLL_NOT_OFFERED`] — `pair` now REFUSES a `mcpmesh-enroll:` line unless the caller
2080/// asked for that ceremony. A behaviour change for existing callers, deliberately: at 43-44 a caller
2081/// whose UI only ever offered "add a contact" completed a self-enrollment and learned which
2082/// ceremony it had run from `enrolled_as_self` afterwards — by which point the device→user binding
2083/// was written and irrevocable short of rotating the user key (#178). The refusal is decided from
2084/// the line before any dial, so the invite survives it and the same line works once the ceremony is
2085/// actually offered. Guard on `>= 45` before sending the field — below it `deny_unknown_fields`
2086/// rejects the whole request. Note what the guard means: a daemon BELOW 45 gives a caller no way to
2087/// decline, so a UI that does not offer device enrollment should require `>= 45` rather than pair
2088/// without it; to 44 when control responses stopped arriving in REQUEST
2089/// order and the `blob_fetch_cancel` verb landed (#172). The daemon now dispatches each request
2090/// CONCURRENTLY on its connection, so a `blob_fetch` no longer stalls every other verb behind it —
2091/// and responses arrive in COMPLETION order. JSON-RPC ids make that legal and the in-tree
2092/// `ControlClient` cannot observe it (one request at a time, by construction), but a hand-rolled
2093/// client that pipelines and matches responses POSITIONALLY breaks. A connection also caps
2094/// in-flight requests and refuses over it with [`ERR_TOO_MANY_INFLIGHT`], and closing a control
2095/// connection now genuinely ABORTS its in-flight work rather than letting it run to completion
2096/// unread. Guard on `>= 44` before pipelining, before sending `blob_fetch_cancel`, and before
2097/// treating [`ERR_CANCELLED`] as unexpected; to 43 with `InviteParams::as_self` — SELF-ENROLLMENT, so one
2098/// person's devices share a `user_id` instead of appearing as unrelated strangers (#86). The
2099/// ceremony is ordinary pairing; the outcome is a device→user binding rather than a peer row, and
2100/// the private key never moves. Guard on `>= 43`. What this entry did NOT say, and 45 fixed: the
2101/// distinct scheme closes the version-SKEW hazard (a pre-43 redeemer silently over-granting) and
2102/// closes nothing for a CURRENT redeemer, which had no way to decline a ceremony it never offered
2103/// (#178); to 42 with the `peer_introduce` + `peer_endorse`
2104/// verbs — install a peer from a
2105/// SIGNED endorsement by someone you are already paired with, so a small group onboards in O(N)
2106/// instead of O(N²) two-human ceremonies (#65). It installs IDENTITY only and grants nothing, which
2107/// is what bounds it. Guard on `>= 42`; to 41 with `StreamFrame::BlobTransfer` — live app-blob
2108/// transfer progress on both the serving and fetching side (#82 ask 2), so an embedder can draw a
2109/// real progress bar instead of an indeterminate spinner. Guard on `>= 41` before expecting the
2110/// frame. NOTE what it did NOT bring, and 44 did: at 41 `blob_fetch` still blocked its whole
2111/// control connection for the transfer and nothing could cancel it (#172) — progress arrived on the
2112/// SUBSCRIBE connection, which is a different one; to 40 with `[services.<name>].rate_limit_per_min` +
2113/// `RegisterServiceParams::rate_limit_per_min` — proxied-request buckets became per
2114/// `(service, endpoint)` instead of one shared per-endpoint bucket, so a noisy service can no
2115/// longer starve a quiet one (#63). `-32053` changes meaning with it: it is now per-service, so a
2116/// consumer that backs off globally on one is backing off further than it needs to. Guard on
2117/// `>= 40` before sending the field or narrowing a back-off; to 39 with `PairParams::as_nickname` +
2118/// `InviteParams::peer_nickname` — LOCAL aliases for the other party, so a nickname collision is
2119/// resolvable by the person who hit it instead of requiring the other human to rename a machine or
2120/// re-mint. #147 made the collision diagnosable; this makes it fixable. Guard on `>= 39` before
2121/// offering an alias field in a UI: below it `deny_unknown_fields` rejects the whole request
2122/// (#87); to 38 with `[network].presence_mode` + `SelfNetwork.
2123/// presence_mode` — `reachable: false` gained a new meaning ("up, paired, and deliberately not
2124/// answering"), and `peer_services` flips from "reachable, empty list" to "unreachable" for a
2125/// caller holding no grant. A consumer must guard on `api_minor >= 38` before telling a user their
2126/// peer is offline, since below it that verdict could not mean this (#89); to 37 when the reserved
2127/// `mcpmesh/*` `_meta` namespace began
2128/// being enforced on EVERY proxied frame rather than the session's first. `run_session` treats
2129/// frame 1 as the `initialize` whatever its method is, so a caller could send any other method
2130/// first and put its real `initialize` — with a forged `mcpmesh/peer` naming another principal,
2131/// forged `groups` and all — in frame 2, where nothing stripped or injected. No shape changed;
2132/// what changed is whether `_meta["mcpmesh/peer"]` can be trusted, which is the entire reason a
2133/// backend reads it. Guard on `api_minor >= 37` before keying authorization on that value (#164).
2134///
2135/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
2136/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
2137/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
2138/// be that class and did bump; do not infer from them that every such change will. When bumping
2139/// several minors at once, read this block end to end AND the release notes, not the diff.
2140///
2141/// That class is bigger than it looks: **10, 17, 21, 22, 23, 24 and 37 all shipped with no change
2142/// to any type in this file** — they moved meaning, not shape. Seven of the forty, and 37 is
2143/// a SECURITY fix, which is the case where a consumer most needs the guard. 38 adds a field, but
2144/// its REAL content is a meaning change to `reachable` — the field exists so the new meaning is
2145/// observable at all. A downstream
2146/// that diffs types across a multi-minor bump sees nothing for any of them.
2147pub const API_MINOR: u32 = 45;
2148
2149#[cfg(test)]
2150mod tests {
2151 use super::*;
2152
2153 /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
2154 /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
2155 /// privacy guarantee that daemon never made.
2156 #[test]
2157 fn peer_path_tags_and_defaults_to_unknown() {
2158 let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
2159 assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
2160 assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
2161 let relay = tagged(PeerPath::Relay {
2162 url: Some("https://relay.example/".into()),
2163 });
2164 assert_eq!(relay["kind"], "relay");
2165 assert_eq!(relay["url"], "https://relay.example/");
2166 // A relay whose URL we do not know still tags as relay, with the key elided.
2167 let bare = tagged(PeerPath::Relay { url: None });
2168 assert_eq!(bare["kind"], "relay");
2169 assert!(bare.get("url").is_none(), "elided, not null: {bare}");
2170
2171 // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
2172 // row. Without `#[serde(other)]` an unknown `kind` errors out of
2173 // `PeerReachability` entirely, so one new variant would break every `status` read an
2174 // older pinned client does.
2175 let future: PeerPath =
2176 serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
2177 assert_eq!(future, PeerPath::Unknown);
2178 let row: PeerReachability = serde_json::from_value(serde_json::json!({
2179 "name": "bob", "reachable": true, "path": {"kind": "quantum"}
2180 }))
2181 .expect("an unknown path kind must not fail the whole row");
2182 assert_eq!(row.path, PeerPath::Unknown);
2183 assert!(row.reachable, "the rest of the row survives");
2184
2185 // A pre-#64 row: no `path` key.
2186 let old = serde_json::json!({"name": "bob", "reachable": true});
2187 let parsed: PeerReachability = serde_json::from_value(old).unwrap();
2188 assert_eq!(
2189 parsed.path,
2190 PeerPath::Unknown,
2191 "an older daemon's row must never imply a direct path"
2192 );
2193 }
2194
2195 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
2196 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
2197 /// consumer projects both through one code path.
2198 #[test]
2199 fn reachability_frame_tags_and_round_trips() {
2200 let frame = StreamFrame::Reachability {
2201 peer: PeerReachability {
2202 name: "bob".into(),
2203 reachable: true,
2204 rtt_ms: Some(12),
2205 age_secs: Some(0),
2206 meta: String::new(),
2207 principal: Some("eid:beef".into()),
2208 path: Default::default(),
2209 },
2210 source: ReachabilitySource::Probe,
2211 };
2212 let v = serde_json::to_value(&frame).unwrap();
2213 assert_eq!(v["type"], "reachability");
2214 assert_eq!(v["peer"]["name"], "bob");
2215 assert_eq!(v["peer"]["reachable"], true);
2216 assert_eq!(
2217 v["peer"]["age_secs"], 0,
2218 "a transition frame is fresh by construction: {v}"
2219 );
2220 assert_eq!(v["source"], "probe", "#150: the producer is named: {v}");
2221 let back: StreamFrame = serde_json::from_value(v).unwrap();
2222 assert_eq!(back, frame);
2223 }
2224
2225 /// #150: the frame's `source` wire shape, and the two ways it must degrade.
2226 ///
2227 /// The default is the load-bearing part. An absent key comes from a daemon at `api_minor`
2228 /// 22–29, which ALREADY has both producers — so it must land on `Unknown`, never on `Probe`.
2229 /// Defaulting to `Probe` would tell a consumer "a throwaway dial saw this" about frames that
2230 /// were a live session degrading, which is the ambiguity the field exists to remove.
2231 #[test]
2232 fn reachability_source_tags_and_defaults_to_unknown() {
2233 let tagged = |s: ReachabilitySource| serde_json::to_value(s).unwrap();
2234 assert_eq!(tagged(ReachabilitySource::Probe), "probe");
2235 assert_eq!(tagged(ReachabilitySource::Session), "session");
2236 assert_eq!(tagged(ReachabilitySource::Unknown), "unknown");
2237 for s in [
2238 ReachabilitySource::Probe,
2239 ReachabilitySource::Session,
2240 ReachabilitySource::Unknown,
2241 ] {
2242 let back: ReachabilitySource = serde_json::from_value(tagged(s)).unwrap();
2243 assert_eq!(back, s, "round trip");
2244 }
2245
2246 let peer = serde_json::json!({"name": "bob", "reachable": true});
2247
2248 // A pre-#150 frame: no `source` key at all.
2249 let old: StreamFrame =
2250 serde_json::from_value(serde_json::json!({"type": "reachability", "peer": peer}))
2251 .expect("an older daemon's frame must still parse");
2252 let StreamFrame::Reachability { source, .. } = old else {
2253 panic!("expected a reachability frame");
2254 };
2255 assert_eq!(
2256 source,
2257 ReachabilitySource::Unknown,
2258 "an api_minor 22-29 daemon has BOTH producers, so an absent key must not claim Probe"
2259 );
2260
2261 // A producer from a NEWER daemon must degrade to Unknown, not fail the whole frame — the
2262 // same stake `PeerPath` buys with `#[serde(other)]`. Without the hand-written Deserialize
2263 // a third producer would break every Reachability frame an older pinned client reads.
2264 let future: StreamFrame = serde_json::from_value(
2265 serde_json::json!({"type": "reachability", "peer": peer, "source": "telemetry"}),
2266 )
2267 .expect("an unknown producer must not fail the whole frame");
2268 let StreamFrame::Reachability { source, peer } = future else {
2269 panic!("expected a reachability frame");
2270 };
2271 assert_eq!(source, ReachabilitySource::Unknown);
2272 assert!(peer.reachable, "the rest of the frame survives");
2273 }
2274
2275 /// #148: a defaulted status is EMPTY and honest — the fixture ergonomic an embedder gets in
2276 /// exchange for us adding fields.
2277 ///
2278 /// Its content is the load-bearing part. A downstream test that omits a field must not thereby
2279 /// assert something: no phantom peers or services, and the optional blocks absent rather than
2280 /// zeroed. `storage: Some(StorageInfo::default())` would read as "0 bytes on disk", which is a
2281 /// measurement nobody took.
2282 #[test]
2283 fn a_defaulted_status_is_empty_and_claims_nothing() {
2284 let d = StatusResult::default();
2285 assert!(d.peers.is_empty() && d.services.is_empty(), "{d:?}");
2286 assert!(d.reachability.is_empty() && d.presence.is_empty(), "{d:?}");
2287 assert!(d.recent_pairings.is_empty(), "{d:?}");
2288 assert_eq!(d.roster, None, "no roster is not an empty roster");
2289 assert_eq!(d.storage, None, "absent, not 0 bytes — nobody measured");
2290 assert_eq!(d.self_network, None, "absent, not offline — nobody looked");
2291 assert_eq!(d.self_user_id, None);
2292 assert!(
2293 d.stack_version.is_empty() && d.self_nickname.is_empty(),
2294 "{d:?}"
2295 );
2296
2297 // The pattern the issue actually asks for: additive growth stops breaking fixtures.
2298 let fixture = StatusResult {
2299 peers: vec![PeerInfo {
2300 name: "bob".into(),
2301 ..Default::default()
2302 }],
2303 ..Default::default()
2304 };
2305 assert_eq!(fixture.peers[0].name, "bob");
2306 assert!(fixture.services.is_empty());
2307
2308 // A default round-trips, so the elide-vs-null discipline holds for one too.
2309 let v = serde_json::to_value(&d).unwrap();
2310 assert!(v.get("roster").is_none(), "elided, not null: {v}");
2311 assert!(v.get("storage").is_none(), "elided, not null: {v}");
2312 let back: StatusResult = serde_json::from_value(v).unwrap();
2313 assert_eq!(back, d);
2314 }
2315
2316 /// #148: a defaulted reachability row is NOT reachable and makes NO path claim.
2317 ///
2318 /// This is the one default where a wrong choice would be a false guarantee rather than a
2319 /// harmless placeholder — the same trap `PeerPath`'s `#[default] Unknown` exists to avoid
2320 /// (#64), now reachable through a second door. A fixture that forgot to set `path` must not
2321 /// thereby assert the peer was reached directly, and one that forgot `reachable` must not
2322 /// claim it was up.
2323 #[test]
2324 fn a_defaulted_reachability_row_asserts_nothing_about_the_peer() {
2325 let d = PeerReachability::default();
2326 assert!(!d.reachable, "an unset row must not claim the peer is up");
2327 assert_eq!(
2328 d.path,
2329 PeerPath::Unknown,
2330 "an unset path must never read as Direct — that is a privacy claim no one made"
2331 );
2332 assert_eq!(d.rtt_ms, None, "no measurement was taken");
2333 assert_eq!(d.age_secs, None, "never probed");
2334 assert_eq!(d.principal, None);
2335 assert!(d.name.is_empty() && d.meta.is_empty());
2336 }
2337
2338 /// #148 gate: the REST of the new defaults, which the first pass left entirely unasserted —
2339 /// moving `BackendKind`'s `#[default]` to `Socket` failed nothing across the whole workspace.
2340 ///
2341 /// Each assertion below is the conservative reading of a field that could otherwise let a
2342 /// fixture assert something by omission.
2343 #[test]
2344 fn the_remaining_defaults_are_conservative() {
2345 let s = ServiceInfo::default();
2346 assert!(
2347 s.allow.is_empty(),
2348 "an unset allow must admit NOBODY — empty is deny (the gate's `any()` is false on an \
2349 empty list), and a permissive default here would be an authz hole reachable from a \
2350 fixture"
2351 );
2352 assert!(s.allow_display.is_empty() && s.name.is_empty());
2353 assert!(
2354 !s.ephemeral,
2355 "persistent is the conservative reading, and matches the wire default"
2356 );
2357 assert_eq!(
2358 s.backend,
2359 BackendKind::Run,
2360 "the documented choice — a convenience, not a claim; pinned so it cannot drift \
2361 silently out of step with its own rustdoc"
2362 );
2363 assert_eq!(BackendKind::default(), BackendKind::Run);
2364
2365 let p = PeerInfo::default();
2366 assert!(p.name.is_empty() && p.services.is_empty());
2367 assert_eq!(p.user_id, None, "no identity was proven");
2368 assert_eq!(p.principal, None);
2369
2370 // The gate's finding: this default is the documented "deliberately LAN-only" posture,
2371 // which the porcelain renders as healthy and NOT as a warning. It is unavoidable (a bool
2372 // has no third state) but it must stay deliberate, so it is pinned rather than left to
2373 // be rediscovered by whoever writes the next fixture.
2374 let n = SelfNetwork::default();
2375 assert!(!n.online, "no relay connection is established");
2376 assert!(
2377 n.relays.is_empty() && n.home_relay.is_none(),
2378 "and none are known — which the renderer reads as LAN-BY-CONFIGURATION, not as an \
2379 outage; say 'nobody looked' with StatusResult.self_network: None instead"
2380 );
2381 assert_eq!(n.last_change_epoch, None, "no transition was observed");
2382
2383 let r = RelayInfo::default();
2384 assert!(
2385 !r.connected,
2386 "an unset relay must not claim a live connection"
2387 );
2388
2389 let st = StorageInfo::default();
2390 assert_eq!(
2391 (st.audit_bytes, st.redb_bytes, st.blobs_bytes),
2392 (0, 0, 0),
2393 "zeros read as MEASURED-and-empty; `StatusResult.storage: None` is 'unmeasured'"
2394 );
2395
2396 let ro = RosterStatus::default();
2397 assert!(
2398 ro.state.is_empty(),
2399 "not a valid state word, deliberately — `doctor` warns on an unknown state rather \
2400 than reporting a healthy roster"
2401 );
2402 assert_eq!(ro.serial, 0);
2403
2404 let pp = PresencePeer::default();
2405 assert!(
2406 !pp.online,
2407 "an unset presence row must not claim the device is up"
2408 );
2409 assert!(pp.role.is_empty() && pp.user_id.is_empty());
2410
2411 let rp = RecentPairing::default();
2412 assert_eq!(rp.paired_at_epoch, 0);
2413 assert!(rp.sas_code.is_empty(), "no ceremony produced a code");
2414 }
2415
2416 /// #150 gate: "an unrecognized value reads as `unknown`" must hold for any VALUE, not just an
2417 /// unrecognized string.
2418 ///
2419 /// `#[serde(default)]` covers an absent key and nothing else, so `"source": null` — what a
2420 /// proxy or non-Rust daemon that normalizes optional fields produces — went through the
2421 /// deserializer and failed the WHOLE frame, silently dropping a liveness transition while the
2422 /// protocol doc promised the field could not break a parse. The container shapes matter
2423 /// separately: a visitor that answers without draining a map/seq desynchronizes the parser and
2424 /// fails the frame anyway, which looks identical from outside.
2425 #[test]
2426 fn a_malformed_source_degrades_instead_of_failing_the_frame() {
2427 let peer = serde_json::json!({"name": "bob", "reachable": true});
2428 for bad in [
2429 serde_json::Value::Null,
2430 serde_json::json!(7),
2431 serde_json::json!(-1),
2432 serde_json::json!(1.5),
2433 serde_json::json!(true),
2434 serde_json::json!({"kind": "probe", "nested": {"deep": [1, 2]}}),
2435 serde_json::json!(["probe", "session"]),
2436 ] {
2437 let frame: StreamFrame = serde_json::from_value(
2438 serde_json::json!({"type": "reachability", "peer": peer, "source": bad}),
2439 )
2440 .unwrap_or_else(|e| panic!("`source: {bad}` must not fail the whole frame: {e}"));
2441 let StreamFrame::Reachability { source, peer } = frame else {
2442 panic!("expected a reachability frame");
2443 };
2444 assert_eq!(source, ReachabilitySource::Unknown, "for source: {bad}");
2445 assert!(peer.reachable, "the rest of the frame survives: {bad}");
2446 }
2447 }
2448
2449 /// #90: the self-network frame tags as `{"type":"self_network","self_network":{…}}` — the
2450 /// SAME block `status` and the snapshot carry. Pinned explicitly (like the reachability
2451 /// tag) so a variant rename cannot slip past a suite whose two ends share the type while
2452 /// breaking every doc-following third-party client.
2453 #[test]
2454 fn self_network_frame_tags_and_round_trips() {
2455 let frame = StreamFrame::SelfNetwork {
2456 self_network: SelfNetwork {
2457 online: true,
2458 home_relay: Some("https://relay.example:443".into()),
2459 relays: vec![RelayInfo {
2460 url: "https://relay.example:443".into(),
2461 connected: true,
2462 }],
2463 direct_addrs: vec!["192.168.1.2:4444".into()],
2464 last_change_epoch: Some(1_753_842_000),
2465 identity_conflict_epoch: None,
2466 // #89: seeded NON-default so the round-trip actually carries it — an empty value
2467 // here would round-trip through a `skip_serializing_if` and prove nothing.
2468 presence_mode: Some("granted".into()),
2469 },
2470 };
2471 let v = serde_json::to_value(&frame).unwrap();
2472 assert_eq!(v["type"], "self_network");
2473 assert_eq!(v["self_network"]["online"], true);
2474 assert_eq!(v["self_network"]["home_relay"], "https://relay.example:443");
2475 assert_eq!(v["self_network"]["relays"][0]["connected"], true);
2476 assert_eq!(
2477 v["self_network"]["presence_mode"], "granted",
2478 "#89: the live presence mode must reach the wire — it is the only way an operator can \
2479 confirm the knob took effect, and a product's privacy switch has nothing to render \
2480 without it"
2481 );
2482 let back: StreamFrame = serde_json::from_value(v).unwrap();
2483 assert_eq!(back, frame);
2484 }
2485
2486 #[test]
2487 fn peer_reachability_serde_is_additive() {
2488 let r = PeerReachability {
2489 name: "bob".into(),
2490 reachable: true,
2491 rtt_ms: Some(42),
2492 age_secs: Some(3),
2493 meta: String::new(),
2494 principal: None,
2495 path: Default::default(),
2496 };
2497 let v = serde_json::to_value(&r).unwrap();
2498 assert_eq!(v["name"], "bob");
2499 assert_eq!(v["reachable"], true);
2500 assert_eq!(v["rtt_ms"], 42);
2501 assert_eq!(v["age_secs"], 3);
2502 // Never-probed peer: optionals elided, not null.
2503 let unknown = PeerReachability {
2504 name: "carol".into(),
2505 reachable: false,
2506 rtt_ms: None,
2507 age_secs: None,
2508 meta: String::new(),
2509 principal: None,
2510 path: Default::default(),
2511 };
2512 let uv = serde_json::to_value(&unknown).unwrap();
2513 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
2514 // An older StatusResult (no reachability field) still deserializes.
2515 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
2516 let s: StatusResult = serde_json::from_value(old).unwrap();
2517 assert!(s.reachability.is_empty());
2518 }
2519
2520 #[test]
2521 fn subscribe_method_tag_resolves() {
2522 let req = serde_json::to_value(Request::Subscribe).unwrap();
2523 assert_eq!(method_of(&req), Some("subscribe"));
2524 }
2525
2526 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
2527
2528 #[test]
2529 fn invite_params_reject_singular_service_typo() {
2530 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
2531 // `InviteParams { services: [] }` and mint a grants-nothing invite that looked
2532 // successful. With deny_unknown_fields the typo is a loud parse error instead.
2533 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
2534 assert!(
2535 err.is_err(),
2536 "an unknown `service` key must be rejected, not silently ignored"
2537 );
2538 // The correct plural shape still parses.
2539 let ok: InviteParams =
2540 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
2541 assert_eq!(ok.services, vec!["kb".to_string()]);
2542 }
2543
2544 #[test]
2545 fn open_session_params_reject_unknown_field() {
2546 let err = serde_json::from_value::<OpenSessionParams>(
2547 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
2548 );
2549 assert!(err.is_err(), "unknown params keys must be rejected");
2550 }
2551
2552 #[test]
2553 fn set_app_metadata_request_carries_the_method_tag() {
2554 let r = Request::SetAppMetadata(SetAppMetadataParams {
2555 metadata: "v=1.2.3".into(),
2556 });
2557 let v = serde_json::to_value(&r).unwrap();
2558 assert_eq!(v["method"], "set_app_metadata");
2559 assert_eq!(v["params"]["metadata"], "v=1.2.3");
2560 assert_eq!(method_of(&v), Some("set_app_metadata"));
2561 }
2562
2563 #[test]
2564 fn set_app_metadata_params_reject_unknown_field() {
2565 let err = serde_json::from_value::<SetAppMetadataParams>(
2566 serde_json::json!({"metadata": "x", "nonsense": 1}),
2567 );
2568 assert!(err.is_err(), "unknown params keys must be rejected");
2569 }
2570
2571 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
2572 /// empty meta does not serialize.
2573 #[test]
2574 fn peer_info_principal_is_additive() {
2575 // An older payload (no principal) still deserializes; empty does not serialize.
2576 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
2577 let p: PeerInfo = serde_json::from_value(old).unwrap();
2578 assert_eq!(p.principal, None);
2579 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
2580 // A bound peer carries BOTH the person user_id AND the device principal (#41).
2581 let full = PeerInfo {
2582 name: "bob".into(),
2583 services: vec!["notes".into()],
2584 user_id: Some("b64u:BOB".into()),
2585 principal: Some("eid:0707".into()),
2586 };
2587 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
2588 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
2589 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
2590 }
2591
2592 #[test]
2593 fn active_session_principal_is_additive() {
2594 // An OLD payload (no `principal`) must still deserialize — #73 is additive.
2595 let old: ActiveSession =
2596 serde_json::from_str(r#"{"peer":"bob","service":"notes","opened_at":7}"#).unwrap();
2597 assert_eq!(old.principal, None, "serde(default) supplies it");
2598
2599 // And a `None` must not serialize, so an old client sees the shape it expects.
2600 let json = serde_json::to_string(&old).unwrap();
2601 assert!(
2602 !json.contains("principal"),
2603 "skip_serializing_if must omit it: {json}"
2604 );
2605
2606 // A real row round-trips the principal.
2607 let new = ActiveSession {
2608 peer: "bob".into(),
2609 service: "notes".into(),
2610 opened_at: 7,
2611 principal: Some("eid:1f0a".into()),
2612 };
2613 let back: ActiveSession =
2614 serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
2615 assert_eq!(back.principal.as_deref(), Some("eid:1f0a"));
2616 }
2617
2618 #[test]
2619 fn peer_reachability_principal_is_additive() {
2620 // Older payload (no principal) still deserializes; empty does not serialize; a set
2621 // value round-trips alongside the #40 meta so an embedder joins on the principal.
2622 let old = serde_json::json!({"name": "bob", "reachable": true});
2623 let r: PeerReachability = serde_json::from_value(old).unwrap();
2624 assert_eq!(r.principal, None);
2625 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
2626 let full = PeerReachability {
2627 name: "bob".into(),
2628 reachable: true,
2629 rtt_ms: Some(12),
2630 age_secs: Some(3),
2631 meta: "v=1.2.3".into(),
2632 principal: Some("eid:0707".into()),
2633 path: Default::default(),
2634 };
2635 let back: PeerReachability =
2636 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
2637 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
2638 assert_eq!(back.meta, "v=1.2.3");
2639 }
2640
2641 #[test]
2642 fn peer_reachability_meta_is_additive() {
2643 // An older payload (no meta) still deserializes; an empty meta does not serialize.
2644 let old = serde_json::json!({"name": "bob", "reachable": true});
2645 let r: PeerReachability = serde_json::from_value(old).unwrap();
2646 assert_eq!(r.meta, "");
2647 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
2648 // A set value round-trips.
2649 let with = PeerReachability {
2650 name: "bob".into(),
2651 reachable: true,
2652 rtt_ms: Some(12),
2653 age_secs: Some(3),
2654 meta: "v=1.2.3".into(),
2655 principal: None,
2656 path: Default::default(),
2657 };
2658 let back: PeerReachability =
2659 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
2660 assert_eq!(back.meta, "v=1.2.3");
2661 }
2662
2663 #[test]
2664 fn presence_peer_meta_is_additive() {
2665 let old = serde_json::json!({
2666 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
2667 });
2668 let p: PresencePeer = serde_json::from_value(old).unwrap();
2669 assert_eq!(p.meta, "");
2670 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
2671 }
2672
2673 #[test]
2674 fn set_nickname_request_carries_the_method_tag() {
2675 let r = Request::SetNickname(SetNicknameParams {
2676 nickname: "workbench".into(),
2677 });
2678 let v = serde_json::to_value(&r).unwrap();
2679 assert_eq!(v["method"], "set_nickname");
2680 assert_eq!(v["params"]["nickname"], "workbench");
2681 assert_eq!(method_of(&v), Some("set_nickname"));
2682 }
2683
2684 #[test]
2685 fn set_nickname_params_reject_unknown_field() {
2686 let err = serde_json::from_value::<SetNicknameParams>(
2687 serde_json::json!({"nickname": "x", "nonsense": 1}),
2688 );
2689 assert!(err.is_err(), "unknown params keys must be rejected");
2690 }
2691
2692 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
2693 /// the additive-only contract — and an empty name must not serialize at all.
2694 #[test]
2695 fn status_self_nickname_is_additive() {
2696 let old = serde_json::json!({
2697 "stack_version": "0.7.0", "services": [], "peers": []
2698 });
2699 let s: StatusResult = serde_json::from_value(old).unwrap();
2700 assert_eq!(s.self_nickname, "");
2701 let v = serde_json::to_value(&s).unwrap();
2702 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
2703 }
2704
2705 #[test]
2706 fn api_minor_is_present_and_monotonic_from_hello() {
2707 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
2708 // crate/stack version, additive on the Hello frame.
2709 let h = Hello {
2710 api: API_NAME.into(),
2711 api_version: API_VERSION.into(),
2712 api_minor: API_MINOR,
2713 stack_version: "9.9.9".into(),
2714 };
2715 let v = serde_json::to_value(&h).unwrap();
2716 assert_eq!(v["api_minor"], API_MINOR);
2717 // An OLD Hello without api_minor still deserializes (additive contract).
2718 let old = serde_json::json!({
2719 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
2720 });
2721 let back: Hello = serde_json::from_value(old).unwrap();
2722 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
2723 }
2724
2725 #[test]
2726 fn hello_result_roundtrips() {
2727 let h = Hello {
2728 api: "mcpmesh-local/1".into(),
2729 api_version: "1.0".into(),
2730 api_minor: 0,
2731 stack_version: "0.1.0".into(),
2732 };
2733 let v = serde_json::to_value(&h).unwrap();
2734 assert_eq!(v["api"], "mcpmesh-local/1");
2735 let back: Hello = serde_json::from_value(v).unwrap();
2736 assert_eq!(back, h);
2737 }
2738
2739 #[test]
2740 fn request_tagged_by_method() {
2741 let r = Request::Status;
2742 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
2743 let r = Request::OpenSession(OpenSessionParams {
2744 peer: "alice".into(),
2745 service: "notes".into(),
2746 });
2747 let v = serde_json::to_value(&r).unwrap();
2748 assert_eq!(v["method"], "open_session");
2749 assert_eq!(v["params"]["peer"], "alice");
2750 }
2751
2752 #[test]
2753 fn parameterless_method_tolerates_params_forms() {
2754 // Omitted and null params deserialize straight into the unit variant.
2755 let omitted: Request =
2756 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
2757 assert_eq!(omitted, Request::Status);
2758 let null: Request =
2759 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
2760 .unwrap();
2761 assert_eq!(null, Request::Status);
2762
2763 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
2764 // the server MUST dispatch on the method string rather than deserialize the whole
2765 // message into `Request`. This is the pattern the daemon's dispatcher uses.
2766 let empty = serde_json::json!({"method": "status", "params": {}});
2767 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
2768 match method_of(&empty) {
2769 Some("status") => {} // dispatcher resolves Status via the method string
2770 other => panic!("method_of failed to resolve status: {other:?}"),
2771 }
2772 }
2773
2774 #[test]
2775 fn backend_spec_roundtrips() {
2776 let run = BackendSpec::Run {
2777 cmd: vec!["notes-mcp".into(), "--stdio".into()],
2778 env: Default::default(),
2779 cwd: None,
2780 };
2781 let v = serde_json::to_value(&run).unwrap();
2782 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
2783 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
2784
2785 let sock = BackendSpec::Socket {
2786 path: "/run/notes.sock".into(),
2787 };
2788 let v = serde_json::to_value(&sock).unwrap();
2789 assert_eq!(v["socket"]["path"], "/run/notes.sock");
2790 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
2791 }
2792
2793 #[test]
2794 fn register_service_wire_shape() {
2795 let r = Request::RegisterService(RegisterServiceParams {
2796 name: "notes".into(),
2797 backend: BackendSpec::Run {
2798 cmd: vec!["notes-mcp".into()],
2799 env: Default::default(),
2800 cwd: None,
2801 },
2802 allow: vec!["alice".into()],
2803 ephemeral: false,
2804 rate_limit_per_min: None,
2805 });
2806 let v = serde_json::to_value(&r).unwrap();
2807 assert_eq!(
2808 v,
2809 serde_json::json!({
2810 "method": "register_service",
2811 "params": {
2812 "name": "notes",
2813 "backend": {"run": {"cmd": ["notes-mcp"]}},
2814 "allow": ["alice"],
2815 }
2816 })
2817 );
2818 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2819 }
2820
2821 #[test]
2822 fn invite_request_and_result_roundtrip() {
2823 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
2824 let r = Request::Invite(InviteParams {
2825 services: vec!["notes".into(), "kb".into()],
2826 app_label: None,
2827 max_uses: None,
2828 // #87: seeded NON-None so the round-trip actually carries it — `None` rides
2829 // `skip_serializing_if` straight past the assertion and proves nothing.
2830 peer_nickname: Some("laptop-of-alice".into()),
2831 as_self: false,
2832 });
2833 let v = serde_json::to_value(&r).unwrap();
2834 assert_eq!(v["method"], "invite");
2835 assert_eq!(
2836 v["params"]["peer_nickname"], "laptop-of-alice",
2837 "#87: the inviter's local alias for the redeemer must reach the wire"
2838 );
2839 assert_eq!(v["params"]["services"][0], "notes");
2840 assert_eq!(v["params"]["services"][1], "kb");
2841 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2842 // method_of resolves the tag generically (no per-variant arm).
2843 assert_eq!(
2844 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
2845 Some("invite")
2846 );
2847
2848 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
2849 let res = InviteResult {
2850 invite_line: "mcpmesh-invite:ABCDEF".into(),
2851 expires_at_epoch: 1_800_000_000,
2852 uses_remaining: 1,
2853 };
2854 let v = serde_json::to_value(&res).unwrap();
2855 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
2856 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
2857 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
2858 }
2859
2860 #[test]
2861 fn pair_request_and_result_roundtrip() {
2862 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
2863 let r = Request::Pair(PairParams {
2864 invite_line: "mcpmesh-invite:ABCDEF".into(),
2865 as_nickname: Some("alice-mbp".into()),
2866 allow_self_enroll: true,
2867 });
2868 let v = serde_json::to_value(&r).unwrap();
2869 assert_eq!(v["method"], "pair");
2870 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
2871 assert_eq!(
2872 v["params"]["as_nickname"], "alice-mbp",
2873 "#87: the redeemer's local alias for the inviter must reach the wire"
2874 );
2875 assert_eq!(
2876 v["params"]["allow_self_enroll"], true,
2877 "#178: the caller's consent to a self-enrollment must reach the wire — the daemon \
2878 refuses the ceremony without it"
2879 );
2880 // An OLD caller's payload — no alias — must still decode. The field is additive.
2881 let legacy: PairParams =
2882 serde_json::from_value(serde_json::json!({"invite_line": "x"})).unwrap();
2883 assert_eq!(legacy.as_nickname, None);
2884 // #178: and the consent defaults to REFUSING. A caller that predates the field, or one that
2885 // simply never set it, must not be read as having offered a device enrollment — that is the
2886 // whole guard, and a `#[serde(default)]` flipping to `true` would silently remove it.
2887 assert!(
2888 !legacy.allow_self_enroll,
2889 "an absent allow_self_enroll must default to false (refuse), never to true"
2890 );
2891 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2892 // method_of resolves the tag generically (no per-variant arm).
2893 assert_eq!(
2894 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
2895 Some("pair")
2896 );
2897
2898 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
2899 // the granted services (the porcelain renders each as `<peer>/<service>`).
2900 let res = PairResult {
2901 peer_nickname: "alice".into(),
2902 sas_code: "tango-fig-cabbage".into(),
2903 services: vec!["notes".into(), "kb".into()],
2904 app_label: None,
2905 peer_user_id: None,
2906 enrolled_as_self: false,
2907 };
2908 let v = serde_json::to_value(&res).unwrap();
2909 assert_eq!(v["peer_nickname"], "alice");
2910 assert_eq!(v["sas_code"], "tango-fig-cabbage");
2911 assert_eq!(v["services"][0], "notes");
2912 assert_eq!(v["services"][1], "kb");
2913 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
2914
2915 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
2916 // deserializes — the `#[serde(default)]` fills it with an empty list.
2917 let old_shape = serde_json::json!({
2918 "peer_nickname": "alice",
2919 "sas_code": "tango-fig-cabbage",
2920 });
2921 let back: PairResult = serde_json::from_value(old_shape).unwrap();
2922 assert_eq!(back.peer_nickname, "alice");
2923 assert!(back.services.is_empty());
2924 }
2925
2926 #[test]
2927 fn roster_install_request_and_result_roundtrip() {
2928 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
2929 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
2930 let r = Request::RosterInstall(RosterInstallParams {
2931 path: "/tmp/roster.json".into(),
2932 org_root_pk: Some("b64u:AAAA".into()),
2933 });
2934 let v = serde_json::to_value(&r).unwrap();
2935 assert_eq!(v["method"], "roster_install");
2936 assert_eq!(v["params"]["path"], "/tmp/roster.json");
2937 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
2938 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2939 // method_of resolves the tag generically (no per-variant arm).
2940 assert_eq!(
2941 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
2942 Some("roster_install")
2943 );
2944
2945 // When the pk is omitted (a subsequent install using the pinned value), it is
2946 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
2947 let omit = Request::RosterInstall(RosterInstallParams {
2948 path: "/tmp/roster.json".into(),
2949 org_root_pk: None,
2950 });
2951 let v = serde_json::to_value(&omit).unwrap();
2952 assert!(
2953 v["params"].get("org_root_pk").is_none(),
2954 "an omitted org_root_pk must not appear on the wire: {v}"
2955 );
2956 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
2957
2958 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
2959 let res = RosterInstallResult {
2960 org_id: "acme".into(),
2961 serial: 42,
2962 severed: 1,
2963 };
2964 let v = serde_json::to_value(&res).unwrap();
2965 assert_eq!(v["org_id"], "acme");
2966 assert_eq!(v["serial"], 42u64);
2967 assert_eq!(v["severed"], 1u32);
2968 assert_eq!(
2969 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
2970 res
2971 );
2972
2973 // Additive-only: a result minted by an older daemon (no `severed` key) still
2974 // deserializes — the `#[serde(default)]` fills it with 0.
2975 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
2976 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
2977 assert_eq!(back.serial, 7);
2978 assert_eq!(back.severed, 0);
2979 }
2980
2981 #[test]
2982 fn org_join_request_and_result_roundtrip() {
2983 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
2984 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
2985 let r = Request::OrgJoin(OrgJoinParams {
2986 org_id: "acme".into(),
2987 org_root_pk: "b64u:AAAA".into(),
2988 user_id: "alice".into(),
2989 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
2990 });
2991 let v = serde_json::to_value(&r).unwrap();
2992 assert_eq!(v["method"], "org_join");
2993 assert_eq!(v["params"]["org_id"], "acme");
2994 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
2995 assert_eq!(v["params"]["user_id"], "alice");
2996 assert_eq!(
2997 v["params"]["user_key"],
2998 "/home/alice/.config/mcpmesh/user.key"
2999 );
3000 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3001 // method_of resolves the tag generically (no per-variant arm).
3002 assert_eq!(
3003 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
3004 Some("org_join")
3005 );
3006
3007 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
3008 let res = OrgJoinResult {
3009 org_id: "acme".into(),
3010 };
3011 let v = serde_json::to_value(&res).unwrap();
3012 assert_eq!(v["org_id"], "acme");
3013 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
3014 }
3015
3016 #[test]
3017 fn set_roster_url_request_roundtrip() {
3018 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
3019 let r = Request::SetRosterUrl(SetRosterUrlParams {
3020 url: "https://intranet.acme.com/roster.json".into(),
3021 });
3022 let v = serde_json::to_value(&r).unwrap();
3023 assert_eq!(v["method"], "set_roster_url");
3024 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
3025 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3026 assert_eq!(
3027 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
3028 Some("set_roster_url")
3029 );
3030 }
3031
3032 #[test]
3033 fn peer_remove_request_roundtrip() {
3034 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
3035 let r = Request::PeerRemove(PeerRemoveParams {
3036 nickname: "bob".into(),
3037 });
3038 let v = serde_json::to_value(&r).unwrap();
3039 assert_eq!(v["method"], "peer_remove");
3040 assert_eq!(v["params"]["nickname"], "bob");
3041 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3042 // method_of resolves the tag generically (no per-variant arm).
3043 assert_eq!(
3044 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
3045 Some("peer_remove")
3046 );
3047 }
3048
3049 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
3050 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
3051 /// defaulting to empty when absent.
3052 /// #65: the wire tags for the introduction pair. The serde tag must equal the dispatch string
3053 /// the daemon matches on — nothing else checks that they agree.
3054 #[test]
3055 fn peer_introduce_and_endorse_roundtrip() {
3056 let r = Request::PeerIntroduce(PeerIntroduceParams {
3057 subject: "eid:aa".into(),
3058 endorsed_by: "b64u:carol".into(),
3059 evidence: "b64u:sig".into(),
3060 subject_user_id: Some("b64u:bob".into()),
3061 subject_binding: Some("b64u:bind".into()),
3062 nickname: "bob".into(),
3063 });
3064 let v = serde_json::to_value(&r).unwrap();
3065 assert_eq!(
3066 v["method"], "peer_introduce",
3067 "the tag must match the daemon's dispatch string exactly"
3068 );
3069 assert_eq!(v["params"]["subject"], "eid:aa");
3070 assert_eq!(v["params"]["subject_binding"], "b64u:bind");
3071 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3072
3073 // The two proof fields are OPTIONAL on the wire and omitted when absent.
3074 let minimal = Request::PeerIntroduce(PeerIntroduceParams {
3075 subject: "eid:aa".into(),
3076 endorsed_by: "b64u:carol".into(),
3077 evidence: "b64u:sig".into(),
3078 subject_user_id: None,
3079 subject_binding: None,
3080 nickname: "bob".into(),
3081 });
3082 let v = serde_json::to_value(&minimal).unwrap();
3083 assert!(v["params"].get("subject_user_id").is_none());
3084 assert!(v["params"].get("subject_binding").is_none());
3085 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), minimal);
3086
3087 let e = Request::PeerEndorse(PeerEndorseParams {
3088 subject: "eid:aa".into(),
3089 subject_user_id: None,
3090 });
3091 let v = serde_json::to_value(&e).unwrap();
3092 assert_eq!(v["method"], "peer_endorse");
3093 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), e);
3094
3095 let res = PeerEndorseResult {
3096 endorsed_by: "b64u:me".into(),
3097 evidence: "b64u:sig".into(),
3098 };
3099 let v = serde_json::to_value(&res).unwrap();
3100 assert_eq!(v["endorsed_by"], "b64u:me");
3101 assert_eq!(serde_json::from_value::<PeerEndorseResult>(v).unwrap(), res);
3102 }
3103
3104 #[test]
3105 fn peer_add_request_roundtrip() {
3106 let r = Request::PeerAdd(PeerAddParams {
3107 nickname: "bob".into(),
3108 endpoint_id: "96246d3f".into(),
3109 allow: vec!["notes".into()],
3110 });
3111 let v = serde_json::to_value(&r).unwrap();
3112 assert_eq!(v["method"], "peer_add");
3113 assert_eq!(v["params"]["nickname"], "bob");
3114 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
3115 assert_eq!(v["params"]["allow"][0], "notes");
3116 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3117 // An absent allow list deserializes to empty (the server-side tolerance).
3118 let p: PeerAddParams =
3119 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
3120 .unwrap();
3121 assert!(p.allow.is_empty());
3122 }
3123
3124 #[test]
3125 fn peer_rename_request_roundtrip() {
3126 // By user_id (renames all of a person's devices in one op).
3127 let r = Request::PeerRename(PeerRenameParams {
3128 user_id: Some("b64u:BOB".into()),
3129 nickname: None,
3130 to: "Bobby".into(),
3131 });
3132 let v = serde_json::to_value(&r).unwrap();
3133 assert_eq!(v["method"], "peer_rename");
3134 assert_eq!(v["params"]["user_id"], "b64u:BOB");
3135 assert_eq!(v["params"]["to"], "Bobby");
3136 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3137 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
3138 assert_eq!(
3139 method_of(
3140 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
3141 ),
3142 Some("peer_rename")
3143 );
3144 }
3145
3146 #[test]
3147 fn status_result_roundtrips() {
3148 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
3149 // older payload with no `roster` key still deserializes to None (serde default).
3150 let s = StatusResult {
3151 stack_version: "0.1.0".into(),
3152 services: vec![ServiceInfo {
3153 name: "notes".into(),
3154 allow: vec!["alice".into()],
3155 allow_display: vec![],
3156 backend: BackendKind::Run,
3157 ephemeral: false,
3158 }],
3159 peers: vec![PeerInfo {
3160 name: "alice".into(),
3161 services: vec!["notes".into()],
3162 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
3163 user_id: Some("b64u:alicepk".into()),
3164 principal: None,
3165 }],
3166 roster: None,
3167 presence: vec![],
3168 self_user_id: Some("b64u:selfpk".into()),
3169 recent_pairings: vec![],
3170 reachability: vec![],
3171 self_nickname: String::new(),
3172 storage: None,
3173 self_network: None,
3174 };
3175 let v = serde_json::to_value(&s).unwrap();
3176 assert_eq!(v["services"][0]["backend"], "run");
3177 // The additive identity fields ride the wire when present.
3178 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
3179 assert_eq!(v["self_user_id"], "b64u:selfpk");
3180 assert!(
3181 v.get("roster").is_none(),
3182 "an absent roster must not appear on the wire: {v}"
3183 );
3184 assert!(
3185 v.get("presence").is_none(),
3186 "an empty presence must not appear on the wire: {v}"
3187 );
3188 assert!(
3189 v.get("recent_pairings").is_none(),
3190 "an empty recent_pairings must not appear on the wire: {v}"
3191 );
3192 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3193
3194 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
3195 // deserializes — the identity fields default to None / a nickname-only peer.
3196 let old_shape = serde_json::json!({
3197 "stack_version": "0.1.0",
3198 "services": [],
3199 "peers": [{ "name": "bob", "services": [] }],
3200 });
3201 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
3202 assert!(back.roster.is_none());
3203 assert!(back.presence.is_empty());
3204 assert!(back.self_user_id.is_none());
3205 assert!(back.peers[0].user_id.is_none());
3206 assert!(back.recent_pairings.is_empty());
3207
3208 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
3209 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
3210 let s = StatusResult {
3211 stack_version: "0.1.0".into(),
3212 services: vec![],
3213 peers: vec![],
3214 roster: Some(RosterStatus {
3215 org_id: "acme".into(),
3216 serial: 42,
3217 state: "approved".into(),
3218 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
3219 }),
3220 presence: vec![
3221 PresencePeer {
3222 user_id: "alice".into(),
3223 device_label: "laptop".into(),
3224 role: "primary".into(),
3225 online: true,
3226 meta: String::new(),
3227 },
3228 PresencePeer {
3229 user_id: "alice".into(),
3230 device_label: "desktop".into(),
3231 role: "mirror".into(),
3232 online: false,
3233 meta: String::new(),
3234 },
3235 ],
3236 self_user_id: None,
3237 recent_pairings: vec![],
3238 reachability: vec![],
3239 self_nickname: String::new(),
3240 storage: None,
3241 self_network: None,
3242 };
3243 let v = serde_json::to_value(&s).unwrap();
3244 assert_eq!(v["roster"]["org_id"], "acme");
3245 assert_eq!(v["roster"]["serial"], 42u64);
3246 assert_eq!(v["roster"]["state"], "approved");
3247 assert_eq!(
3248 v["roster"]["org_root_fingerprint"],
3249 "tango-fig-cabbage-anchor"
3250 );
3251 assert_eq!(v["presence"][0]["user_id"], "alice");
3252 assert_eq!(v["presence"][0]["device_label"], "laptop");
3253 assert_eq!(v["presence"][0]["role"], "primary");
3254 assert_eq!(v["presence"][0]["online"], true);
3255 assert_eq!(v["presence"][1]["online"], false);
3256 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3257 }
3258
3259 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
3260 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
3261 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
3262 /// older daemon (no key at all) still deserializes to empty.
3263 #[test]
3264 fn recent_pairings_are_additive_on_status() {
3265 let s = StatusResult {
3266 stack_version: "0.1.0".into(),
3267 services: vec![],
3268 peers: vec![],
3269 roster: None,
3270 presence: vec![],
3271 self_user_id: None,
3272 recent_pairings: vec![RecentPairing {
3273 peer_nickname: "bob".into(),
3274 sas_code: "tango-fig-cabbage".into(),
3275 paired_at_epoch: 1_800_000_000,
3276 }],
3277 reachability: vec![],
3278 self_nickname: String::new(),
3279 storage: None,
3280 self_network: None,
3281 };
3282 let v = serde_json::to_value(&s).unwrap();
3283 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
3284 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
3285 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
3286 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3287
3288 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
3289 // the `#[serde(default)]` fills it with an empty list.
3290 let old_shape = serde_json::json!({
3291 "stack_version": "0.1.0",
3292 "services": [],
3293 "peers": [],
3294 });
3295 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
3296 assert!(back.recent_pairings.is_empty());
3297 }
3298
3299 #[test]
3300 fn blob_requests_and_results_roundtrip() {
3301 // BlobPublish → { method, params: { scope, path } }.
3302 let r = Request::BlobPublish(BlobPublishParams {
3303 scope: "docs".into(),
3304 path: "/tmp/a.bin".into(),
3305 });
3306 let v = serde_json::to_value(&r).unwrap();
3307 assert_eq!(v["method"], "blob_publish");
3308 assert_eq!(v["params"]["scope"], "docs");
3309 assert_eq!(v["params"]["path"], "/tmp/a.bin");
3310 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3311
3312 // BlobGrant → { method, params: { scope, principal } }.
3313 // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
3314 // would otherwise ship undetected — the e2e test calls the provider directly and never
3315 // crosses JSON-RPC.
3316 let rev = Request::BlobRevoke(BlobRevokeParams {
3317 scope: "photos".into(),
3318 principals: vec!["alice".into()],
3319 });
3320 let v = serde_json::to_value(&rev).unwrap();
3321 assert_eq!(v["method"], "blob_revoke");
3322 assert_eq!(v["params"]["principals"][0], "alice");
3323 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
3324
3325 let unp = Request::BlobUnpublish(BlobUnpublishParams {
3326 scope: "photos".into(),
3327 hash: "abc123".into(),
3328 });
3329 let v = serde_json::to_value(&unp).unwrap();
3330 assert_eq!(v["method"], "blob_unpublish");
3331 assert_eq!(v["params"]["hash"], "abc123");
3332 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
3333
3334 let r = Request::BlobGrant(BlobGrantParams {
3335 scope: "docs".into(),
3336 principal: "alice".into(),
3337 });
3338 let v = serde_json::to_value(&r).unwrap();
3339 assert_eq!(v["method"], "blob_grant");
3340 assert_eq!(v["params"]["principal"], "alice");
3341 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3342
3343 // BlobList is parameterless (method_of resolves it).
3344 assert_eq!(
3345 method_of(&serde_json::json!({"method": "blob_list"})),
3346 Some("blob_list")
3347 );
3348
3349 // BlobFetch → { method, params: { ticket, dest_path } }.
3350 let r = Request::BlobFetch(BlobFetchParams {
3351 ticket: "blobAAA".into(),
3352 dest_path: "/tmp/out.bin".into(),
3353 });
3354 let v = serde_json::to_value(&r).unwrap();
3355 assert_eq!(v["method"], "blob_fetch");
3356 assert_eq!(v["params"]["ticket"], "blobAAA");
3357 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
3358 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3359
3360 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
3361 let res = BlobPublishResult {
3362 ticket: "blobAAA".into(),
3363 hash: "ab".repeat(32),
3364 };
3365 let v = serde_json::to_value(&res).unwrap();
3366 assert_eq!(v["ticket"], "blobAAA");
3367 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
3368
3369 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
3370 let res = BlobScopeList {
3371 scopes: vec![ScopeInfo {
3372 name: "docs".into(),
3373 hashes: vec!["ab".repeat(32)],
3374 grants: vec!["alice".into()],
3375 withdrawn: vec![],
3376 hash_count: 1,
3377 grant_count: 1,
3378 withdrawn_count: 0,
3379 }],
3380 total: 1,
3381 truncated: false,
3382 };
3383 let v = serde_json::to_value(&res).unwrap();
3384 assert_eq!(v["scopes"][0]["name"], "docs");
3385 assert_eq!(v["scopes"][0]["grants"][0], "alice");
3386 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
3387
3388 // BlobFetchResult carries the verified hash + byte length.
3389 let res = BlobFetchResult {
3390 hash: "ab".repeat(32),
3391 bytes_len: 4194304,
3392 };
3393 let v = serde_json::to_value(&res).unwrap();
3394 assert_eq!(v["bytes_len"], 4194304u64);
3395 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
3396 }
3397
3398 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
3399 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
3400 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
3401 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
3402 #[test]
3403 fn stream_frames_roundtrip_with_the_documented_tags() {
3404 let snap = StreamFrame::Snapshot {
3405 self_network: None,
3406 active_sessions: vec![ActiveSession {
3407 peer: "bob".into(),
3408 service: "notes".into(),
3409 opened_at: 1_751_760_000,
3410 principal: None,
3411 }],
3412 reachability: vec![PeerReachability {
3413 name: "bob".into(),
3414 reachable: true,
3415 rtt_ms: Some(42),
3416 age_secs: Some(3),
3417 meta: String::new(),
3418 principal: None,
3419 path: Default::default(),
3420 }],
3421 };
3422 let v = serde_json::to_value(&snap).unwrap();
3423 assert_eq!(v["type"], "snapshot");
3424 assert_eq!(v["active_sessions"][0]["peer"], "bob");
3425 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
3426 assert_eq!(v["reachability"][0]["name"], "bob");
3427 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
3428
3429 let event = StreamFrame::Event {
3430 record: Box::new(AuditRecord::session_open(
3431 "2026-07-03T14:02:11.480Z".into(),
3432 Some("bob".into()),
3433 "notes".into(),
3434 None,
3435 )),
3436 };
3437 let v = serde_json::to_value(&event).unwrap();
3438 assert_eq!(v["type"], "event");
3439 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
3440 assert_eq!(v["record"]["kind"], "session_open");
3441 assert_eq!(v["record"]["peer"], "bob");
3442 assert_eq!(v["record"]["service"], "notes");
3443 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
3444
3445 let lagged = StreamFrame::Lagged { dropped: 12 };
3446 let v = serde_json::to_value(&lagged).unwrap();
3447 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
3448 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
3449 }
3450
3451 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
3452 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
3453 /// raw `Value` stream instead (`ControlClient::open_stream`).
3454 #[test]
3455 fn unknown_stream_frame_type_is_rejected() {
3456 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
3457 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
3458 }
3459
3460 #[test]
3461 fn audit_summary_request_and_result_roundtrip() {
3462 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
3463 // tolerates omitted/null params; the server dispatches on the method string (method_of).
3464 let r = Request::AuditSummary;
3465 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
3466 assert_eq!(
3467 method_of(&serde_json::json!({"method": "audit_summary"})),
3468 Some("audit_summary")
3469 );
3470
3471 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
3472 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
3473 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
3474 let res = AuditSummaryResult {
3475 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
3476 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
3477 total_sessions: 4,
3478 };
3479 let v = serde_json::to_value(&res).unwrap();
3480 assert_eq!(v["per_peer"][1][0], "bob");
3481 assert_eq!(v["per_peer"][1][1], 2u64);
3482 assert_eq!(v["per_service"][1][0], "notes");
3483 assert_eq!(v["total_sessions"], 4u64);
3484 assert_eq!(
3485 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
3486 res
3487 );
3488
3489 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
3490 // deserializes — the `#[serde(default)]` fills it with 0.
3491 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
3492 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
3493 assert_eq!(back.total_sessions, 0);
3494 assert!(back.per_peer.is_empty());
3495 }
3496}