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 /// The org's DECLARED group namespace, in roster document order (#93). `api_minor >= 46`.
299 ///
300 /// The set an `allow` entry may name — a roster is refused if any user carries a group outside
301 /// it — so this is what a UI offers when assigning membership. Without it an embedder in roster
302 /// mode had managed group membership it could not enumerate, and the only way to learn the
303 /// groups was to hand-parse the daemon-owned `roster.json`.
304 ///
305 /// Display/authoring input, never an authorization answer: naming a group grants nothing.
306 /// Additive — a payload from an older daemon reads as an empty list.
307 #[serde(default, skip_serializing_if = "Vec::is_empty")]
308 pub groups: Vec<String>,
309}
310
311/// One reachable roster peer device as reported by `status` (the advisory presence read).
312/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
313/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
314/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
315#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
316pub struct PresencePeer {
317 pub user_id: String,
318 /// The person's human display name from the roster (#93). `api_minor >= 46`.
319 ///
320 /// `user_id` is an authorization handle; this is what a UI puts next to a face. The roster
321 /// carried it all along and the control seam dropped it, so an embedder had a presence list it
322 /// could only label with an opaque id. Display-only — never an authz input.
323 ///
324 /// Additive: absent from an older daemon's payload, and empty when the roster's own field is.
325 #[serde(default, skip_serializing_if = "String::is_empty")]
326 pub display_name: String,
327 /// The groups this person belongs to (#93). `api_minor >= 46`.
328 ///
329 /// The same strings an `allow` entry names, so a UI can show why someone is admitted without
330 /// re-deriving it. Advisory display data: the gate reads the roster, never this. Additive.
331 #[serde(default, skip_serializing_if = "Vec::is_empty")]
332 pub groups: Vec<String>,
333 pub device_label: String,
334 pub role: String, // "primary" | "mirror" (roster vocabulary)
335 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
336 pub online: bool,
337 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
338 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
339 /// data; never an authz input. Additive: default + skip-if-empty.
340 #[serde(default, skip_serializing_if = "String::is_empty")]
341 pub meta: String,
342}
343
344/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
345/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
346/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
347/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
348/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
349/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
350/// an epoch — never an EndpointId.
351#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
352pub struct RecentPairing {
353 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
354 pub peer_nickname: String,
355 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
356 /// `PairResult.sas_code` carried. Never checked programmatically.
357 pub sas_code: String,
358 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
359 pub paired_at_epoch: u64,
360 /// `true` when the ceremony was a SELF-ENROLLMENT (`invite { as_self: true }`, #86): the
361 /// redeemer became another device of THIS person rather than a peer, so there is no peer row
362 /// behind `peer_nickname` and a SAS mismatch means an impostor now presents your identity —
363 /// the remedy is `device_revoke` of that endpoint, not `peer_remove` (#214). The endpoint is
364 /// on the `self_enroll` audit event, not here — this row stays surface-clean. Set structurally
365 /// by the ceremony that ran, never inferred from the nickname text. Additive
366 /// (`api_minor >= 62`): `#[serde(default, skip_serializing_if = ...)]`, absent = an ordinary
367 /// pairing.
368 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
369 pub self_enroll: bool,
370}
371
372#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
373pub struct StatusResult {
374 pub stack_version: String,
375 pub services: Vec<ServiceInfo>,
376 pub peers: Vec<PeerInfo>,
377 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
378 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
379 #[serde(default, skip_serializing_if = "Option::is_none")]
380 pub roster: Option<RosterStatus>,
381 /// The reachable roster peer devices (the advisory presence read), each with an `online`
382 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
383 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
384 #[serde(default, skip_serializing_if = "Vec::is_empty")]
385 pub presence: Vec<PresencePeer>,
386 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
387 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
388 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
389 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
390 #[serde(default, skip_serializing_if = "Option::is_none")]
391 pub self_user_id: Option<String>,
392 /// `true` when THIS device holds the private user key behind `self_user_id` (#214,
393 /// `api_minor >= 62`). `false` when it presents that identity on the strength of an ADOPTED
394 /// enrollment binding (#86) — the key lives on the device that enrolled it — and when it has
395 /// no user key at all (`self_user_id` absent). An enrolled device and a key-holding one
396 /// otherwise report the same `self_user_id`, and three refusals hinge on the difference:
397 /// `peer_endorse`, `device_revoke` and `invite { as_self }` all refuse on an enrolled device,
398 /// and [`Request::SelfEnrollDetach`] applies only there. ADVISORY display data for placing
399 /// those affordances — never an authorization input; the daemon re-checks on every call.
400 /// Additive: `#[serde(default, skip_serializing_if = ...)]`, so it reads `false` from a daemon
401 /// below 62 — guard on `api_minor` before treating that as "enrolled".
402 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
403 pub self_user_key_held: bool,
404 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
405 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
406 /// that has accepted no pairing since it started. Additive:
407 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
408 #[serde(default, skip_serializing_if = "Vec::is_empty")]
409 pub recent_pairings: Vec<RecentPairing>,
410 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
411 /// first probe completes. Additive: default + skip-if-empty.
412 #[serde(default, skip_serializing_if = "Vec::is_empty")]
413 pub reachability: Vec<PeerReachability>,
414 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
415 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
416 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
417 /// skip-if-empty so an older payload round-trips.
418 #[serde(default, skip_serializing_if = "String::is_empty")]
419 pub self_nickname: String,
420 /// On-disk footprint of this node's own state (#88), so an embedder can warn a user before
421 /// ENOSPC rather than after — the audit log's write rate is driven by inbound peer traffic,
422 /// and it shares a filesystem with `state.redb` and the device key. A LIVE read (computed
423 /// per `status` call), not a boot-time snapshot. `None` only in mesh-less control-only mode.
424 /// Additive: default + skip-if-none so an older payload round-trips.
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 pub storage: Option<StorageInfo>,
427 /// Endpoints this node currently REFUSES (#85 ask 4, `api_minor >= 51`), local or signed.
428 ///
429 /// Present because a revocation is otherwise invisible: a peer that has been cut off simply
430 /// stops working, and neither side can tell that from a network fault. Empty on the
431 /// overwhelming majority of nodes, so it is elided rather than serialized as `[]`.
432 #[serde(default, skip_serializing_if = "Vec::is_empty")]
433 pub revoked: Vec<RevokedEndpoint>,
434 /// THIS node's own reachability posture (#90) — see [`SelfNetwork`]. Computed live per
435 /// call; `None` in mesh-less control-only mode. Additive: default + skip-if-none.
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub self_network: Option<SelfNetwork>,
438}
439
440/// The `status.self_network` block (#90): THIS node's own reachability posture — the first
441/// question in every "my message never arrived" investigation, previously unanswerable from
442/// either side of the API. Self-facing only: everything here is the node's own information
443/// (relay URLs come from its own config, sanitized; direct addresses already ride its invites).
444///
445/// `online` is iroh's own semantics — a home-relay connection is established. In
446/// `relay_mode = "disabled"` it is ALWAYS `false` with an empty `relays` list: that is a
447/// configuration, not an outage — render it as "LAN-only", never as a health warning.
448///
449/// Additive-only.
450///
451/// **`Default` is `{online: false, relays: []}` — which is exactly the shape above meaning
452/// "deliberately LAN-only" (#148).** The porcelain reads it that way and SUPPRESSES the "no relay
453/// connection" line for it. So a fixture built with `..Default::default()` claims a healthy
454/// LAN-only posture, not an unknown one. There is no third value for a `bool`; the honest way to
455/// say "nobody looked" is `StatusResult.self_network: None`, which is what a defaulted
456/// `StatusResult` gives you.
457#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
458pub struct SelfNetwork {
459 /// A home-relay connection is established (iroh's `online` definition). The signal #53's
460 /// `set_relays` never had: when this goes false on a relay-enabled node, the relay set is
461 /// the thing to look at.
462 pub online: bool,
463 /// The CONNECTED home relay's URL, sanitized to scheme + host + port (operator-supplied
464 /// relay URLs can carry userinfo tokens; `status` output gets screenshotted). `None` when
465 /// no relay is connected.
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub home_relay: Option<String>,
468 /// Every known home relay and its current connection state. Empty when no relays are
469 /// configured, or before the endpoint has selected any.
470 #[serde(default, skip_serializing_if = "Vec::is_empty")]
471 pub relays: Vec<RelayInfo>,
472 /// This endpoint's direct (non-relay) socket addresses — its own dialable coordinates.
473 #[serde(default, skip_serializing_if = "Vec::is_empty")]
474 pub direct_addrs: Vec<String>,
475 /// When the daemon's watcher last observed a TRANSITION (epoch seconds) — a change of
476 /// `online`, `home_relay`, or a relay's connection state; `direct_addrs` drift alone does
477 /// not stamp (nor emit a frame). OMITTED (not `null`) until the first observed transition
478 /// after boot, and from a point-in-time computation with no watcher running.
479 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub last_change_epoch: Option<i64>,
481 /// This node's `[network].presence_mode` (#89): `"paired"` | `"granted"` | `"off"` — who
482 /// currently gets an answer to the `mcpmesh/ping/1` reachability probe.
483 ///
484 /// Reported because the setting was otherwise **unobservable**: an operator who set it had no
485 /// way to confirm it took effect, and a product backing a privacy switch with it could not show
486 /// the user its real state. Always present from `api_minor >= 38`.
487 ///
488 /// **It is not "appear offline".** It withholds the pong payload and makes our own probe report
489 /// this node unreachable; it does not hide that the node is running (a QUIC application close
490 /// implies a completed handshake, and `mcpmesh/pair/1` answers any stranger by design). Do not
491 /// render it to users as invisibility.
492 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub presence_mode: Option<String>,
494 /// This node's `[network].local_discovery` (#68): `"off"` | `"on"` | `"resolve"` — whether it
495 /// finds peers on the local link with no internet, and whether it announces itself there.
496 ///
497 /// Reported for the same reason `presence_mode` is: the setting is otherwise unobservable, and
498 /// this one has two questions behind it. "Why can these two machines on one LAN not find each
499 /// other" is answered by `"off"`; and **`"on"` means this node is multicasting its endpoint id
500 /// and addresses to every device on the link**, which a product backing a privacy switch has to
501 /// be able to show the user. `"resolve"` never publishes this node's identity or addresses,
502 /// but still emits a service query roughly once a second — quieter than `"on"`, not silent.
503 ///
504 /// Always present from `api_minor >= 50`; absent below it, and absent without a mesh.
505 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub local_discovery: Option<String>,
507 /// When the relay last reported that ANOTHER endpoint is presenting this node's identity
508 /// (#134, epoch seconds), or absent if never — the overwhelmingly common case.
509 ///
510 /// Two nodes booted from COPIES of one mesh root share an endpoint id. The relay can serve only
511 /// one, so the displaced node's peers simply go unreachable with nothing saying why; diagnosing
512 /// that cost a downstream real time. This is that missing "why".
513 ///
514 /// **Sticky, and a timestamp rather than a flag.** The condition is announced once, as the
515 /// displaced connection is dropped — it is not a state the relay keeps reporting — so a
516 /// self-clearing flag would read false by the time anyone called `status`. Judge staleness from
517 /// the epoch, exactly as with `last_change_epoch`.
518 ///
519 /// **Absence is not proof of uniqueness.** Detection needs an
520 /// `IdentityConflictLayer` in the process's `tracing` subscriber: the standalone daemon
521 /// installs one at boot, but an EMBEDDED node cannot (a subscriber is global and the host owns
522 /// it) and reports `None` until the host installs it. Never render absence as "identity
523 /// verified unique".
524 ///
525 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`. `api_minor >= 32`.
526 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub identity_conflict_epoch: Option<i64>,
528}
529
530/// One home relay's connection state (#90). No latency — per-relay RTT needs iroh's
531/// `net_report`, which is unstable-feature-gated as of 1.0.3; `connected` is the stable truth.
532#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
533pub struct RelayInfo {
534 /// Sanitized (scheme + host + port), like `home_relay`.
535 pub url: String,
536 pub connected: bool,
537}
538
539/// One entry of `status.revoked` (#85 ask 4).
540#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
541pub struct RevokedEndpoint {
542 /// The `eid:` device principal that is refused.
543 pub principal: String,
544 /// When THIS node applied it, epoch seconds.
545 pub revoked_at_epoch: u64,
546 /// `"local"` — this operator's own decision about someone else's device — or `"signed"`, a
547 /// statement the device's OWNER issued about their own. Two different claims, and an operator
548 /// reading this list needs to tell them apart: only the second is evidence that the person
549 /// themselves declared the device dead.
550 pub source: String,
551 /// For `"signed"`: the verified `b64u:` that signed it.
552 #[serde(default, skip_serializing_if = "Option::is_none")]
553 pub signer_user_id: Option<String>,
554 /// Free-text operator note, never interpreted.
555 #[serde(default, skip_serializing_if = "Option::is_none")]
556 pub reason: Option<String>,
557 /// The local nickname this endpoint still has a pair row under, if any. Revocation does not
558 /// delete the row, so this is usually present — and it is what makes the list readable.
559 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub nickname: Option<String>,
561}
562
563/// The `status.storage` block (#88): bytes actually on disk, by subsystem. Counts, never
564/// content. Additive-only.
565///
566/// **`Default` is all zeros, which reads as "measured, and found empty" (#148).** It is here so a
567/// fixture can build one field and elide the rest; it is not a way to say "unmeasured". For that,
568/// leave `StatusResult.storage` as `None` — a defaulted `StatusResult` does exactly that.
569#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
570pub struct StorageInfo {
571 /// Summed sizes of the monthly audit files (`<state>/audit/*.jsonl`).
572 pub audit_bytes: u64,
573 /// Size of the peer/trust state store (`state.redb`).
574 pub redb_bytes: u64,
575 /// Total size under the app-blob store directory; 0 when no blob store exists.
576 pub blobs_bytes: u64,
577 /// Blob garbage collection (#80), or `None` when it is not configured — which is the default
578 /// and the behavior of every release up to 0.42.0.
579 ///
580 /// `None` means "not collecting", NOT "collecting and idle": a configured collector reports
581 /// `Some` with `runs: 0` until its first sweep.
582 #[serde(default, skip_serializing_if = "Option::is_none")]
583 pub blobs_gc: Option<BlobsGcInfo>,
584}
585
586/// The `status.storage.blobs_gc` block (#80): what the background app-blob collector has done.
587///
588/// **There is deliberately no `bytes_reclaimed`.** iroh-blobs calls back only BEFORE a sweep, never
589/// after, so any byte count here would be a guess. `blobs_bytes` is measured by walking the store
590/// directory; an operator reads reclaim off that, over time.
591#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
592pub struct BlobsGcInfo {
593 /// The interval the store is actually running on, in seconds.
594 pub interval_secs: u64,
595 /// Runs STARTED. iroh-blobs offers no completion callback, so this counts sweeps begun.
596 ///
597 /// **Watch this number.** Upstream's collector `break`s its loop on the first sweep error
598 /// rather than continuing, so one failure silently ends collection until the daemon restarts. A
599 /// `runs` that stops advancing across several intervals is the only signal that happened.
600 ///
601 /// Also: the collector SLEEPS before its first run, so a node with a 24h interval reports
602 /// `runs: 0` for its first 24 hours. That is not a fault.
603 pub runs: u64,
604 /// Unix seconds at the start of the most recent run; `None` before the first.
605 pub last_run_epoch: Option<i64>,
606 /// Hashes protected on the most recent run — the size of the liveness root the scope table
607 /// produced.
608 pub last_protected: u64,
609 /// Runs ABORTED because the liveness root could not be read. Each one swept nothing, which is
610 /// the intended fail-safe; a number that climbs means collection is not happening.
611 pub aborted: u64,
612}
613
614/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
615#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
616#[serde(deny_unknown_fields)]
617pub struct RegisterServiceParams {
618 pub name: String,
619 pub backend: BackendSpec,
620 pub allow: Vec<String>,
621 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
622 /// to the on-disk config, and automatically unregistered when the control connection that
623 /// registered it closes (and gone on daemon restart). For an embedder that serves a
624 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
625 /// socket path solely to keep a persisted registration valid, and the stale-registration
626 /// accumulation that comes with no unregister. Default false = the persistent behavior.
627 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
628 pub ephemeral: bool,
629 /// Per-service proxied-request rate (#63), falling back to `[limits].rate_limit_per_min`.
630 ///
631 /// **CLAMPED, never honoured upward.** `[limits].rate_limit_per_min` is a hard ceiling: a
632 /// larger value here is reduced to it, so a control call cannot uncap a service. Before #63
633 /// every service a peer could reach drew from one shared bucket, so a noisy service starved a
634 /// quiet one; buckets are now per `(service, endpoint)`.
635 ///
636 /// `0` is rejected rather than silently blocking every request. `api_minor >= 40`.
637 #[serde(default, skip_serializing_if = "Option::is_none")]
638 pub rate_limit_per_min: Option<u32>,
639}
640
641/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
642/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
643/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
644/// list (an invite that grants nothing is useless — #34).
645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646#[serde(deny_unknown_fields)]
647pub struct InviteParams {
648 #[serde(default)]
649 pub services: Vec<String>,
650 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
651 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
652 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub app_label: Option<String>,
655 /// How many times this invite may be redeemed (#87). Absent = **1**, the single-use behaviour
656 /// every existing caller already gets.
657 ///
658 /// Each redemption runs its OWN SAS ceremony and writes its own mutual peer rows — this is not
659 /// a shared or group identity, it is N independent pairings that happen to share one secret.
660 /// Onboarding a team stops being N mint-and-send rounds.
661 ///
662 /// Clamped to [`MAX_INVITE_USES`]; `0` is rejected rather than silently meaning "unusable". A
663 /// bearer credential's blast radius is `max_uses` × TTL, so it is opt-in and capped on purpose.
664 /// The value actually applied comes back in [`InviteResult::uses_remaining`] — read that rather
665 /// than assuming you got what you asked for.
666 ///
667 /// **`api_minor >= 35`, and sending it to an older daemon FAILS rather than degrading.**
668 /// `InviteParams` is `deny_unknown_fields`, so an `api_minor < 35` daemon answers `-32602
669 /// unknown field 'max_uses'` — it does not quietly mint a single-use invite. Loud is the right
670 /// behaviour; omit the field entirely when talking to one.
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub max_uses: Option<u32>,
673 /// YOUR local name for whoever redeems this invite (#87), overriding the nickname they claim
674 /// for themselves in the ceremony.
675 ///
676 /// The redeemer's self-claimed name is usually its hostname, so two same-model laptops collide
677 /// and the pairing is refused with [`ERR_NICKNAME_TAKEN`]. Before this field the only fixes
678 /// were to ask the other person to rename their machine, or to unpair whoever holds the name.
679 /// This lets you just call them something else.
680 ///
681 /// Local only: it is never sent to the peer and never affects what they call themselves or
682 /// you. It does **not** bypass the collision check — an alias that itself collides is refused
683 /// identically, because a duplicate display name makes your own `<peer>/<service>` routing
684 /// ambiguous whoever chose it.
685 ///
686 /// **Rejected with `max_uses > 1`:** one alias applied to every redeemer of a multi-use invite
687 /// would collide on the second redemption, so it is refused at MINT rather than producing an
688 /// invite that works exactly once. `api_minor >= 39`.
689 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub peer_nickname: Option<String>,
691 /// Mint a SELF-ENROLLMENT invite (#86): the redeemer becomes another device of **you**, not a
692 /// peer.
693 ///
694 /// The ceremony is the ordinary one — same secret, same SAS. What differs is the outcome:
695 /// neither side writes a peer row and nothing is granted, and the inviter signs a device→user
696 /// binding for the redeemer's authenticated endpoint. Both devices then present the same
697 /// `user_pk`, so every peer resolves them to ONE `user_id`.
698 ///
699 /// **The private key never moves.** The enrolling device signs a binding for the new device's
700 /// endpoint and hands over only that signature, so a second copy of the identity never exists.
701 /// The consequence: an enrolled device cannot enroll a third — enroll every device from the one
702 /// that holds the key.
703 ///
704 /// **The SAS matters more here than anywhere else.** The inviter signs a binding for whichever
705 /// endpoint redeems, so a redemption by an impostor mints *that impostor* a binding for your
706 /// identity. Requires `max_uses = 1` and an empty `services`, both refused otherwise.
707 /// `api_minor >= 43`.
708 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
709 pub as_self: bool,
710}
711
712/// The ceiling on [`InviteParams::max_uses`] (#87). Comfortably above "a team", far below "a
713/// fleet": one leaked invite line must not be able to enroll an unbounded number of devices for the
714/// whole 24h TTL.
715pub const MAX_INVITE_USES: u32 = 64;
716
717/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
718/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(deny_unknown_fields)]
721pub struct PairParams {
722 #[serde(default)]
723 pub invite_line: String,
724 /// YOUR local name for the inviter (#87), overriding the nickname their invite suggests.
725 ///
726 /// An invite carries the inviter's suggestion for what you should call them — usually their
727 /// hostname. If you already use that name for a different peer, the pairing is refused with
728 /// [`ERR_INVITE_NAME_CONFLICT`] and the message tells you to go ask them for a new invite.
729 /// This lets you resolve it yourself, without `set_nickname` (which rewrites your own GLOBAL
730 /// self-name — not what anyone wants in order to add one colleague).
731 ///
732 /// Local only: never sent to the inviter. It does **not** bypass the collision check — an alias
733 /// that itself collides is refused identically, because a duplicate display name makes your own
734 /// `<peer>/<service>` routing ambiguous whoever chose it. `api_minor >= 39`.
735 #[serde(default, skip_serializing_if = "Option::is_none")]
736 pub as_nickname: Option<String>,
737 /// Consent to complete a SELF-ENROLLMENT (#178): a `mcpmesh-enroll:` line is refused with
738 /// [`ERR_SELF_ENROLL_NOT_OFFERED`] unless this is set.
739 ///
740 /// Defaults to `false`, which is the whole point. #86 gave self-enrollment its own scheme so a
741 /// version-skewed redeemer refuses rather than pairing wrongly — but a CURRENT caller that only
742 /// ever meant to pair still ran the ceremony to completion, and learned which one it had run
743 /// from [`PairResult::enrolled_as_self`] only AFTER the device→user binding was written. That
744 /// binding admits this device to everyone who trusts the inviter's `user_id`, and it is
745 /// irrevocable short of rotating that user key — so "observe it afterwards" is not a place a
746 /// caller can refuse from.
747 ///
748 /// Set it when the ceremony is one your UI actually OFFERED ("add another of my devices"). Leave
749 /// it unset on an ordinary "join / add a contact" field: the refusal costs nothing, the invite is
750 /// untouched (nothing is dialled and nothing is burned), and the same line still works if the
751 /// person is then offered the real choice.
752 ///
753 /// To decide BEFORE calling — to show the right prompt rather than recover from a refusal — use
754 /// `mcpmesh_node::pairing::is_enrollment_line`. `api_minor >= 45`.
755 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
756 pub allow_self_enroll: bool,
757}
758
759/// Params of [`Request::AttestTo`] (#85 ask 3).
760#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
761#[serde(deny_unknown_fields)]
762pub struct AttestToParams {
763 /// A `mcpmesh-attest:` line from the peer that will admit this device.
764 pub offer: String,
765}
766
767/// Result of [`Request::AttestOffer`] (#85 ask 3).
768#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
769pub struct AttestOfferResult {
770 /// The `mcpmesh-attest:` line. Hand it to your other device.
771 pub offer: String,
772}
773
774/// Params of [`Request::PeerRevoke`] (#85 ask 4).
775#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
776#[serde(deny_unknown_fields)]
777pub struct PeerRevokeParams {
778 /// A nickname, an `eid:` device principal, or a `b64u:` user_id. A `b64u:` revokes EVERY
779 /// endpoint this node associates with that person.
780 pub peer: String,
781 /// Free-text operator note, stored and shown in `status`. Never interpreted.
782 #[serde(default, skip_serializing_if = "Option::is_none")]
783 pub reason: Option<String>,
784}
785
786/// Result of [`Request::PeerRevoke`].
787#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
788pub struct PeerRevokeResult {
789 /// The `eid:` principals now revoked. Empty means the name resolved to no endpoint — an ERROR
790 /// is returned instead in that case, so an empty list here never reads as success.
791 pub revoked: Vec<String>,
792 /// Live connections severed by this call. `0` is normal (the peer may be offline) and is NOT a
793 /// failure — but a non-zero count is the evidence that revocation was immediate rather than
794 /// deferred to the peer's next disconnect.
795 pub severed: usize,
796}
797
798/// Params of [`Request::PeerUnrevoke`] (#85 ask 4).
799///
800/// A nickname or `eid:` lifts that device's ENDPOINT revocation and reports it in `unrevoked` —
801/// but under a standing IDENTITY revocation (`peer_revoke b64u:`) on the `user_id` its row carries,
802/// that re-admits nothing (#218, `api_minor >= 61`): the gate still refuses the device on the
803/// identity. Unrevoke the `b64u:` to restore every device of the person.
804#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
805#[serde(deny_unknown_fields)]
806pub struct PeerUnrevokeParams {
807 /// Nickname, `eid:`, or `b64u:` — the same vocabulary as `peer_revoke`.
808 pub peer: String,
809}
810
811/// Result of [`Request::PeerUnrevoke`].
812#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
813pub struct PeerUnrevokeResult {
814 /// The `eid:` principals whose revocation was lifted. Empty = none were revoked (idempotent).
815 pub unrevoked: Vec<String>,
816}
817
818/// Params of [`Request::DeviceRevoke`] (#85 ask 4).
819#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
820#[serde(deny_unknown_fields)]
821pub struct DeviceRevokeParams {
822 /// The `eid:` principal of the device being revoked — one of THIS person's own.
823 ///
824 /// Explicit rather than "this node", because the device you are revoking is usually the one you
825 /// no longer have: you issue the token from your replacement machine, naming the lost one.
826 pub endpoint: String,
827 #[serde(default, skip_serializing_if = "Option::is_none")]
828 pub reason: Option<String>,
829}
830
831/// Result of [`Request::DeviceRevoke`]: the portable token, and what it says.
832#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
833pub struct DeviceRevokeResult {
834 /// The signed statement, `mcpmesh-revoke:<base64url>`. Hand this to your peers.
835 ///
836 /// Not a secret — it authorizes nothing and grants nothing; it only asks that an endpoint be
837 /// treated as dead, and only peers who already trust the signer will act on it.
838 pub token: String,
839 /// The `eid:` it revokes, echoed so a caller can confirm they named the device they meant.
840 pub endpoint: String,
841 /// The signing `b64u:` user_id — the identity your peers already pinned.
842 pub user_id: String,
843}
844
845/// Params of [`Request::DeviceRevocationImport`] (#85 ask 4).
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(deny_unknown_fields)]
848pub struct DeviceRevocationImportParams {
849 /// A `mcpmesh-revoke:` token from a peer.
850 pub token: String,
851}
852
853/// Result of [`Request::DeviceRevocationImport`].
854#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
855pub struct DeviceRevocationImportResult {
856 /// The `eid:` now revoked.
857 pub endpoint: String,
858 /// The `b64u:` that signed it — verified, not claimed.
859 pub user_id: String,
860 /// `false` when an equal-or-newer revocation for this endpoint was already held: the import is
861 /// idempotent, and a replayed OLDER token must not overwrite a newer one.
862 pub applied: bool,
863 /// Live connections severed. See `PeerRevokeResult::severed`.
864 pub severed: usize,
865}
866
867/// Params of [`Request::PeerRemove`]: the nickname to unpair.
868#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
869#[serde(deny_unknown_fields)]
870pub struct PeerRemoveParams {
871 pub nickname: String,
872}
873
874/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
875/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
876#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
877#[serde(deny_unknown_fields)]
878pub struct PeerRenameParams {
879 #[serde(default)]
880 pub user_id: Option<String>,
881 #[serde(default)]
882 pub nickname: Option<String>,
883 pub to: String,
884}
885
886/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
887/// (iroh base32) plus the nickname and service allow list to install it under.
888#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
889#[serde(deny_unknown_fields)]
890pub struct PeerAddParams {
891 pub nickname: String,
892 pub endpoint_id: String,
893 #[serde(default)]
894 pub allow: Vec<String>,
895}
896
897/// Params of [`Request::PeerEndorse`] (#65): vouch for a peer so a third party can install them.
898#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
899#[serde(deny_unknown_fields)]
900pub struct PeerEndorseParams {
901 /// The subject's endpoint id, `eid:<hex>` — usually a peer you are paired with, though the
902 /// daemon does not require that: an endorsement is YOUR statement, and the recipient decides
903 /// what it is worth.
904 pub subject: String,
905 /// The subject's user key, `b64u:`, when you are also vouching for that. The recipient will
906 /// additionally require the SUBJECT's own device binding before trusting it — see
907 /// [`PeerIntroduceParams::subject_binding`].
908 #[serde(default, skip_serializing_if = "Option::is_none")]
909 pub subject_user_id: Option<String>,
910}
911
912/// Result of [`Request::PeerEndorse`] (#65) — hand both fields to the recipient.
913#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
914pub struct PeerEndorseResult {
915 /// YOUR user id, `b64u:` — what the recipient passes as `endorsed_by`. They must already be
916 /// paired with you for it to resolve.
917 pub endorsed_by: String,
918 /// The signature, `b64u:` — what the recipient passes as `evidence`.
919 pub evidence: String,
920}
921
922/// Params of [`Request::PeerIntroduce`] (#65): install a peer vouched for by someone you are
923/// already paired with.
924///
925/// The endorsement replaces pairing's SAS with the endorser's signature, so you are trusting that
926/// endorser's judgment and key hygiene as well as their identity. It buys identity resolution only
927/// — see [`Request::PeerIntroduce`].
928#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
929#[serde(deny_unknown_fields)]
930pub struct PeerIntroduceParams {
931 /// The subject's endpoint id, `eid:<hex>` — who is being introduced.
932 pub subject: String,
933 /// The endorser's user public key, `b64u:`. MUST be the `user_id` of a CURRENTLY paired peer:
934 /// the chain has to terminate at someone you paired with yourself, so an endorsement from a
935 /// stranger — or from someone you have since unpaired — is refused.
936 pub endorsed_by: String,
937 /// The endorser's signature over the domain-separated preimage, `b64u:`.
938 pub evidence: String,
939 /// The subject's OWN user key, `b64u:`, so several of the subject's devices resolve to one
940 /// person. Part of the endorser's signed statement, so it cannot be added or removed after
941 /// the fact.
942 ///
943 /// **Requires `subject_binding` too, and is REFUSED without it.** A `user_id` is
944 /// authorization-bearing — service `allow` lists match on it — so the endorser vouching for it
945 /// is not enough: an endorser could otherwise name a *victim's* `user_id` (which is public, on
946 /// `status` and every audit record) for an attacker's endpoint, and the attacker would inherit
947 /// that victim's grants. The subject must prove the key is theirs.
948 #[serde(default, skip_serializing_if = "Option::is_none")]
949 pub subject_user_id: Option<String>,
950 /// The SUBJECT's own device→user binding for `subject_user_id`, `b64u:` — the same signature a
951 /// peer presents at pairing (`mcpmesh/join/device-binding/1`), proving *it* controls that user
952 /// key and that the key is bound to *this* endpoint.
953 ///
954 /// Two independent signatures are required for a `user_id`, and they say different things: the
955 /// endorser's says "I vouch for this endpoint", the subject's says "this user key is mine".
956 /// Neither alone is sufficient.
957 #[serde(default, skip_serializing_if = "Option::is_none")]
958 pub subject_binding: Option<String>,
959 /// YOUR local name for the subject. Same rules and the same collision guard as pairing (#87).
960 pub nickname: String,
961}
962
963/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
964/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966#[serde(deny_unknown_fields)]
967pub struct OpenSessionParams {
968 #[serde(default)]
969 pub peer: String,
970 #[serde(default)]
971 pub service: String,
972 /// A QUIC idle timeout for THIS session only, in seconds (#166, `api_minor >= 54`).
973 ///
974 /// Absent inherits `[network].idle_timeout_secs`, i.e. today's behaviour. `0` means "no idle
975 /// timeout from this side" — the same meaning the node-wide knob gives it, so the two cannot be
976 /// read differently.
977 ///
978 /// **Only LOWERING is unilateral.** QUIC negotiates `max_idle_timeout` to the MINIMUM of the
979 /// two peers' values (RFC 9000 §10.1), so this can always make a session die sooner when it
980 /// goes quiet and can never make it outlive what the peer allows. Raising needs both peers
981 /// configured — which was already true of the node-wide knob, and which no per-connection seam
982 /// changes.
983 ///
984 /// **Outbound only, and that is not half a feature.** An accepted session uses the node-wide
985 /// value, because iroh gives the server config no per-connection seam — but the direction that
986 /// CAN work one-sidedly is available here, and the direction that cannot never worked anywhere.
987 /// A node wanting a shorter timeout on a session it did not initiate can dial instead.
988 ///
989 /// **Ignored on a RACING dial**, because that opens connections it then abandons. The precise
990 /// rule, since the first version of this sentence was wrong in both directions:
991 ///
992 /// - A **roster person** races whenever the roster lists them with ANY device — including
993 /// exactly one — so a `user_id` naming a rostered person never gets it.
994 /// - A pairing-mode **`b64u:`** races only with TWO OR MORE stored devices; with exactly one it
995 /// falls through to the single-entry path and DOES get it.
996 ///
997 /// The node logs at `warn!` when it drops the value, naming the peer — a caller cannot know how
998 /// many devices a peer has, so a silent drop would be unattributable. Name one device with
999 /// `eid:` to be certain.
1000 ///
1001 /// No per-connection KEEPALIVE: iroh caps the per-path keepalive at 5s and discards larger
1002 /// values, so one could only make pings more frequent — the node-wide knob already refuses that
1003 /// direction (#56).
1004 #[serde(default, skip_serializing_if = "Option::is_none")]
1005 pub idle_timeout_secs: Option<u64>,
1006}
1007
1008/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
1009/// on FIRST install (`b64u:`; omit once pinned — config carries it).
1010#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1011#[serde(deny_unknown_fields)]
1012pub struct RosterInstallParams {
1013 pub path: String,
1014 #[serde(default, skip_serializing_if = "Option::is_none")]
1015 pub org_root_pk: Option<String>,
1016}
1017
1018/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
1019/// never crosses the API.
1020#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1021#[serde(deny_unknown_fields)]
1022pub struct OrgJoinParams {
1023 pub org_id: String,
1024 pub org_root_pk: String,
1025 pub user_id: String,
1026 pub user_key: String,
1027}
1028
1029/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
1030/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
1031/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
1032/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
1033#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1034#[serde(deny_unknown_fields)]
1035pub struct SetAppMetadataParams {
1036 pub metadata: String,
1037}
1038
1039/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
1040/// principal, or a `b64u:` user_id.
1041#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1042#[serde(deny_unknown_fields)]
1043pub struct PeerServicesParams {
1044 pub peer: String,
1045}
1046
1047/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
1048/// caller — computed authoritatively on the peer (which owns the truth), always current, only
1049/// the caller's own admitted services (never the peer's full registry).
1050#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1051pub struct PeerServicesResult {
1052 pub services: Vec<String>,
1053}
1054
1055/// Params of [`Request::PeerDiagnostics`] (#140): the peer to dump — a nickname or an `eid:`
1056/// device principal.
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1058#[serde(deny_unknown_fields)]
1059pub struct PeerDiagnosticsParams {
1060 pub peer: String,
1061}
1062
1063/// Result of [`Request::PeerDiagnostics`] (#140): the DURABLE per-peer state this node carries,
1064/// for diagnosing why a specific long-lived pairing behaves differently from a fresh one.
1065///
1066/// **This surface carries a PEER's transport coordinates on purpose.** The rendered porcelain is
1067/// address-free everywhere — nicknames and path KINDS — because that discipline keeps a peer's
1068/// coordinates out of screenshots. (`SelfNetwork.direct_addrs` already returns this node's OWN
1069/// addresses on `status`; what is new here is another endpoint's.) The question this answers is
1070/// "what address is this node about to dial, and where did it come from", which has no answer
1071/// without the address. It is your own store's record of your own paired peers. Do not render it
1072/// in ordinary porcelain, and read it before pasting it anywhere public.
1073///
1074/// The intended use is a paired capture: run it on BOTH ends of a stuck pairing and compare the
1075/// stored hint against the live path each side reports.
1076#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1077pub struct PeerDiagnosticsResult {
1078 /// The peer's nickname as this node stores it.
1079 pub nickname: String,
1080 /// The peer's stable `eid:` device principal.
1081 pub principal: String,
1082 /// The peer's `b64u:` user_id if it proved a device→user binding at pairing.
1083 #[serde(default, skip_serializing_if = "Option::is_none")]
1084 pub user_id: Option<String>,
1085 /// When the pairing was written (epoch seconds as a string), if recorded. A LONG-LIVED pairing
1086 /// is exactly what #140 is about, so the age is part of the evidence.
1087 #[serde(default, skip_serializing_if = "Option::is_none")]
1088 pub paired_at: Option<String>,
1089 /// The persisted dial HINT, verbatim as stored — the durable state a freshly paired identity
1090 /// does not have. `None` for a peer added without one.
1091 ///
1092 /// It is MERGED with discovery rather than replacing it — iroh inserts it as one more
1093 /// candidate path (`Source::App`) and then triggers address lookup.
1094 ///
1095 /// **But that lookup is skipped when a path is already selected.** iroh's
1096 /// `trigger_address_lookup` returns early if `selected_path.is_some()`, and a selected path is
1097 /// cleared only when the last connection to that peer closes. So on a pair that already holds
1098 /// an open RELAYED connection — live sessions, dial-backs, a working relay — discovery does
1099 /// NOT re-run, and this hint is the only addressing the dial contributes. Do not read "merged,
1100 /// so a stale hint is harmless" as unconditional; it is least true in exactly the state a
1101 /// stuck pairing is in.
1102 ///
1103 /// It is the only durable per-peer state ON THIS NODE'S DISK that the dial path reads, which
1104 /// is what makes it the first thing to compare between two ends. It is not the only durable
1105 /// state a long-lived identity carries — a published discovery record under the same key, and
1106 /// [`SelfNetwork::identity_conflict_epoch`], live elsewhere.
1107 #[serde(default, skip_serializing_if = "Option::is_none")]
1108 pub last_addr: Option<String>,
1109 /// The addresses parsed out of `last_addr`, for reading without a JSON round trip: IP
1110 /// addresses verbatim, relay URLs as `relay <url>` and SANITIZED to scheme+host+port (an
1111 /// operator's relay URL can carry a userinfo token, and this output is meant to be pasted into
1112 /// an issue). Empty when the hint is absent, unparseable, or for a different endpoint — all of
1113 /// which degrade to an id-only dial.
1114 ///
1115 /// A `relay …` entry with no IP alongside it is worth noticing: that hint can never punch.
1116 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1117 pub hint_addrs: Vec<String>,
1118 /// Whether the stored hint actually contributes anything to a dial. `false` with a present
1119 /// `last_addr` means it is being silently discarded — because it does not parse, because its
1120 /// embedded id is a different peer, or (since 0.52.1, #203) because every address in it is one
1121 /// that can never be a QUIC peer and was filtered out. `last_addr` is reported verbatim above,
1122 /// so comparing it against `hint_addrs` distinguishes the three.
1123 pub hint_usable: bool,
1124 /// This node's LIVE view of the peer, read straight from the reachability cache — the same
1125 /// values `status` reports, repeated here so one capture holds both the durable and the live
1126 /// side. `None` when this peer has **never been probed**, which is the honest answer on a
1127 /// freshly restarted daemon; it is not the same as unreachable.
1128 ///
1129 /// Read from the cache rather than through `status`'s projection deliberately: that projection
1130 /// spawns a background probe for every stale peer, which would make this diagnostic a
1131 /// participant in the reproduction it is meant to observe.
1132 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub reachability: Option<PeerReachability>,
1134 /// What **iroh** currently holds for this endpoint, as opposed to what this node stored
1135 /// (#140, `api_minor >= 56`). The other half of the capture, and the half the standing
1136 /// hypothesis lives in.
1137 ///
1138 /// Everything above describes our own disk. Until this field there was no way to see what iroh
1139 /// made of it — whether the hint's addresses are in its remote map at all, whether discovery
1140 /// contributed anything alongside them, or which address is carrying traffic. Read straight off
1141 /// `Endpoint::remote_info`, a point read of the remote map: no dial, no probe, no address
1142 /// lookup, so this stays safe to run ON a live reproduction.
1143 ///
1144 /// **`None` means iroh currently holds NO ENTRY — which is not the same as an empty list, and
1145 /// is not the same as "never heard of".** iroh reaps a remote's state about 60 seconds after
1146 /// the last connection to it closes (`ACTOR_MAX_IDLE_TIMEOUT`), so `None` is the normal answer
1147 /// both for a peer never dialled AND for one talked to a few minutes ago. An empty list means
1148 /// iroh has an entry and holds no address in it.
1149 ///
1150 /// This distinction matters most to the question #140 is asking, which is about durability over
1151 /// time: reading `None` as "iroh never knew this peer" would be wrong on any daemon that has
1152 /// been idle, which is most of them.
1153 #[serde(default, skip_serializing_if = "Option::is_none")]
1154 pub known_addrs: Option<Vec<KnownAddr>>,
1155 /// Addresses in [`hint_addrs`](Self::hint_addrs) that iroh does **not** currently hold.
1156 ///
1157 /// The hint is written whole: `set_last_addr` REPLACES the stored value with one built from the
1158 /// live connection's open IP paths, so these are not accumulated cruft — they are addresses
1159 /// that were real at the last successful connection and are absent from iroh's view now. (An
1160 /// earlier version of this doc said #124 "amends but never removes"; that is false, and
1161 /// `dial_hint.rs` says so in as many words.)
1162 ///
1163 /// **Empty whenever [`known_addrs`](Self::known_addrs) is `None`**, because there is no view to
1164 /// difference against. Reporting the whole hint as unknown when iroh simply has no entry would
1165 /// call a current, correct hint stale on every idle daemon.
1166 ///
1167 /// INFERRED by set difference, not read: iroh 1.0.3's `TransportAddrInfo` carries no
1168 /// provenance, so "did this come from our hint or from discovery?" cannot be answered directly.
1169 /// Naming it an inference is the honest version.
1170 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1171 pub hint_addrs_unknown_to_iroh: Vec<String>,
1172 /// The converse: what iroh holds that our stored hint does not name — inferred the same way,
1173 /// and empty for the same reason when [`known_addrs`](Self::known_addrs) is `None`.
1174 ///
1175 /// **A non-empty list here is the NORMAL state of a healthy peer, and a growing one is not
1176 /// evidence that the stored hint has drifted.** The two lists are built from different things
1177 /// and are expected to differ in size:
1178 ///
1179 /// - [`hint_addrs`](Self::hint_addrs) comes from the open **IP** paths of one live connection —
1180 /// typically one to three addresses.
1181 /// - [`known_addrs`](Self::known_addrs) is iroh's remote map: every address it has learned for
1182 /// the peer, from discovery and from paths, active or not, **relay URLs included**.
1183 ///
1184 /// So this list grows when **iroh learns more candidates**, which is discovery working. It says
1185 /// nothing about whether the hint is current; [`hint_addrs_unknown_to_iroh`] is the field that
1186 /// speaks to that, in the other direction.
1187 ///
1188 /// A relay URL iroh holds will sit here for as long as a hint whose addresses came from
1189 /// `dial_hint::observed_for` stands: that function filters to IP paths, so a value it produced
1190 /// cannot name a relay. Verified end to end against a **real** relay by
1191 /// `a_live_session_refreshes_the_dial_hint_and_never_stores_a_relay`
1192 /// (`cli/tests/dial_hint_refresh.rs`), which starts a relayed session and asserts the healed
1193 /// hint carries the peer's direct address and no relay.
1194 ///
1195 /// **Sourced-from, not written-when — the distinction is load-bearing.** A stored hint can
1196 /// still name a relay three ways, and each is reported rather than hidden: a legacy row written
1197 /// before 0.52.2; a legacy value *carried forward* by a later write, since `merge_hint` and the
1198 /// attestation admit path preserve a stored value rather than originating one; and a direct
1199 /// `PeerStore::add` by an embedder, `allowlist` being a public module.
1200 ///
1201 /// This warning exists because the reading was gotten wrong in the field, on #140 itself: a
1202 /// reporter read this going 5 -> 8 across an upgrade as the hint drifting from iroh's view.
1203 ///
1204 /// [`hint_addrs_unknown_to_iroh`]: Self::hint_addrs_unknown_to_iroh
1205 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1206 pub iroh_addrs_not_in_hint: Vec<String>,
1207}
1208
1209/// One address iroh holds for a peer (#140, `api_minor >= 56`).
1210///
1211/// Rendered by the SAME labelling [`PeerDiagnosticsResult::hint_addrs`] uses — IPs verbatim, relays
1212/// as `relay <url>` sanitized to scheme+host+port — because the two lists exist to be read side by
1213/// side, and differently-formatted addresses would make a formatting difference look like a real
1214/// one. The sanitization is not optional here either: this output is meant to be pasted into a
1215/// public issue, and an operator's relay URL can carry a userinfo token.
1216#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1217pub struct KnownAddr {
1218 /// The address, labelled as above.
1219 pub addr: String,
1220 /// Whether iroh reports this address as in ACTIVE use, as opposed to merely known.
1221 ///
1222 /// **One bit, and it collapses three states.** iroh maps only `PathStatus::Open` to active;
1223 /// `Inactive`, `Unusable` ("we attempted holepunching and it didn't work") and `Unknown` ("we
1224 /// have not yet attempted holepunching") all render `false`. So an idle direct address beside an
1225 /// active relay is *consistent with* #140's selected-path hypothesis and equally consistent with
1226 /// an ordinary failed hole-punch — which is a NAT diagnosis, the opposite conclusion. This field
1227 /// cannot discriminate them; it says what is carrying traffic and no more.
1228 pub active: bool,
1229}
1230
1231/// Params of [`Request::PeerHintClear`] (#140): whose stored dial hint to forget.
1232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1233#[serde(deny_unknown_fields)]
1234pub struct PeerHintClearParams {
1235 /// Nickname / `eid:` / `b64u:` — the same vocabulary every other peer verb takes.
1236 pub peer: String,
1237}
1238
1239/// Result of [`Request::PeerHintClear`] (#140).
1240#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1241pub struct PeerHintClearResult {
1242 /// How many hints were removed. A `b64u:` user_id names EVERY device of that person and the
1243 /// racing dial path attaches a hint for each, so clearing "the" hint would leave the pairing
1244 /// still addressing from stored state while reporting success. Every device is cleared, and the
1245 /// count says how many actually had one.
1246 ///
1247 /// `0` means nothing was stored — already the state this verb produces, so a no-op, not an error.
1248 pub cleared: usize,
1249 /// The raw hints removed, verbatim, in the order the devices resolved.
1250 ///
1251 /// **This is the undo, and since 0.52.2 it is the ONLY one.** There is no `peer_hint_set`, and
1252 /// on the pairing this verb targets the hint may never be rewritten on its own: every writer
1253 /// now stores only what a connection OBSERVED, and all of them decline to store anything for a
1254 /// relay-only connection — which is the defining property of a stuck pair. Re-pairing no longer
1255 /// reliably restores it either: the ceremony writes a hint only if it observes a direct path,
1256 /// and on a pair that cannot punch it does not. Keep this value.
1257 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1258 pub forgotten: Vec<String>,
1259}
1260
1261/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
1262/// to remove — the deregistration mirror of `register_service`.
1263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1264#[serde(deny_unknown_fields)]
1265pub struct UnregisterServiceParams {
1266 pub name: String,
1267}
1268
1269/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
1270/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
1271/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
1272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1273#[serde(deny_unknown_fields)]
1274pub struct ServiceAllowParams {
1275 pub service: String,
1276 pub principal: String,
1277}
1278
1279/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
1280/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
1281/// they stored at pairing time until a re-invite.
1282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1283#[serde(deny_unknown_fields)]
1284pub struct SetNicknameParams {
1285 pub nickname: String,
1286}
1287
1288/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
1289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1290#[serde(deny_unknown_fields)]
1291pub struct SetRosterUrlParams {
1292 pub url: String,
1293}
1294
1295/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
1296/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
1297/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
1298/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
1299/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
1300/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
1301/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
1302/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
1303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1304#[serde(deny_unknown_fields)]
1305pub struct SetRelaysParams {
1306 pub relay_urls: Vec<String>,
1307}
1308
1309/// Result of [`Request::SetRelays`] (#53).
1310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1311pub struct SetRelaysResult {
1312 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
1313 pub changed: bool,
1314 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
1315 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
1316 /// live custom→custom path (already applied to the running endpoint).
1317 pub restart_required: bool,
1318}
1319
1320/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
1321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1322#[serde(deny_unknown_fields)]
1323pub struct BlobPublishParams {
1324 pub scope: String,
1325 pub path: String,
1326}
1327
1328/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
1329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1330#[serde(deny_unknown_fields)]
1331pub struct BlobGrantParams {
1332 pub scope: String,
1333 pub principal: String,
1334}
1335
1336/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
1337///
1338/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
1339/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
1340/// access to everything else.
1341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1342#[serde(deny_unknown_fields)]
1343pub struct BlobRevokeParams {
1344 pub scope: String,
1345 pub principals: Vec<String>,
1346}
1347
1348/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
1349///
1350/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
1351/// this takes effect immediately for authorization — but the bytes stay in the local store until a
1352/// GARBAGE-COLLECTION sweep reclaims them, and only a node that set `[blobs].gc_interval` runs one
1353/// (#80, `api_minor >= 49`). There is no reclaim VERB — collection is periodic and configured at
1354/// store construction, so "deleted" means "deleted within an interval" at best. On a node with no
1355/// interval configured — the default — the bytes stay forever. Do not surface this to a user as
1356/// deletion unless you know the node collects.
1357#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1358#[serde(deny_unknown_fields)]
1359pub struct BlobUnpublishParams {
1360 pub scope: String,
1361 pub hash: String,
1362}
1363
1364/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
1365///
1366/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
1367/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
1368/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
1369/// turn the original publisher going offline into a hang at every fetcher.
1370///
1371/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
1372/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
1373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1374#[serde(deny_unknown_fields)]
1375pub struct BlobRepublishParams {
1376 pub scope: String,
1377 pub hash: String,
1378}
1379
1380/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
1381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1382#[serde(deny_unknown_fields)]
1383pub struct BlobFetchParams {
1384 pub ticket: String,
1385 pub dest_path: String,
1386 /// ADDITIONAL sources to try if the ticket's publisher does not answer (#83).
1387 /// `api_minor >= 47`.
1388 ///
1389 /// Content addressing makes every recipient a potential source, and without this the control
1390 /// API made that unusable: a ticket names ONE address, so a file shared with a room became
1391 /// unfetchable the moment the sender closed their laptop — even though other people in the room
1392 /// already held the identical, verified bytes.
1393 ///
1394 /// Each entry is a stable principal (`eid:` device, `b64u:` user_id) or a paired nickname —
1395 /// the same vocabulary `open_session` takes. They are preferred **in order, after** the ticket's
1396 /// own address, so the publisher stays the first choice and a live one costs nothing —
1397 /// alternates are not dialled at all when it answers.
1398 ///
1399 /// Since 0.49.1 the dials are **hedged**: an alternate starts about a second after a source has
1400 /// failed to answer, rather than after that source's full dial timeout. A source unreachable at
1401 /// the head of the list therefore costs about a second, not twenty, and a long `from` list is no
1402 /// longer a long wait. Each source is still dialled at most once.
1403 ///
1404 /// **An alternate only works if it can serve you.** The bytes are BLAKE3-verified against the
1405 /// ticket's hash whoever supplies them, so a hostile alternate cannot substitute content — but
1406 /// it must have republished the hash into a scope that grants you, or it answers with a
1407 /// permission refusal and the fetch moves on. Every failure mode falls through, not only an
1408 /// unreachable dial: a refusal, a missing hash, a mid-stream reset, and a stalled transfer all
1409 /// move to the next source.
1410 ///
1411 /// Additive: absent from an older caller's payload and read as empty, which is the
1412 /// single-source behaviour.
1413 /// Capped at [`MAX_BLOB_SOURCES`]; more is an error rather than a silent truncation.
1414 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1415 pub from: Vec<String>,
1416}
1417
1418/// The ceiling on [`BlobFetchParams::from`] (#83).
1419///
1420/// Naming a PERSON expands to every device of theirs, so the list a caller writes is not the number
1421/// of dials it buys. Comfortably above "everyone in a room", far below anything that turns a fetch
1422/// into an hour.
1423///
1424/// **The justification changed in 0.49.1 and the number did not.** Until then sources were tried
1425/// strictly in turn, each costing up to a dial timeout, so the cap bounded a WAIT. Dials are now
1426/// hedged, which bounds the wait by roughly a second per unresponsive source instead — but the cap
1427/// still bounds the WORK: a fetch holds one of the connection's [`MAX_INFLIGHT`] slots, and a long
1428/// list is a long list of other people's machines being asked to answer.
1429///
1430/// Exceeding it is an ERROR, not a truncation: silently dropping the tail would make a fetch fail
1431/// while the source that had the blob sat unused, which is exactly what this feature exists to
1432/// prevent.
1433pub const MAX_BLOB_SOURCES: usize = 32;
1434
1435/// Params of [`Request::BlobFetchCancel`] (#172): stop every in-flight [`Request::BlobFetch`] of
1436/// this blob.
1437///
1438/// Keyed by HASH, not by JSON-RPC id, and the reason is not aesthetic: [`crate::ControlClient`]
1439/// borrows `&mut self` for a request's whole duration, so a client physically cannot send an
1440/// id-keyed cancel down the connection whose request it would name. A hash is reachable from
1441/// anywhere — including a fresh connection — and it is already the key a consumer holds, since
1442/// every [`crate::StreamFrame::BlobTransfer`] carries it.
1443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1444#[serde(deny_unknown_fields)]
1445pub struct BlobFetchCancelParams {
1446 /// The blob's BLAKE3 hash, hex — as it appears on `BlobTransfer` frames and `BlobFetchResult`.
1447 pub hash: String,
1448}
1449
1450/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
1451/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
1452///
1453/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
1454/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
1455/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
1456/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
1457/// identical to inline variant bodies.
1458///
1459/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
1460/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
1461/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
1462/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
1463/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
1464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1465#[serde(tag = "method", content = "params", rename_all = "snake_case")]
1466pub enum Request {
1467 /// Register/update a `[services.*]` entry idempotently.
1468 RegisterService(RegisterServiceParams),
1469 Status,
1470 /// Mint a pairing invite granting `services` — single-use unless `max_uses` says otherwise
1471 /// (#87). The daemon
1472 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
1473 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
1474 /// `method` string generically; the tag comes from `rename_all`.
1475 Invite(InviteParams),
1476 /// Redeem a pairing invite. The daemon dials the inviter named by
1477 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
1478 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
1479 /// (snake_case); `method_of` reads the `method` string generically.
1480 ///
1481 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1482 Pair(PairParams),
1483 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
1484 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
1485 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
1486 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
1487 /// NOT severed here: existing sessions run to completion; the peer only loses the
1488 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
1489 /// `method_of` reads the `method` string generically (no per-variant arm).
1490 ///
1491 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1492 PeerRemove(PeerRemoveParams),
1493 /// Rename a contact's nickname (nickname) authoritatively. Renames the
1494 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
1495 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
1496 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
1497 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
1498 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
1499 /// host-privileged like the other pair ops.
1500 PeerRename(PeerRenameParams),
1501 /// Mint an attestation OFFER (#85 ask 3): a `mcpmesh-attest:` line telling another device of a
1502 /// person you already pair with where to dial. Tag `"attest_offer"`.
1503 ///
1504 /// **Carries nothing secret** — the offering node's id and address, both of which an invite
1505 /// line already carries in the clear. It exists because a device freshly restored from a
1506 /// recovery phrase holds no rows and so has no way to find anyone.
1507 ///
1508 /// Refused unless this node has `[identity].admit_attested_devices` on: an offer it would not
1509 /// honour is worse than no offer.
1510 AttestOffer,
1511 /// Present THIS device's identity to a peer, using their `mcpmesh-attest:` line (#85 ask 3).
1512 /// Tag `"attest_to"`.
1513 ///
1514 /// The recovery path's second half: `user_key_import` restores the `b64u:` your peers pinned,
1515 /// and this is what gets the machine holding it ADMITTED. Requires a user key — with none there
1516 /// is nothing to attest.
1517 ///
1518 /// The peer admits this device only if it already holds a row for this person, has opted in,
1519 /// and has revoked neither this endpoint nor the IDENTITY. It cannot admit a stranger.
1520 AttestTo(AttestToParams),
1521 /// REVOKE an endpoint locally: "I no longer trust this device" (#85 ask 4). Tag
1522 /// `"peer_revoke"`.
1523 ///
1524 /// **Not the same act as [`PeerRemove`](Self::PeerRemove), deliberately.** Removal is routine —
1525 /// we are not working together any more — and re-pairing afterwards is normal. Revocation is a
1526 /// claim about COMPROMISE, and it outlives the pair row: a revoked endpoint is refused whether
1527 /// or not it is in the allowlist, so it cannot be undone by a fresh pairing. Making them one
1528 /// verb would either make removal irreversible or make revocation weak.
1529 ///
1530 /// Takes effect IMMEDIATELY, like `service_allow_revoke` (#54): live sessions are severed
1531 /// rather than left to end on their own, which for long-lived MCP sessions is unbounded.
1532 ///
1533 /// A `b64u:` principal revokes EVERY endpoint this node associates with that person — the "not
1534 /// on any of their devices" case, which an operator will otherwise get wrong doing it device by
1535 /// device.
1536 ///
1537 /// Reversible with [`PeerUnrevoke`](Self::PeerUnrevoke): this list is LOCAL and not
1538 /// authoritative for anyone else, so an operator mistake has to be fixable. Both directions are
1539 /// audited.
1540 PeerRevoke(PeerRevokeParams),
1541 /// Lift a local revocation (#85 ask 4). Tag `"peer_unrevoke"`. Idempotent.
1542 ///
1543 /// Restores the peer only if its pair row still exists — revocation never deleted it. A
1544 /// revocation applied from a SIGNED statement can be lifted too: the signature proved who asked,
1545 /// not that this node must obey forever.
1546 PeerUnrevoke(PeerUnrevokeParams),
1547 /// Sign a revocation of one of THIS node's own endpoints with THIS node's user key (#85 ask 4),
1548 /// producing a portable token. Tag `"device_revoke"`.
1549 ///
1550 /// The direction that matters, and the one local revocation cannot express: my laptop was
1551 /// stolen, and my peers cannot discover that by themselves. I have to tell them, and they have
1552 /// to be able to verify it was me.
1553 ///
1554 /// Requires a user key — a node with none has no authority to speak for its person.
1555 /// **Distribution is out of band**: pairing mode has no gossip, so getting the token to your
1556 /// peers is the same problem as getting them an invite line, and has the same answer.
1557 DeviceRevoke(DeviceRevokeParams),
1558 /// Apply a signed device revocation from a peer (#85 ask 4). Tag `"device_revocation_import"`.
1559 ///
1560 /// Refused unless this node ALREADY trusts the signing `user_id` (holds a paired entry carrying
1561 /// it) **and** the revoked endpoint is one this node associates with that same person, or is
1562 /// entirely unknown to it. That bound is what keeps this from being an "mark any endpoint dead"
1563 /// primitive: a peer may kill their OWN devices in your node, and nothing else.
1564 DeviceRevocationImport(DeviceRevocationImportParams),
1565 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
1566 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
1567 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
1568 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
1569 /// vocabulary — do not build on it. Tag `"peer_add"`.
1570 PeerAdd(PeerAddParams),
1571 /// Install a peer from a SIGNED endorsement by someone you are already paired with (#65) —
1572 /// O(N) onboarding for a small group, without a fresh two-human SAS ceremony per pair.
1573 ///
1574 /// **It installs IDENTITY, never AUTHORIZATION.** The subject becomes resolvable; it is granted
1575 /// nothing. Service access stays principal-keyed in config (#38) and an explicit, separate act.
1576 /// That is what bounds the feature: a compromised endorser can make you KNOW about an attacker,
1577 /// it cannot make you SERVE one.
1578 ///
1579 /// Unlike [`PeerAdd`](Self::PeerAdd) — which is reserved precisely because the caller merely
1580 /// ASSERTS an id — this is verifiable: the endorsement is checked against a user key you
1581 /// already hold from pairing with the endorser. Tag `"peer_introduce"`.
1582 PeerIntroduce(PeerIntroduceParams),
1583 /// PRODUCE an endorsement of a peer, for someone else to redeem with
1584 /// [`PeerIntroduce`](Self::PeerIntroduce) (#65). The other half of an introduction: without it
1585 /// nothing can generate `evidence`, and the install half is unusable.
1586 ///
1587 /// Signs with THIS node's user key, so the result is only meaningful to someone who has paired
1588 /// with you. Endorsing does not change your own trust in the subject. Tag `"peer_endorse"`.
1589 PeerEndorse(PeerEndorseParams),
1590 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
1591 /// Distinct from the proxy's job: this returns a session the client streams.
1592 /// Named `open_session` rather than `connect` to avoid colliding
1593 /// with the `connect` porcelain.
1594 OpenSession(OpenSessionParams),
1595 /// Install a signed roster from a local file (the manual `internal roster install` path).
1596 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
1597 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
1598 /// pins the org root on FIRST install (`b64u:`); omit it
1599 /// once pinned (config carries it). Tag `"roster_install"`.
1600 RosterInstall(RosterInstallParams),
1601 /// Read the installed roster's MEMBERSHIP: the declared groups, and every person with their
1602 /// display name, groups, and devices (#93). Parameterless. Tag `"roster_members"`.
1603 ///
1604 /// The read half of roster mode. `status` reports that a roster exists (`RosterStatus`) and who
1605 /// is currently online (`PresencePeer`); neither answered "who is in this org" — a person with
1606 /// no live device appeared nowhere at all, so an embedder could not draw a member list, and
1607 /// the only route to one was hand-parsing the daemon-owned `roster.json`.
1608 ///
1609 /// ADVISORY and display-oriented, like `status`: the gate reads the roster document, never
1610 /// this. Empty in a pure-pairing daemon or before the first roster is installed.
1611 RosterMembers,
1612 /// AUTHOR an org: mint this node's org root key, sign an empty roster (serial 1), install it
1613 /// (which pins the root), and return the copyable org invite (#66). Tag `"org_create"`.
1614 ///
1615 /// One-time per node — a second call is refused rather than replacing the key, because
1616 /// replacing it would orphan every roster it has signed.
1617 OrgCreate(OrgCreateParams),
1618 /// APPROVE a join code into the roster: verify its device→user-key binding, upsert the member
1619 /// with the given groups, bump the serial, re-sign, install (#66). Tag `"org_approve"`.
1620 ///
1621 /// The cryptographic half of the ceremony. Verifying that the code came from the PERSON you
1622 /// think it did stays an out-of-band human step, and `join_code_fingerprint` in the result is
1623 /// what the two humans compare.
1624 OrgApprove(OrgApproveParams),
1625 /// ROTATE the org root (#93 ask c). Tag `"org_rotate"`.
1626 ///
1627 /// The org's trust anchor is one pinned key, and nothing could move it: an operator laptop that
1628 /// died took the org with it 90 days later, when the roster expired — and the delay is what
1629 /// made that hard to diagnose. Recovery was O(N) fresh ceremonies with every member.
1630 ///
1631 /// Publishes a roster signed by the SUCCESSOR carrying a cross-signature by the CURRENT root, so
1632 /// a member still pinned to the current key adopts the successor with the key it already has.
1633 /// The bridge rides every subsequent roster, so a member offline for one publication catches up
1634 /// — but one two rotations behind needs a fresh `org_join`.
1635 ///
1636 /// **This is not escrow.** If the current root key is LOST there is nothing to sign the bridge
1637 /// with. Copying `org-root.key` to a second operator machine already works and remains the
1638 /// answer for that.
1639 OrgRotate(OrgRotateParams),
1640 /// INSPECT a join code without approving it (#66): who it claims to be, and the fingerprint the
1641 /// two humans compare. Read-only — nothing is signed, installed, or persisted.
1642 /// Tag `"org_join_code"`.
1643 ///
1644 /// This is what makes an "approve this person" button correct rather than merely possible. The
1645 /// fingerprint has to be shown and confirmed out-of-band BEFORE the approval, because a
1646 /// substituted code is caught there or not at all — and reading it off `OrgApprove`'s result
1647 /// is too late, the member is already in the signed roster. The CLI always had this (it
1648 /// decoded the code locally); an embedder could not, since the join-code format lives in
1649 /// `mcpmesh-node` and not on this seam.
1650 OrgJoinCode(OrgJoinCodeParams),
1651 /// REVOKE from the roster: remove a person, one device, or a person's user key, then bump,
1652 /// re-sign, and install — which severs the cut devices' live sessions (#66).
1653 /// Tag `"org_revoke"`.
1654 OrgRevoke(OrgRevokeParams),
1655 /// EXPORT this node's user key as a recovery phrase (#85 ask 2). Parameterless.
1656 /// Tag `"user_key_export"`.
1657 ///
1658 /// **The phrase IS the private key**, in a form a human can write down. Anyone who reads it can
1659 /// present this identity. It is deliberately not logged, not audited, and not echoed anywhere
1660 /// but this response.
1661 UserKeyExport,
1662 /// IMPORT a user key from a recovery phrase (#85 ask 2), so a person's `b64u:` survives the
1663 /// hardware. Tag `"user_key_import"`.
1664 UserKeyImport(UserKeyImportParams),
1665 /// DETACH this device from an identity it was ENROLLED into (#214) — the inverse of the
1666 /// adoption a `pair { allow_self_enroll }` performs (#86). Parameterless. Tag
1667 /// `"self_enroll_detach"`.
1668 ///
1669 /// Drops the adopted device→user binding, live and on disk, so this node goes back to
1670 /// presenting its own identity (imported, else boot-derived). The exit that self-enrollment
1671 /// otherwise lacks: an
1672 /// enrolled device holds no user key, so `user_key_import` — the only other verb that clears
1673 /// the slot — is not available to it, and a person handed a substituted `mcpmesh-enroll:` line
1674 /// was permanently a device of a stranger's identity.
1675 ///
1676 /// **Local only.** It does not reach any peer: whoever already learned this endpoint as that
1677 /// person's device still believes it. Telling THEM is `device_revoke`, issued from the device
1678 /// that holds the key. Refused with [`ERR_NOT_ENROLLED`] when nothing is adopted.
1679 SelfEnrollDetach,
1680 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
1681 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
1682 /// `user_key` is a LOCAL path
1683 /// (the key never crosses the API). Tag `"org_join"`.
1684 OrgJoin(OrgJoinParams),
1685 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
1686 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
1687 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
1688 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
1689 /// `"set_roster_url"`.
1690 SetRosterUrl(SetRosterUrlParams),
1691 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
1692 /// daemon's own serialized config-write path (no lost-update window against a
1693 /// concurrent grant/registration) and update the in-memory name future invites
1694 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
1695 SetNickname(SetNicknameParams),
1696 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
1697 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
1698 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
1699 /// on restart; the embedder re-sets on startup).
1700 SetAppMetadata(SetAppMetadataParams),
1701 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
1702 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
1703 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
1704 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
1705 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
1706 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
1707 /// [`SetRelaysResult`]. Tag `"set_relays"`.
1708 SetRelays(SetRelaysParams),
1709 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
1710 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
1711 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
1712 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
1713 /// hot-reloads. Idempotent. Ack result.
1714 UnregisterService(UnregisterServiceParams),
1715 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
1716 /// and returns the service names whose allow admits the caller's principal. Answers
1717 /// [`PeerServicesResult`].
1718 PeerServices(PeerServicesParams),
1719 /// Dump the DURABLE per-peer state this node carries for one peer (#140) — the persisted dial
1720 /// hint, the pairing stamp, and the live reachability row, in one capture. A DIAGNOSTIC verb:
1721 /// unlike every other surface it carries transport vocabulary on purpose. Answers with
1722 /// [`PeerDiagnosticsResult`]. `api_minor >= 33`.
1723 PeerDiagnostics(PeerDiagnosticsParams),
1724 /// FORGET the persisted dial hint for one peer (#140) — `api_minor >= 59`.
1725 ///
1726 /// An experiment tool, and a workaround. `PeerEntry.last_addr` is the only durable per-peer
1727 /// state on this node's disk that the dial path reads, and it is the ONLY thing a long-lived
1728 /// pairing carries that a freshly paired identity does not. Nothing invalidates it: a
1729 /// relay-only connection deliberately declines to overwrite it (persisting a relay URL over a
1730 /// direct candidate was #124's own bug), and "learned nothing" means leave alone. So a hint
1731 /// written before a network change can persist indefinitely on a pair whose every connection
1732 /// since has been relayed.
1733 ///
1734 /// Clearing it makes an existing pairing **addressing-equivalent to a fresh identity**, which
1735 /// is exactly the difference #140 is about — a pair that cannot punch as a long-lived pairing
1736 /// while punching in 23ms with fresh identities on the same hardware.
1737 ///
1738 /// **Advisory, never authorization.** A hint is addressing; its absence is a supported state
1739 /// (the dial degrades to id-only, which is what every peer does before its first refresh). The
1740 /// worst case is one slower dial while discovery runs. The peer row, its `user_id`, its
1741 /// services and its pairing stamp are untouched.
1742 ///
1743 /// Nothing clears a hint automatically — choosing an invalidation policy before the data exists
1744 /// is what produced a fix that helped one peer and not this one. Answers
1745 /// [`PeerHintClearResult`].
1746 PeerHintClear(PeerHintClearParams),
1747 ServiceAllowGrant(ServiceAllowParams),
1748 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
1749 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
1750 /// Idempotent. Ack result.
1751 ServiceAllowRevoke(ServiceAllowParams),
1752 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
1753 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
1754 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
1755 /// Tag `"blob_publish"`.
1756 BlobPublish(BlobPublishParams),
1757 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
1758 /// nickname (the shared `principal_set` expansion). Tag
1759 /// `"blob_grant"`.
1760 BlobGrant(BlobGrantParams),
1761 /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
1762 BlobRevoke(BlobRevokeParams),
1763 /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
1764 /// bytes.
1765 BlobUnpublish(BlobUnpublishParams),
1766 /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
1767 /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
1768 /// two interchangeably after a fetch.
1769 BlobRepublish(BlobRepublishParams),
1770 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
1771 BlobList(BlobListParams),
1772 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
1773 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
1774 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
1775 BlobFetch(BlobFetchParams),
1776 /// Cancel every in-flight [`BlobFetch`](Self::BlobFetch) of one hash (#172). Answers a
1777 /// [`BlobFetchCancelResult`]; the cancelled fetches themselves answer [`ERR_CANCELLED`].
1778 /// Tag `"blob_fetch_cancel"`.
1779 BlobFetchCancel(BlobFetchCancelParams),
1780 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
1781 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
1782 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
1783 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
1784 /// `method_of` reads the `method` string generically (no per-variant arm).
1785 AuditSummary,
1786 /// Delete audit months strictly older than `before` (#88) — the retention lever the log
1787 /// never had. Local-only and owner-only (the control socket is the daemon owner's). Answers
1788 /// [`AuditPruneResult`]. Tag `"audit_prune"`.
1789 AuditPrune(AuditPruneParams),
1790 /// Read this node's LOCAL audit records, filtered and paged (#88) — the "show me everything
1791 /// you hold about me" verb. Local-only; nothing is transmitted. Answers
1792 /// [`AuditListResult`]. Tag `"audit_list"`.
1793 AuditList(AuditListParams),
1794 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
1795 /// connection STOPS being request/response after this call and becomes a one-way push stream
1796 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
1797 Subscribe,
1798}
1799
1800/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
1801/// computed porcelain-side from the invite's org_root_pk). Additive-only.
1802#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1803pub struct OrgJoinResult {
1804 pub org_id: String,
1805 /// `true` when the org root was pinned but this node's ROSTER TRANSPORT is not running, so the
1806 /// join is only half in effect until the daemon restarts (#93). `api_minor >= 46`.
1807 ///
1808 /// Roster mode is decided at BOOT: it fixes the ALPN set bound on the endpoint and whether
1809 /// gossip, presence and app-blobs are constructed at all. The roster GATE hot-swaps live. So a
1810 /// node that booted in pairing mode and then joins an org reaches a state where MCP sessions to
1811 /// org members work as soon as a roster arrives, while `status.presence` stays permanently
1812 /// empty and every blob verb hard-closes with `blobs not enabled` — succeeding partially, with
1813 /// no error anywhere, which a caller previously had no way to detect.
1814 ///
1815 /// **What to do with it:** if `true`, tell the user the join succeeded and the node must
1816 /// restart before presence and file sharing work. Do not treat it as a failure — nothing was
1817 /// left half-written; the pin is durable and the restart is sufficient.
1818 ///
1819 /// `false` when the transport is already composed (the node booted with an org root pinned), or
1820 /// on a re-join of an org this node is already in.
1821 ///
1822 /// Same shape as [`SetRelaysResult::restart_required`] (#53), for the same reason. Additive:
1823 /// absent from an older daemon's payload and reads as `false` — which was that daemon's
1824 /// implicit, and wrong, answer.
1825 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1826 pub restart_required: bool,
1827}
1828
1829/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
1830/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
1831/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
1832///
1833/// Additive-only: any future field MUST land as
1834/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1835#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1836pub struct RosterInstallResult {
1837 pub org_id: String,
1838 pub serial: u64,
1839 /// How many live sessions were severed, for the porcelain's confirmation line.
1840 #[serde(default)]
1841 pub severed: u32,
1842}
1843
1844/// Params of [`Request::OrgCreate`] (#66).
1845#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1846#[serde(deny_unknown_fields)]
1847pub struct OrgCreateParams {
1848 /// The org's name — its `org_id`, the value every member's roster carries.
1849 pub name: String,
1850 /// How long the signed roster stays valid, in seconds. Omit for the 90-day default.
1851 ///
1852 /// This is an operator-grade default and a sharp edge at small scale: past it the roster
1853 /// degrades and the group stops working, which for a handful of laptops can arrive days after
1854 /// one of them was closed for a long weekend. A small team should pass a long value here
1855 /// deliberately rather than discover the default later.
1856 #[serde(default, skip_serializing_if = "Option::is_none")]
1857 pub expires_secs: Option<i64>,
1858 /// An HTTPS URL where the signed roster will be published. Carried in the org invite (so a
1859 /// joiner bootstraps its first roster) AND pinned in this operator's `[roster].url`.
1860 #[serde(default, skip_serializing_if = "Option::is_none")]
1861 pub roster_url: Option<String>,
1862}
1863
1864/// Result of [`Request::OrgCreate`] (#66).
1865#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1866pub struct OrgCreateResult {
1867 pub org_id: String,
1868 pub serial: u64,
1869 /// The copyable `mcpmesh-org:` invite to hand a joiner — one of the two permitted opaque
1870 /// artifacts on this surface, the same carve-out the pairing invite line takes.
1871 pub org_invite: String,
1872 /// The org root's fingerprint in short words, for the out-of-band read-back that anchors every
1873 /// joiner's trust. NOT the key.
1874 pub org_root_fingerprint: String,
1875}
1876
1877/// Params of [`Request::OrgRotate`] (#93 ask c).
1878#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1879#[serde(deny_unknown_fields)]
1880pub struct OrgRotateParams {
1881 /// Where to read or write the successor key. Omit for `<config>/org_root_next.key`.
1882 ///
1883 /// Reused if it already exists, so a rotation can be prepared on a machine that is not the one
1884 /// publishing it.
1885 #[serde(default, skip_serializing_if = "Option::is_none")]
1886 pub new_key_path: Option<String>,
1887}
1888
1889/// Result of [`Request::OrgRotate`] (#93 ask c).
1890#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
1891pub struct OrgRotateResult {
1892 pub org_id: String,
1893 pub serial: u64,
1894 /// The new anchor, `b64u:`. Members adopt it as they receive the roster.
1895 pub new_root_pk: String,
1896 /// Short fingerprints, for an operator to read out when telling members what changed.
1897 pub old_root_fingerprint: String,
1898 pub new_root_fingerprint: String,
1899}
1900
1901/// Params of [`Request::OrgApprove`] (#66).
1902#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1903#[serde(deny_unknown_fields)]
1904pub struct OrgApproveParams {
1905 /// The `mcpmesh-join:` code the joiner sent.
1906 pub join_code: String,
1907 /// The groups to grant. Each must be DECLARED in the roster (see
1908 /// [`RosterMembersResult::groups`]) — an undeclared one is refused, because it would make an
1909 /// `allow` entry naming it ambiguous.
1910 #[serde(default)]
1911 pub groups: Vec<String>,
1912 /// Override the `user_id` the joiner requested. Omit to accept theirs.
1913 ///
1914 /// Worth using: the requested id is chosen by the person being approved, and it is the string
1915 /// every `allow` entry will name.
1916 #[serde(default, skip_serializing_if = "Option::is_none")]
1917 pub user_id: Option<String>,
1918}
1919
1920/// Result of [`Request::OrgApprove`] (#66).
1921#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1922pub struct OrgApproveResult {
1923 pub user_id: String,
1924 pub groups: Vec<String>,
1925 pub org_id: String,
1926 pub serial: u64,
1927 /// The join code's fingerprint in short words — the enrollment analogue of the pairing SAS.
1928 ///
1929 /// **Show this to the operator and have them confirm it out-of-band before trusting the
1930 /// approval.** Nothing else binds the person to the `user_pk` in the code, so a substituted
1931 /// code is caught here or not at all. Returned rather than checked, because only the human can
1932 /// check it.
1933 pub join_code_fingerprint: String,
1934}
1935
1936/// Params of [`Request::UserKeyImport`] (#85 ask 2).
1937#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1938#[serde(deny_unknown_fields)]
1939pub struct UserKeyImportParams {
1940 /// The recovery phrase, as written down. Whitespace and case are forgiven; a wrong word, the
1941 /// wrong count, or a failed checksum are refused by position rather than guessed at.
1942 pub recovery_phrase: String,
1943 /// Replace an EXISTING user key. Defaults to `false`, and the refusal is the point: importing
1944 /// over a live key discards the identity this node currently presents, which is irreversible
1945 /// without that key's own phrase.
1946 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1947 pub replace: bool,
1948}
1949
1950/// Result of [`Request::UserKeyExport`] (#85 ask 2).
1951///
1952/// **`recovery_phrase` is the private key.** Show it to the person who owns it, once, and do not
1953/// persist it anywhere your application would not persist the key file itself.
1954#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1955pub struct UserKeyExportResult {
1956 /// 33 words. Write them down in order.
1957 pub recovery_phrase: String,
1958 /// The `b64u:` identity this phrase restores — safe to display and to record, unlike the
1959 /// phrase. Compare it after an import to confirm the right identity came back.
1960 pub user_id: String,
1961}
1962
1963/// REDACTING `Debug` — the phrase is a private key, and a derived one would put it in any
1964/// `tracing::debug!(?params)` a future change adds to the dispatch, or in an embedder's `dbg!`.
1965/// Three lines to make that leak unrepresentable rather than merely absent today.
1966impl std::fmt::Debug for UserKeyImportParams {
1967 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1968 f.debug_struct("UserKeyImportParams")
1969 .field("recovery_phrase", &"<redacted>")
1970 .field("replace", &self.replace)
1971 .finish()
1972 }
1973}
1974
1975/// REDACTING `Debug` — see [`UserKeyImportParams`]. The `user_id` is safe and is kept, because a
1976/// `{:?}` with nothing in it is worse for debugging than one with the non-secret half.
1977impl std::fmt::Debug for UserKeyExportResult {
1978 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1979 f.debug_struct("UserKeyExportResult")
1980 .field("recovery_phrase", &"<redacted>")
1981 .field("user_id", &self.user_id)
1982 .finish()
1983 }
1984}
1985
1986/// Result of [`Request::SelfEnrollDetach`] (#214).
1987#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1988pub struct SelfEnrollDetachResult {
1989 /// The `b64u:` identity now in effect — this node's own (imported, else boot-derived). What a
1990 /// UI shows to confirm the exit took. `None` only when this node has no user key of its own: boot mints
1991 /// one, so that is a boot that could NOT load or mint it (logged as a warning there) — the
1992 /// same condition under which `status.self_user_id` is absent.
1993 #[serde(default, skip_serializing_if = "Option::is_none")]
1994 pub user_id: Option<String>,
1995 /// The `b64u:` identity this device has STOPPED presenting — the one it was enrolled into.
1996 pub detached_from: String,
1997}
1998
1999/// Result of [`Request::UserKeyImport`] (#85 ask 2).
2000#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2001pub struct UserKeyImportResult {
2002 /// The `b64u:` identity now in effect. **Compare it against the one you are recovering** — the
2003 /// phrase's checksum catches most transcription errors, but a `user_id` that does not match is
2004 /// the definitive answer, and the only one that distinguishes "restored the wrong key" from
2005 /// "peers have not seen me yet".
2006 pub user_id: String,
2007 /// `true` when this discarded a REAL identity — a user key the node had loaded from disk, or
2008 /// one an earlier import in this daemon's lifetime wrote (#221), rather than one it minted at
2009 /// this boot and had never presented to anyone.
2010 ///
2011 /// The distinction is the useful one: a fresh node always has a key on disk before an import
2012 /// can run (its own boot mints one), so "a file existed" would be `true` for every recovery on
2013 /// new hardware and would have a UI warn that something was destroyed when nothing was.
2014 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2015 pub replaced: bool,
2016}
2017
2018/// Params of [`Request::OrgJoinCode`] (#66).
2019#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2020#[serde(deny_unknown_fields)]
2021pub struct OrgJoinCodeParams {
2022 /// The `mcpmesh-join:` code to inspect.
2023 pub join_code: String,
2024}
2025
2026/// Result of [`Request::OrgJoinCode`] (#66): what a join code claims, plus the fingerprint that
2027/// decides whether to believe it.
2028///
2029/// The claims are ATTACKER-CONTROLLED — they come out of a code someone handed you. `display_name`
2030/// and `requested_user_id` are what the sender asked for, not facts. What is verified is the
2031/// device→user-key binding (a bad one is refused rather than reported), and what is *checkable* is
2032/// `join_code_fingerprint`.
2033#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2034pub struct OrgJoinCodeResult {
2035 /// The human name the code carries. Sender-chosen — render it, do not trust it.
2036 pub display_name: String,
2037 /// The `user_id` the sender is asking for. Sender-chosen, and it is what every `allow` entry
2038 /// would name, so it is worth an operator's attention before approving.
2039 pub requested_user_id: String,
2040 /// The label of the device being enrolled. Sender-chosen.
2041 pub device_label: String,
2042 /// The fingerprint in short words — the enrollment analogue of the pairing SAS.
2043 ///
2044 /// **Show this and have the operator confirm it out-of-band before calling
2045 /// [`Request::OrgApprove`].** Nothing in a join code binds it to a person; a substituted code
2046 /// carries a different `user_pk` and so diverges here. This is the entire check.
2047 pub join_code_fingerprint: String,
2048}
2049
2050/// Params of [`Request::OrgRevoke`] (#66).
2051#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2052#[serde(deny_unknown_fields)]
2053pub struct OrgRevokeParams {
2054 /// Who or what to revoke: a `user_id` (the person and every device), or `"<user_id>/<label>"`
2055 /// (one device).
2056 pub target: String,
2057 /// Treat this as a USER-KEY rotation instead: remove the person but leave their devices
2058 /// un-revoked, so the same hardware re-enrolls under a fresh user key and is re-approved with
2059 /// the same `user_id`.
2060 ///
2061 /// The distinction is the point — a departure must revoke the devices, a rotation must not.
2062 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2063 pub user_key: bool,
2064}
2065
2066/// Result of [`Request::OrgRevoke`] (#66).
2067#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2068pub struct OrgRevokeResult {
2069 pub target: String,
2070 /// `"person"` | `"device"` | `"user-key-rotation"` — which grammar the target resolved to, so a
2071 /// caller can confirm the destructive reading it got was the one it meant.
2072 pub mode: String,
2073 pub org_id: String,
2074 pub serial: u64,
2075 /// Live sessions severed by the install. Revocation is IMMEDIATE (#54): a cut device's existing
2076 /// connections are closed, not left to drain.
2077 #[serde(default)]
2078 pub severed: u32,
2079}
2080
2081/// Result of [`Request::RosterMembers`]: the org's membership as an embedder renders it (#93).
2082///
2083/// Distinct from `status.presence` in what it enumerates: that lists reachable DEVICES and omits a
2084/// person entirely when none of their devices is up. This lists every person the roster carries,
2085/// online or not — a member list, not a presence list — with `online` per device so a UI can draw
2086/// both from one read.
2087///
2088/// ADVISORY. Every field here is display or authoring input; nothing in it is an authorization
2089/// answer. The gate reads the signed roster.
2090#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2091pub struct RosterMembersResult {
2092 /// The org's declared group namespace, in document order — the set an `allow` entry may name.
2093 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2094 pub groups: Vec<String>,
2095 /// Every person in the roster, ordered by `user_id` for a stable display.
2096 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2097 pub users: Vec<RosterMember>,
2098}
2099
2100/// One person in a [`RosterMembersResult`] (#93).
2101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2102pub struct RosterMember {
2103 /// The stable authorization handle — what an `allow` entry names.
2104 pub user_id: String,
2105 /// The human name, for display. Empty if the roster's own field is.
2106 #[serde(default, skip_serializing_if = "String::is_empty")]
2107 pub display_name: String,
2108 /// The groups this person belongs to, each declared in [`RosterMembersResult::groups`].
2109 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2110 pub groups: Vec<String>,
2111 /// Their ACTIVE devices — revoked ones are absent, exactly as the gate sees it. Ordered
2112 /// primary-before-mirror, then by label.
2113 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2114 pub devices: Vec<RosterMemberDevice>,
2115}
2116
2117/// One device of a [`RosterMember`] (#93).
2118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2119pub struct RosterMemberDevice {
2120 /// The device's human label.
2121 pub label: String,
2122 /// `"primary"` | `"mirror"` — the advisory dial-ordering hint, never a security property.
2123 pub role: String,
2124 /// The device's stable `eid:` principal — the SAME vocabulary [`PeerInfo::principal`] carries,
2125 /// and what a per-device `allow` entry names.
2126 ///
2127 /// Included where `PresencePeer` deliberately omits it, because this surface exists to be
2128 /// ACTED on: an embedder granting or revoking one device of a person needs the handle to name
2129 /// it, and the alternative is a nickname that does not exist in roster mode.
2130 pub principal: String,
2131 /// Whether the device has a live presence heartbeat. Advisory — absence never blocks a dial,
2132 /// and never removes a dial candidate.
2133 pub online: bool,
2134}
2135
2136/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
2137/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
2138/// carve-out as the pairing invite line). Additive-only.
2139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2140pub struct BlobPublishResult {
2141 pub ticket: String,
2142 pub hash: String, // bare blake3 hex
2143}
2144
2145/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
2146/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
2147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2148pub struct ScopeInfo {
2149 pub name: String,
2150 pub hashes: Vec<String>,
2151 pub grants: Vec<String>,
2152 /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
2153 /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
2154 /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
2155 /// pre-`api_minor` 19 client sees exactly what it saw before.
2156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2157 pub withdrawn: Vec<String>,
2158 /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
2159 #[serde(default)]
2160 pub hash_count: usize,
2161 /// Size of `grants`.
2162 #[serde(default)]
2163 pub grant_count: usize,
2164 /// Size of `withdrawn`.
2165 #[serde(default)]
2166 pub withdrawn_count: usize,
2167}
2168
2169/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
2170/// matters because the verb took no params before `api_minor` 20.
2171///
2172/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
2173/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
2174/// The control surface carries no strike bound, so the connection survives — but the caller gets an
2175/// opaque failure with no way to page, which is unusable rather than merely large.
2176#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2177#[serde(default, deny_unknown_fields)]
2178pub struct BlobListParams {
2179 /// EXACT scope name, never a prefix.
2180 pub scope: Option<String>,
2181 /// Only scopes containing this hash; the rendering you send is normalized first.
2182 pub hash: Option<String>,
2183 pub limit: Option<usize>,
2184 pub offset: Option<usize>,
2185 /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
2186 pub counts_only: bool,
2187}
2188
2189/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
2190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2191pub struct BlobScopeList {
2192 pub scopes: Vec<ScopeInfo>,
2193 /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
2194 /// complete answer from a clipped one.
2195 #[serde(default)]
2196 pub total: usize,
2197 /// True when more scopes matched than were returned. Page with `offset` to see the rest.
2198 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2199 pub truncated: bool,
2200}
2201
2202/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
2203/// Additive-only.
2204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2205pub struct BlobFetchResult {
2206 pub hash: String,
2207 pub bytes_len: u64,
2208}
2209
2210/// Result of [`Request::BlobFetchCancel`] (#172).
2211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2212pub struct BlobFetchCancelResult {
2213 /// True when a fetch of that hash was in flight and has been told to stop. False is NOT an
2214 /// error — it means nothing was fetching that blob here, which is also what a caller sees when
2215 /// it races a fetch that just finished.
2216 pub cancelled: bool,
2217}
2218
2219/// Params of [`Request::AuditPrune`] (#88): delete monthly audit files STRICTLY older than
2220/// `before` (that month itself is kept — delete-before, not delete-including). Rejects unknown
2221/// fields, and the daemon validates the `YYYY-MM` shape up front: a malformed month errors
2222/// loudly instead of string-comparing to nothing and reporting a clean no-op.
2223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2224#[serde(deny_unknown_fields)]
2225pub struct AuditPruneParams {
2226 /// A zero-padded `YYYY-MM` month key.
2227 pub before: String,
2228}
2229
2230/// Result of [`Request::AuditPrune`]: the month keys actually deleted, ascending. Empty when
2231/// nothing was older than `before` (idempotent).
2232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2233pub struct AuditPruneResult {
2234 pub deleted_months: Vec<String>,
2235}
2236
2237/// Params of [`Request::AuditList`] (#88). All filters optional and AND-combined; every field
2238/// absent lists everything (paged). Rejects unknown fields — a typo'd filter that silently
2239/// matched everything would let a "what do you hold about X" answer overclaim.
2240#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2241#[serde(deny_unknown_fields)]
2242pub struct AuditListParams {
2243 /// Inclusive `YYYY-MM` lower bound — month-file granularity (the rotation unit), so an
2244 /// out-of-range month is skipped without parsing it.
2245 #[serde(default, skip_serializing_if = "Option::is_none")]
2246 pub since: Option<String>,
2247 /// Inclusive `YYYY-MM` upper bound.
2248 #[serde(default, skip_serializing_if = "Option::is_none")]
2249 pub until: Option<String>,
2250 /// One of the wire kind strings (`session_open` / `session_close` / `request` /
2251 /// `blob_fetch` / `trust`). An UNKNOWN string is an error, never silently-all.
2252 #[serde(default, skip_serializing_if = "Option::is_none")]
2253 pub kind: Option<String>,
2254 /// The record's attributed peer nickname.
2255 #[serde(default, skip_serializing_if = "Option::is_none")]
2256 pub peer: Option<String>,
2257 /// Page size, default 500, clamped to 1000 — a month file can be arbitrarily large and the
2258 /// response is ONE JSON frame under the transport's frame cap, so the clamp is load-bearing
2259 /// (the same lesson as `blob_list`'s, minor 20).
2260 #[serde(default, skip_serializing_if = "Option::is_none")]
2261 pub limit: Option<u32>,
2262 /// Records to skip (after filtering), for paging.
2263 #[serde(default, skip_serializing_if = "Option::is_none")]
2264 pub offset: Option<u32>,
2265}
2266
2267/// Result of [`Request::AuditList`]: one page of matching records in chronological order
2268/// (oldest month first, in-file order within a month), plus the TOTAL match count so a caller
2269/// can page without a second counting call. `total` counts ALL matches, not the page.
2270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2271pub struct AuditListResult {
2272 pub records: Vec<AuditRecord>,
2273 pub total: u64,
2274}
2275
2276/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
2277/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
2278/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
2279/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
2280/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
2281/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
2282///
2283/// Additive-only: any future field MUST land as
2284/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
2285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2286pub struct AuditSummaryResult {
2287 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
2288 /// peer to attribute) but IS in `total_sessions`.
2289 pub per_peer: Vec<(String, u64)>,
2290 /// Sessions opened per registered service name.
2291 pub per_service: Vec<(String, u64)>,
2292 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
2293 #[serde(default)]
2294 pub total_sessions: u64,
2295}
2296
2297/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
2298/// (the ONE pairing artifact deliberately carved out of the
2299/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
2300/// absolute expiry in epoch seconds (≤ now + 24h).
2301///
2302/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
2303/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
2304/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
2305/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
2306/// ceremony" note in `docs/local-protocol.md` (#35).
2307///
2308/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
2309/// so older payloads still deserialize.
2310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2311pub struct InviteResult {
2312 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
2313 pub invite_line: String,
2314 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
2315 pub expires_at_epoch: u64,
2316 /// How many redemptions this invite has left (#87) — **the value actually applied**, after the
2317 /// [`MAX_INVITE_USES`] clamp. `1` for an ordinary single-use invite.
2318 ///
2319 /// Reported so a caller that asked for more than the cap is told what it got rather than
2320 /// discovering it when the fourth colleague fails. Additive: `#[serde(default = "one")]`, so a
2321 /// response from an older daemon reads as single-use. `api_minor >= 35`.
2322 #[serde(default = "one_use")]
2323 pub uses_remaining: u32,
2324}
2325
2326/// The serde default for a `uses_remaining` field absent from an older payload or invite line: one
2327/// redemption, which is what every pre-#87 invite is.
2328pub fn one_use() -> u32 {
2329 1
2330}
2331
2332/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
2333/// redeemer's local name for the new peer) plus the display-only short authentication
2334/// code (SAS) — a few words the human reads aloud to a second channel to
2335/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
2336/// artifact (like the invite line), NOT a transport-vocabulary leak.
2337///
2338/// Additive-only: any future field MUST land as
2339/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
2340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2341pub struct PairResult {
2342 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
2343 pub peer_nickname: String,
2344 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
2345 /// sides for the out-of-band human check. Never sent on the wire, never checked
2346 /// programmatically.
2347 pub sas_code: String,
2348 /// TRUE when this redemption was a SELF-ENROLLMENT (#86): you are now another device of the
2349 /// inviter's person, not their peer. No peer row was written and nothing was granted.
2350 ///
2351 /// Reported so a caller can tell the two outcomes apart without inspecting its own store.
2352 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2353 pub enrolled_as_self: bool,
2354 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
2355 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
2356 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
2357 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
2358 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
2359 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2360 pub services: Vec<String>,
2361 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
2362 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
2363 #[serde(default, skip_serializing_if = "Option::is_none")]
2364 pub app_label: Option<String>,
2365 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
2366 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
2367 /// can align with its own — and the same value it may later pass to `open_session` to dial
2368 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
2369 /// binding (a legacy/keyless peer). Additive.
2370 #[serde(default, skip_serializing_if = "Option::is_none")]
2371 pub peer_user_id: Option<String>,
2372}
2373
2374/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
2375/// top of the base record schema: it removes no field and makes the JSONL self-describing so
2376/// a consumer can filter by class without guessing from which optional fields are present.
2377#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2378#[serde(rename_all = "snake_case")]
2379pub enum AuditKind {
2380 /// A mesh session opened (a backend was selected for an authenticated peer).
2381 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
2382 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
2383 SessionOpen,
2384 /// A mesh session closed (the backend returned / the session tore down).
2385 SessionClose,
2386 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
2387 Request,
2388 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
2389 BlobFetch,
2390 /// A trust mutation (pair, unpair, roster install/swap, revoke).
2391 Trust,
2392}
2393
2394/// One audit record — the union of the event classes, and the `record` payload of a
2395/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
2396/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
2397/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
2398/// `bytes_out`).
2399///
2400/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
2401/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
2402/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
2403#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2404pub struct AuditRecord {
2405 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
2406 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
2407 pub ts: String,
2408 pub kind: AuditKind,
2409 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
2410 /// local-only events with no remote peer (a manual roster install).
2411 #[serde(skip_serializing_if = "Option::is_none")]
2412 pub peer: Option<String>,
2413 #[serde(skip_serializing_if = "Option::is_none")]
2414 pub service: Option<String>,
2415 #[serde(skip_serializing_if = "Option::is_none")]
2416 pub method: Option<String>,
2417 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
2418 #[serde(skip_serializing_if = "Option::is_none")]
2419 pub tool: Option<String>,
2420 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
2421 #[serde(skip_serializing_if = "Option::is_none")]
2422 pub args_hash: Option<String>,
2423 /// Byte COUNT of the response sent back to the peer — a count, never the content.
2424 #[serde(skip_serializing_if = "Option::is_none")]
2425 pub bytes_out: Option<u64>,
2426 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
2427 #[serde(skip_serializing_if = "Option::is_none")]
2428 pub status: Option<String>,
2429 #[serde(skip_serializing_if = "Option::is_none")]
2430 pub latency_ms: Option<u64>,
2431 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
2432 #[serde(skip_serializing_if = "Option::is_none")]
2433 pub event: Option<String>,
2434 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
2435 /// nickname or `org/serial` (`Trust`).
2436 #[serde(skip_serializing_if = "Option::is_none")]
2437 pub target: Option<String>,
2438 /// The subject's STABLE principal, from the same gate resolution that produced `peer`
2439 /// (#57, `api_minor >= 29`). `peer` is a display name and collides — two devices under one
2440 /// nickname were indistinguishable in the stream and the on-disk log. Same argument and
2441 /// shape as `PeerInfo` (#41), `PeerReachability` (#42), and `ActiveSession` (#73).
2442 ///
2443 /// TWO NAMESPACES, deliberately: session/request/blob records attribute the DEVICE
2444 /// (`eid:<hex>`, like `ActiveSession` — the exact authenticated endpoint), while the trust
2445 /// `pair` record carries the value the grant appended to the allow (`b64u:<pk>` when the
2446 /// device presented a user binding, else `eid:`, #38). Joining a bound peer's sessions to
2447 /// its allow entry therefore goes through the `status` peers list (which carries BOTH the
2448 /// device principal and the `user_id`), not string equality on this field alone.
2449 ///
2450 /// **`peer_introduce` (#65) is the one exception, deliberately:** it carries the ENDORSER, not
2451 /// the subject. An introduction's whole security question is *who vouched for this peer*, and
2452 /// the subject is already in `target`. So `audit_list --peer <endorser>` finds the
2453 /// introductions that endorser caused, which is the query an operator actually runs.
2454 ///
2455 /// Deliberately absent on: `unpair` (may tear down several devices — no single subject),
2456 /// `roster_install` (purely local), and the failed-outbound-dial session record (our own
2457 /// dial, not a gate-resolved caller). Absent on every record written before 0.24.0.
2458 #[serde(default, skip_serializing_if = "Option::is_none")]
2459 pub principal: Option<String>,
2460}
2461
2462impl AuditRecord {
2463 fn base(ts: String, kind: AuditKind) -> Self {
2464 Self {
2465 ts,
2466 kind,
2467 peer: None,
2468 service: None,
2469 method: None,
2470 tool: None,
2471 args_hash: None,
2472 bytes_out: None,
2473 status: None,
2474 latency_ms: None,
2475 event: None,
2476 target: None,
2477 principal: None,
2478 }
2479 }
2480
2481 /// `principal` is an EXPLICIT parameter on every constructor (#57, kept from the original
2482 /// #72 design): a builder would let a call site silently omit it and reintroduce the
2483 /// collapsed-identity bug for that one event class. Pass `None` only for the documented
2484 /// no-single-subject records (see the field doc).
2485 pub fn session_open(
2486 ts: String,
2487 peer: Option<String>,
2488 service: String,
2489 principal: Option<String>,
2490 ) -> Self {
2491 let mut r = Self::base(ts, AuditKind::SessionOpen);
2492 r.peer = peer;
2493 r.service = Some(service);
2494 r.principal = principal;
2495 r
2496 }
2497
2498 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
2499 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
2500 /// reaches no backend and so is never audited by the far side's session guard — without a
2501 /// dedicated constructor. DRY: reuses the existing optional `status` field.
2502 pub fn with_status(mut self, status: &str) -> Self {
2503 self.status = Some(status.into());
2504 self
2505 }
2506
2507 pub fn session_close(
2508 ts: String,
2509 peer: Option<String>,
2510 service: String,
2511 principal: Option<String>,
2512 ) -> Self {
2513 let mut r = Self::base(ts, AuditKind::SessionClose);
2514 r.peer = peer;
2515 r.service = Some(service);
2516 r.principal = principal;
2517 r
2518 }
2519
2520 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
2521 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
2522 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
2523 #[allow(clippy::too_many_arguments)]
2524 pub fn proxied_request(
2525 ts: String,
2526 peer: Option<String>,
2527 service: String,
2528 method: String,
2529 tool: Option<String>,
2530 args_hash: String,
2531 bytes_out: u64,
2532 status: String,
2533 latency_ms: u64,
2534 principal: Option<String>,
2535 ) -> Self {
2536 let mut r = Self::base(ts, AuditKind::Request);
2537 r.peer = peer;
2538 r.service = Some(service);
2539 r.method = Some(method);
2540 r.tool = tool;
2541 r.args_hash = Some(args_hash);
2542 r.bytes_out = Some(bytes_out);
2543 r.status = Some(status);
2544 r.latency_ms = Some(latency_ms);
2545 r.principal = principal;
2546 r
2547 }
2548
2549 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
2550 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
2551 pub fn proxied_notification(
2552 ts: String,
2553 peer: Option<String>,
2554 service: String,
2555 method: String,
2556 tool: Option<String>,
2557 args_hash: String,
2558 principal: Option<String>,
2559 ) -> Self {
2560 let mut r = Self::base(ts, AuditKind::Request);
2561 r.peer = peer;
2562 r.service = Some(service);
2563 r.method = Some(method);
2564 r.tool = tool;
2565 r.args_hash = Some(args_hash);
2566 r.principal = principal;
2567 r
2568 }
2569
2570 pub fn blob_fetch(
2571 ts: String,
2572 peer: Option<String>,
2573 hash: String,
2574 status: String,
2575 principal: Option<String>,
2576 ) -> Self {
2577 let mut r = Self::base(ts, AuditKind::BlobFetch);
2578 r.peer = peer;
2579 r.target = Some(hash);
2580 r.status = Some(status);
2581 r.principal = principal;
2582 r
2583 }
2584
2585 pub fn trust(
2586 ts: String,
2587 event: String,
2588 target: Option<String>,
2589 principal: Option<String>,
2590 ) -> Self {
2591 let mut r = Self::base(ts, AuditKind::Trust);
2592 r.event = Some(event);
2593 r.target = target;
2594 r.principal = principal;
2595 r
2596 }
2597}
2598
2599/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
2600/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
2601#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2602pub struct ActiveSession {
2603 pub peer: String,
2604 pub service: String,
2605 pub opened_at: i64,
2606 /// The caller's STABLE device principal, `eid:<hex>` (#73).
2607 ///
2608 /// `peer` is a display nickname and collides: two devices under one nickname, or two contacts
2609 /// sharing a display name, are indistinguishable in the live-session view. So "who is using my
2610 /// service right now", per-peer session counts, and any UI that lets a user act on a live
2611 /// session (revoke, disconnect, inspect) were all keyed on a collidable string.
2612 ///
2613 /// Same argument and same shape as [`PeerInfo`] (#41) and [`PeerReachability`] (#42).
2614 /// Nicknames NEVER authorize; this is the value to key on.
2615 ///
2616 /// **Snapshot only, for now.** `ActiveSession` appears in [`StreamFrame::Snapshot`] — there is
2617 /// no `active_sessions` on `StatusResult`. A client that keeps its view current by applying
2618 /// subsequent `session_open`/`session_close` events still has a collision problem: those are
2619 /// [`AuditRecord`]s and carry no principal (#57, unmerged). So the snapshot distinguishes two
2620 /// same-nickname devices and the next `session_close` for that nickname does not say which row
2621 /// to drop. Re-subscribe for an authoritative view until #57 lands.
2622 ///
2623 /// Always present for a real row — `Option` only so an older client round-trips. Additive.
2624 #[serde(default, skip_serializing_if = "Option::is_none")]
2625 pub principal: Option<String>,
2626}
2627
2628/// Which side of an app-blob transfer a [`StreamFrame::BlobTransfer`] describes (#82).
2629#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2630#[serde(rename_all = "snake_case")]
2631pub enum BlobDirection {
2632 /// We are SERVING bytes to a peer that dialed our app-blob ALPN.
2633 Serve,
2634 /// We are FETCHING bytes from a peer, via `blob_fetch`.
2635 Fetch,
2636}
2637
2638/// Where an app-blob transfer is in its life (#82).
2639#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2640#[serde(rename_all = "snake_case")]
2641pub enum BlobTransferState {
2642 /// The transfer began; `bytes_total` is known from here on.
2643 Started,
2644 /// Bytes advanced. COALESCED — see [`StreamFrame::BlobTransfer`].
2645 Progress,
2646 /// Finished successfully. Carries the FINAL byte count.
2647 Completed,
2648 /// Ended without completing (peer went away, refused, or the store errored).
2649 Aborted,
2650}
2651
2652/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
2653/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
2654/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
2655/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
2656/// them (see `docs/local-protocol.md` "Live event stream").
2657///
2658/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
2659/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
2660/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
2661/// `_ =>` arm and later additions are additive for Rust.
2662///
2663/// **They are NOT additive for JSON, and this line claimed they were until 1.55.** The enum is
2664/// `#[serde(tag = "type")]` with no catch-all variant, so an unrecognised tag is a hard
2665/// deserialization error: [`StreamSubscription::next`](crate::StreamSubscription::next) surfaces a
2666/// newer daemon's frame as [`ClientError::Malformed`](crate::ClientError::Malformed) and a consumer
2667/// that propagates it loses the whole stream. `#[non_exhaustive]` is a Rust-`match` property and
2668/// does nothing for serde. A consumer that must survive a daemon newer than its `mcpmesh-local-api`
2669/// reads raw frames via [`ControlClient::open_stream`](crate::ControlClient::open_stream) and
2670/// ignores tags it does not know — that is the only forward-compatible path, and the crates ship in
2671/// lockstep precisely because of this.
2672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2673#[serde(tag = "type", rename_all = "snake_case")]
2674#[non_exhaustive]
2675pub enum StreamFrame {
2676 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
2677 /// reachability) so a fresh subscriber renders immediately without replaying history.
2678 Snapshot {
2679 active_sessions: Vec<ActiveSession>,
2680 reachability: Vec<PeerReachability>,
2681 /// THIS node's own reachability posture (#90), so a fresh subscriber renders it without
2682 /// a `status` poll. `None` in mesh-less control-only mode. Additive: default +
2683 /// skip-if-none so an older payload round-trips.
2684 #[serde(default, skip_serializing_if = "Option::is_none")]
2685 self_network: Option<SelfNetwork>,
2686 },
2687 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
2688 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
2689 /// `Box`, so the wire shape is the record's fields verbatim.
2690 Event { record: Box<AuditRecord> },
2691 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
2692 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
2693 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
2694 /// it returns, rather than on the next poll tick.
2695 ///
2696 /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
2697 /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
2698 /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
2699 /// `0` — the observation just completed.
2700 ///
2701 /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
2702 /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
2703 /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
2704 /// frames were impossible was reading a stale guarantee.
2705 ///
2706 /// Two producers, as of API 1.22 — and since 1.30 `source` says WHICH ONE, so the distinction
2707 /// is readable rather than inferred:
2708 ///
2709 /// - [`ReachabilitySource::Probe`] — a probe completing (`status`/`subscribe` refreshing a
2710 /// stale entry). It describes a throwaway dial, not anyone's live connection.
2711 /// - [`ReachabilitySource::Session`] — a live session whose selected path changed under it
2712 /// (#92 item 2). A claim about the link in use.
2713 ///
2714 /// The second producer is why `path` is trustworthy for a long-lived session: a session that
2715 /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
2716 /// mislabelled until something probes. `path` is a truth claim about where user data went, so
2717 /// `Unknown` means "we do not know" and must never be rendered as private.
2718 ///
2719 /// **`rtt_ms` is not a discriminator, and never was** (#150). Until 1.30 this doc said a
2720 /// session-sourced frame carries `rtt_ms: None` — true only of a FIRST observation, where no
2721 /// round trip was measured and none is invented. A session-sourced frame for an
2722 /// already-probed peer carries that probe's `rtt_ms: Some(..)`, because the path watcher
2723 /// deliberately leaves `rtt_ms`/`meta`/`probed_at` alone (refreshing them would stamp a stale
2724 /// RTT as fresh and suppress the corrective probe — #92 review). That is the common case for a
2725 /// peer probed at pairing time and then watched through a long call. Read `source`.
2726 Reachability {
2727 peer: PeerReachability,
2728 /// Which producer emitted this frame (#150). `api_minor >= 30`.
2729 ///
2730 /// Additive: `#[serde(default)]`, landing on [`ReachabilitySource::Unknown`] — NOT on
2731 /// `Probe`. A daemon at `api_minor` 22–29 already has both producers, so an absent field
2732 /// genuinely does not say which one ran; defaulting to `Probe` would assert the wrong
2733 /// producer for every session-sourced frame such a daemon emits, which is the exact
2734 /// ambiguity this field exists to remove.
2735 #[serde(default)]
2736 source: ReachabilitySource,
2737 },
2738 /// THIS node's own network posture CHANGED (#90): `online` flipped, the home relay moved,
2739 /// or a relay's connection state changed — pushed so an embedder learns "you just went
2740 /// unreachable" the moment it happens instead of on a poll tick, and so #53's `set_relays`
2741 /// finally has a signal telling someone to use it. `direct_addrs` drift alone does not
2742 /// emit (address churn is chatty and not a decision point; it rides the next frame).
2743 /// `api_minor >= 28`.
2744 SelfNetwork { self_network: SelfNetwork },
2745 /// This machine was SUSPENDED and has just resumed (#167 ask 2) — a closed laptop lid, a sleep,
2746 /// a hibernate. `api_minor >= 55`.
2747 ///
2748 /// The signal an embedder holding long-lived sessions actually needs. While a machine is
2749 /// suspended it sends nothing, so the *peer's* idle timer runs out and tears the connection down
2750 /// before the lid is even reopened; `keep_alive_secs` cannot help, because a suspended process
2751 /// emits no PINGs. Without this frame the first thing an app learns is a failed send, which is
2752 /// the worst possible moment to find out. With it, the app can tear down and re-dial
2753 /// deliberately.
2754 ///
2755 /// **Detected as clock skew, not guessed.** Rust's `Instant` is `CLOCK_MONOTONIC` on Linux and
2756 /// `CLOCK_UPTIME_RAW` on Apple targets, and neither advances across a suspend while the wall
2757 /// clock does. A tick where the wall clock outran the monotonic clock by more than the threshold is a
2758 /// suspend; a tick where BOTH ran long is a starved runtime and emits nothing. That distinction
2759 /// is deliberate — a signal that fired under load would train consumers to ignore it.
2760 ///
2761 /// **It names no session.** The daemon cannot know which of an embedder's sessions survived —
2762 /// a short suspend may well leave one intact. It means "this machine was away for N seconds;
2763 /// re-check what you hold".
2764 ///
2765 /// **A forward wall-clock STEP also emits, and cannot be told apart from a sleep.** A board with
2766 /// no RTC that boots with a bogus epoch and is then stepped months forward by NTP produces a
2767 /// frame claiming a multi-year suspend. Read `suspended_secs` as "wall time ran this much
2768 /// further than this process did", which is what is actually measured; the frame's advice
2769 /// survives either cause, but the number is not a measurement of sleep alone. Distinguishing
2770 /// them needs a continuous clock (`CLOCK_BOOTTIME` / `mach_continuous_time`), which is a
2771 /// per-platform dependency this does not take.
2772 ///
2773 /// Not retroactive, and — unlike the other transitions — with **nothing in `Snapshot` to
2774 /// recover it from.** [`Reachability`](StreamFrame::Reachability) and
2775 /// [`SelfNetwork`](StreamFrame::SelfNetwork) missed frames are recoverable because `Snapshot`
2776 /// carries `reachability` and `self_network`; there is no resume field, because "was this
2777 /// machine recently asleep" is not a state the daemon holds. A subscriber that attaches after a
2778 /// wake cannot learn one happened. If you reconnect, assume you missed events and re-check what
2779 /// you hold — the same advice this frame carries.
2780 Resumed {
2781 /// How long the machine was away, in seconds — the number that decides whether to re-dial
2782 /// everything or nothing. It is the wall-clock/monotonic skew, so it measures the suspend
2783 /// itself and not the time since the last frame.
2784 suspended_secs: u64,
2785 /// Wall-clock epoch seconds at which the resume was DETECTED (up to one tick after the
2786 /// machine actually woke).
2787 at_epoch: i64,
2788 },
2789 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
2790 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
2791 Lagged { dropped: u64 },
2792 /// An app-blob transfer advanced (#82). Emitted on BOTH sides: `Serve` while we send bytes to
2793 /// a peer, `Fetch` while `blob_fetch` pulls them.
2794 ///
2795 /// **`Progress` is COALESCED, deliberately.** iroh-blobs reports progress per ~16 KiB chunk, so
2796 /// a 4 GiB transfer would push ~262k frames through a bounded ring and every subscriber would
2797 /// see `Lagged` — losing the audit events that share it. A frame is emitted on `Started`, on
2798 /// `Completed`/`Aborted`, and on `Progress` only after at least `max(1 MiB, total/100)` more
2799 /// bytes, so a transfer costs at most ~102 frames whatever its size.
2800 ///
2801 /// **Do not treat the last `Progress` as the total** — the final stride is usually skipped.
2802 /// `Completed` carries the final `bytes_done`.
2803 BlobTransfer {
2804 direction: BlobDirection,
2805 /// The blob's hash, hex.
2806 hash: String,
2807 bytes_done: u64,
2808 /// Known from `Started` onward; `None` only if the size was never reported.
2809 #[serde(default, skip_serializing_if = "Option::is_none")]
2810 bytes_total: Option<u64>,
2811 state: BlobTransferState,
2812 /// SERVING side only: the STABLE `eid:` device principal we are serving (#38 — never a
2813 /// display nickname). Always `eid:<hex>`: this comes from the authenticated endpoint, so it
2814 /// is NOT the same namespace as a grant written as a user_id or roster name. Absent when fetching, where the counterparty is named
2815 /// by the ticket rather than by a resolved identity.
2816 #[serde(default, skip_serializing_if = "Option::is_none")]
2817 peer: Option<String>,
2818 },
2819}
2820
2821/// Extract the `method` tag from a raw request value without deserializing the whole
2822/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
2823/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
2824/// methods (adjacent tagging rejects `params:{}` on unit variants).
2825pub fn method_of(v: &serde_json::Value) -> Option<&str> {
2826 v.get("method").and_then(serde_json::Value::as_str)
2827}
2828
2829/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
2830/// Config→BackendSpec is a hand-written match, not a serde passthrough.
2831#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2832#[serde(rename_all = "snake_case")]
2833pub enum BackendSpec {
2834 Run {
2835 cmd: Vec<String>,
2836 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
2837 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
2838 /// these (identity is not spoofable by a service definition). Default empty.
2839 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2840 env: BTreeMap<String, String>,
2841 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
2842 #[serde(default, skip_serializing_if = "Option::is_none")]
2843 cwd: Option<String>,
2844 },
2845 Socket {
2846 path: String,
2847 },
2848}
2849
2850/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
2851/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
2852/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
2853/// `{}` (success) for an unknown name, which silently included every ephemeral service.
2854pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
2855/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
2856/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
2857pub const ERR_NO_SUCH_BLOB: i64 = -32041;
2858/// The blob was deliberately withdrawn from this scope (#107). Distinct from
2859/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
2860/// purpose — `blob_publish` from the file if the re-share is intended".
2861pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
2862/// `pair` was refused because the redeemer's nickname is already held by a DIFFERENT paired peer
2863/// (#87), so an embedder can branch on the one refusal that has a self-service remedy — rename and
2864/// redeem the same invite again — without reading the prose (#147).
2865///
2866/// Reading the prose was the only option before this code, and it does not survive translation: the
2867/// message is generated on the INVITER's side and travels to the redeemer, so the embedder that
2868/// DISPLAYS it cannot rewrite it into its own vocabulary except by substring-matching our copy.
2869/// Branch on this and write your own sentence naming your own rename affordance.
2870///
2871/// Deliberately narrow. It rides ONLY this refusal, which is sent exclusively to a caller that
2872/// proved possession of a live invite secret. The generic refusal keeps `-32000` and its opaque
2873/// reason: distinguishing unknown-vs-expired-vs-wrong-secret would be a redemption oracle.
2874pub const ERR_NICKNAME_TAKEN: i64 = -32043;
2875
2876/// The invite line's own `expires_at_epoch` has passed (#159). Decided LOCALLY, before dialing —
2877/// this says nothing about the inviter's state. Remedy: ask for a fresh invite.
2878pub const ERR_INVITE_EXPIRED: i64 = -32044;
2879
2880/// The inviter has **no outstanding invite at all** — its accept gate fast-closed the dial (#159).
2881///
2882/// This is as close to "expired or already used" as we can safely get, and the distinction matters:
2883/// it is a fact about the INVITER, not about the secret presented. Answering per-secret would be a
2884/// redemption oracle — a prober would learn which guessed secrets were ever real — which is why
2885/// [`ERR_INVITE_REFUSED`] stays deliberately undifferentiated. Remedy: ask for a fresh invite.
2886pub const ERR_INVITE_NOT_LIVE: i64 = -32045;
2887
2888/// The inviter's address could not be dialed at all (#159) — offline, asleep, or unroutable.
2889/// Remedy: check they are running, then retry the same invite; it is untouched.
2890pub const ERR_INVITER_UNREACHABLE: i64 = -32046;
2891
2892/// **The address-swap defense fired**: the TLS-authenticated peer is not the endpoint the invite
2893/// names (#159).
2894///
2895/// The one refusal here that must NOT be rendered as "try again". Something answered in place of
2896/// the machine the invite identifies — a substituted address, or a forged invite. An embedder that
2897/// treats every pairing failure as a friendly retry papers over exactly the attack this check
2898/// exists to catch. Remedy: do not retry; get the invite again through a channel you trust.
2899pub const ERR_INVITER_MISMATCH: i64 = -32047;
2900
2901/// The invite asks to be called a name this node already uses for a DIFFERENT peer (#159).
2902///
2903/// The redeemer-side mirror of [`ERR_NICKNAME_TAKEN`], and a distinct condition: that one is the
2904/// inviter refusing the redeemer's name, this is the redeemer refusing the inviter's suggestion.
2905/// Nothing is granted either way — a name confers no access (#38) — so this protects this node's
2906/// own display and routing clarity. Remedy: ask for an invite suggesting a different name.
2907pub const ERR_INVITE_NAME_CONFLICT: i64 = -32048;
2908
2909/// The inviter refused, and the cause is **deliberately withheld** (#159).
2910///
2911/// Unknown secret, expired secret, and wrong secret are one answer on purpose: telling them apart
2912/// is a redemption oracle. The code carries exactly as much as the prose already did — "that invite
2913/// did not work" — so a consumer can branch without parsing, and without learning anything a
2914/// prober could use. Remedy: ask for a fresh invite.
2915pub const ERR_INVITE_REFUSED: i64 = -32049;
2916
2917/// The request was stopped on purpose before it finished (#172) — today, a `blob_fetch` that
2918/// [`Request::BlobFetchCancel`] tripped.
2919///
2920/// A cancelled request still ANSWERS. Cancellation is cooperative rather than a task abort
2921/// precisely so this code can be delivered: an aborted task returns nothing, and the caller waits
2922/// forever on work that already stopped. Distinct from `-32000` because it is not a failure — the
2923/// caller (or its user) asked for it. Remedy: none; retry the fetch if the cancel was a mistake.
2924///
2925/// **What it does not promise:** partial chunks already streamed into the blob store stay there,
2926/// unlisted and unreclaimable, exactly as they do when a fetch fails. That is #80's reclaim gap,
2927/// unchanged by cancellation.
2928pub const ERR_CANCELLED: i64 = -32050;
2929
2930/// This control connection already has [`MAX_INFLIGHT`] requests running, so this one was refused
2931/// without being started (#172).
2932///
2933/// **Retryable, and cheap to retry** — retry after any response lands, or spread the load over a
2934/// second control connection. It is refused rather than queued deliberately: a queue is invisible
2935/// backpressure that a caller cannot tell apart from a slow daemon, and waiting for a permit inside
2936/// the read loop would reintroduce the head-of-line blocking concurrent dispatch exists to remove.
2937///
2938/// Not a security boundary — the control socket is the daemon owner's. It bounds the work one
2939/// connection can have outstanding so a buggy client cannot spawn unboundedly.
2940pub const ERR_TOO_MANY_INFLIGHT: i64 = -32051;
2941
2942/// The invite line is a SELF-ENROLLMENT (`mcpmesh-enroll:`) and the caller did not offer that
2943/// ceremony — [`PairParams::allow_self_enroll`] was unset (#178).
2944///
2945/// Decided from the line in hand, BEFORE any dial: nothing was contacted, no secret was revealed,
2946/// and the invite is untouched. Like [`ERR_INVITE_EXPIRED`] it therefore reveals nothing about the
2947/// inviter and is safe to name precisely.
2948///
2949/// Distinct from [`ERR_INVITE_REFUSED`] in the direction it points: that one is the inviter turning
2950/// US down, this one is US declining a ceremony we were never asked to run. Remedy: if the person
2951/// meant to add another of their OWN devices, offer that explicitly and retry the SAME line with
2952/// `allow_self_enroll`; otherwise they pasted the wrong link and want an ordinary
2953/// `mcpmesh-invite:` one.
2954pub const ERR_SELF_ENROLL_NOT_OFFERED: i64 = -32052;
2955
2956/// `service_allow_grant` — the principal is REVOKED on this node, so the grant was refused before
2957/// anything was written (#212, `api_minor >= 60`). Also `peer_introduce` (#218, `api_minor >= 61`)
2958/// when the SUBJECT proves a `user_id` this node has revoked: the row would be refused on sight.
2959///
2960/// Admission runs two gates: the revocation table first (`peer_revoke`), then the service's
2961/// `allow`. A grant to a revoked principal used to succeed and write a real `allow` entry that the
2962/// first gate would never let a session reach — the caller was told "granted" and `status`
2963/// confirmed it, while every session from that peer was refused. Now the write path consults the
2964/// same table admission does, and answers this instead of `{}`.
2965///
2966/// "Revoked" here means what admission means by it, read live: an `eid:` that `peer_revoke` marked
2967/// dead (locally or by a signed import, or by the installed roster), or a `b64u:` identity that
2968/// `peer_revoke` revoked — every row carrying that `user_id` is refused, whatever the endpoint
2969/// table says about the device (#218). Remedy: `peer_unrevoke` first if the revocation was a
2970/// mistake; otherwise there is nothing to grant.
2971///
2972/// **Numbering:** `-32053`..`-32055` are skipped. They are the SESSION-plane codes
2973/// (`mcpmesh_net::errors`: rate-limited / service refused / unreachable), and `-32053` in particular
2974/// is named by number throughout this file and the docs with its rate-limit meaning. Control codes
2975/// `-32051` and `-32052` already collide with session codes, which is survivable because the two
2976/// planes never share a frame — but a control `-32053` would make "guard on `-32053`" ambiguous on
2977/// the page that documents both. The control family continues from `-32056`.
2978pub const ERR_PRINCIPAL_REVOKED: i64 = -32056;
2979
2980/// `pair` — the INVITER refused because it has revoked YOUR identity (`peer_revoke b64u:` on its
2981/// side) (#218, `api_minor >= 61`).
2982///
2983/// The inviter-side twin of [`ERR_PRINCIPAL_REVOKED`], and a different code because it names a
2984/// different node's table: that one is "this node revoked X, run `peer_unrevoke` here"; this one is
2985/// "the peer revoked me, and nothing on this side lifts it". Before #218 the inviter made no such
2986/// check — the row was written with the revoked `user_id`, the caller was told "paired", and every
2987/// session it opened was refused.
2988///
2989/// The one `pair` refusal besides [`ERR_INVITER_MISMATCH`] that must NOT be rendered as "ask for a
2990/// fresh invite": the invite was consumed, and any invite redeemed by a device presenting that
2991/// identity is refused the same way until the inviter lifts the revocation. What it does NOT do:
2992/// identity revocation refuses a device presenting the identity, and cannot stop a person who stops
2993/// presenting the key — redeeming with no binding (or under a new user key) lands as an ordinary
2994/// `eid:` pairing of an endpoint the inviter never revoked. Coded rather than folded into [`ERR_INVITE_REFUSED`] for the reason #147
2995/// codes anything: a caller that has PROVEN a live secret may be told the truth (the redemption
2996/// oracle that keeps `-32049` opaque is about unproven secrets), and the remedy differs from every
2997/// other refusal's — it is on the other side of the wire.
2998pub const ERR_PAIR_IDENTITY_REVOKED: i64 = -32057;
2999
3000/// `self_enroll_detach` on a device with NO adopted binding in effect (#214): there is no live
3001/// enrollment to exit, and nothing live was changed. A STALE enrollment file left on disk (by a
3002/// boot that declined a binding that did not verify for this endpoint) is removed first, so the
3003/// next boot will not re-adopt it, and the message says when that happened. A removal that fails
3004/// is not this code: it is an uncoded `-32000` naming the file.
3005///
3006/// A UI that offers the detach only when `self_user_id` is present and `self_user_key_held` is
3007/// `false` does not send it except in a race — a concurrent detach, or an import (which also clears
3008/// the slot) — and can treat it as "already done". (It also never cleans a boot-declined file,
3009/// which is harmless: boot declines it again on every start.) Offering it on `!self_user_key_held`
3010/// alone also offers it to a node with no user key at all, which gets this code.
3011pub const ERR_NOT_ENROLLED: i64 = -32058;
3012
3013/// `invite { as_self: true }` on a device that was itself ENROLLED into another identity (#214):
3014/// it holds no user key, so there is nothing to sign a binding with.
3015///
3016/// Refused AT MINT, on the device that can act on it. Before this the mint succeeded and the
3017/// refusal surfaced one round trip later on the OTHER machine as the deliberately opaque
3018/// [`ERR_INVITE_REFUSED`] — "that invite didn't work, ask for a new one", which is dead-end advice
3019/// for a permanent condition. Remedy: enroll from the device that holds the key, or
3020/// [`Request::SelfEnrollDetach`] this one first if it should not be enrolled at all.
3021/// `StatusResult::self_user_key_held` is the same fact, readable before anyone presses the button.
3022pub const ERR_SELF_ENROLL_NO_KEY: i64 = -32059;
3023
3024/// How many requests one control connection may have in flight at once (#172), after which it
3025/// answers [`ERR_TOO_MANY_INFLIGHT`]. Per connection, not per daemon.
3026pub const MAX_INFLIGHT: usize = 32;
3027
3028pub const API_NAME: &str = "mcpmesh-local/1";
3029/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
3030///
3031/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
3032/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
3033/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
3034/// methods, or a strictness change like params validation — bumped in the same change that makes
3035/// it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
3036/// than a minor it requires. It never resets except on a MAJOR bump.
3037///
3038/// It also bumps for a change to what a field MEANS with no change to its shape — six of the
3039/// thirty have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
3040/// to claim, and it was wrong in both directions: minor 9's entry records surface changes that
3041/// shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
3042pub const API_VERSION: &str = "1.63";
3043/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
3044/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
3045/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
3046/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
3047/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
3048/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
3049/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
3050/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
3051/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
3052/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
3053/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
3054/// observable contract did: a revoked principal's next session is refused even on a connection it
3055/// already holds, and its live connections are severed. Previously both waited for the peer to
3056/// disconnect on its own, which is unbounded (#54). A consumer can guard on
3057/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
3058/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
3059/// about an unknown service name — a name in neither the config nor the ephemeral registry now
3060/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
3061/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
3062/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
3063/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
3064/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
3065/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
3066/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
3067/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
3068/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
3069/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
3070/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
3071/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
3072/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
3073/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
3074/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
3075/// unpublish now survives a later republish via a per-scope withdrawal set, and
3076/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
3077/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
3078/// daemon with more scopes than that previously answered with
3079/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
3080/// the caller an opaque failure with no way to page. The connection survived: the control surface
3081/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
3082/// `total`/`truncated` (#84b); to 21 when a
3083/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
3084/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
3085/// that frame: a live per-session watcher that pushes when a session's selected path changes,
3086/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
3087/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
3088/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
3089/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
3090/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128); to 25
3091/// with [`ActiveSession::principal`] — the live-session view was keyed on a display nickname, so
3092/// two devices under one nickname were indistinguishable and any UI acting on a session (revoke,
3093/// disconnect, inspect) keyed on a collidable string (#73); to 26 when a
3094/// rate-limited inbound NOTIFICATION stopped being silently dropped and became a recorded audit
3095/// event — no type changed; the observable audit stream did (#76, #139); to 27 with the `audit_prune` /
3096/// `audit_list` verbs, `StatusResult::storage`, and the opt-in `[limits].audit_retain_months`
3097/// boot retention — the audit log stopped being a permanent, unbounded, unreadable record (#88);
3098/// to 28 with `StatusResult::self_network` / `StreamFrame::SelfNetwork` / the snapshot's copy —
3099/// the node's OWN reachability posture, previously unanswerable from either side of the API
3100/// (#90); to 29 with [`AuditRecord::principal`] — stable identity on the event stream and the
3101/// on-disk log, resolving #57's parked docs conflict in favour of the #41/#42/#73 line (the
3102/// audit surface bans secrets and raw hex, not the prefixed principal rendering); to 30 with
3103/// [`StreamFrame::Reachability`]'s `source` — the frame has had TWO producers since 22 with no way
3104/// to tell them apart, so an embedder could not distinguish "a throwaway dial went via a relay"
3105/// from "the link this call is on just degraded", and had to hedge every message down to the
3106/// weaker claim. `rtt_ms: None` was never the discriminator the doc implied (#150); to 31 with
3107/// [`ERR_NICKNAME_TAKEN`] — the nickname-collision `pair` refusal is branchable instead of
3108/// `-32000`, so an embedder writes its own recovery copy rather than substring-matching ours. The
3109/// prose changed with it: it named the `set_nickname` CONTROL VERB as the remedy, which a GUI user
3110/// cannot type, and the refusal is generated inviter-side so the embedder displaying it could not
3111/// rewrite it (#147); to 32 with [`SelfNetwork::identity_conflict_epoch`] — two nodes booted from
3112/// COPIES of one mesh root share an endpoint id, and the displaced one's peers went unreachable
3113/// with nothing saying why. The relay reports it and iroh only `warn!`s it, so the fact existed
3114/// and was unreadable (#134); to 33 with the `peer_diagnostics` verb — a long-lived pairing that
3115/// cannot hole-punch while a fresh identity on the same hardware can differs only in DURABLE
3116/// per-peer state, and none of it was readable from outside the daemon (#140); to 34 when
3117/// outstanding invites became DURABLE — `invite.expires_at_epoch` changed meaning from an upper
3118/// bound on the daemon's process lifetime to the real lifetime, and `invite` gained an error where
3119/// it previously always succeeded. No shape changed, which is exactly the class minor 10 records:
3120/// guard on `api_minor >= 34` before telling a user their invite will still be good tomorrow
3121/// (#87b); to 35 with `InviteParams.max_uses` + `InviteResult.uses_remaining` — a bounded
3122/// multi-use invite, so onboarding a team is one link rather than one ceremony per person. Each
3123/// redemption still runs its own SAS and writes its own peer rows; it is N pairings sharing a
3124/// secret, never a group identity (#87); to 36 with branchable codes for the rest of the ONBOARDING
3125/// refusals — expired line, no live invite, inviter unreachable, id mismatch, name conflict, and
3126/// the deliberately-opaque refusal. `ERR_NICKNAME_TAKEN` had been the only coded pairing failure,
3127/// so every other one arrived as `-32000` and an embedder could either forward our prose to end
3128/// users or substring-match it (#159); to 63 when the identity gates began to hold under the
3129/// user-key lock (#221, #219) — no type changed: `user_key_export` REFUSES (`-32602`) on an
3130/// enrolled device, where through 62 it returned the recovery phrase of the local key boot minted,
3131/// an identity no peer has paired with; `user_key_import`'s `replace` guard now protects a key an
3132/// earlier import wrote within the same daemon lifetime, where through 62 a second import without
3133/// `replace` silently discarded the first; `peer_endorse` refuses when no user key is on disk
3134/// instead of minting one; and `peer_endorse`, `device_revoke`, `user_key_export` and the
3135/// self-enrollment signature check the enrollment gate under the lock an adoption or import writes
3136/// under, so neither can land between the check and the signature. Guard on `>= 63` before
3137/// offering `user_key_export` on a device whose `self_user_key_held` is false. Crate-level a MINOR
3138/// release of `mcpmesh-node` (0.54 → 0.55): `pairing::rendezvous::SignBindingFn` became async; to
3139/// 62 with the self-enrollment EXIT and the surface an
3140/// embedder needs to ship the ceremony at all (#214): [`Request::SelfEnrollDetach`] drops an
3141/// adopted binding (the inverse of `pair { allow_self_enroll }`, and the only exit an enrolled
3142/// device has — `user_key_import` needs the phrase of a key it does not hold);
3143/// [`RecentPairing::self_enroll`] marks which ceremony produced a SAS row, so the inviter's
3144/// mismatch branch can route to `device_revoke` instead of a `peer_remove` of a peer that does not
3145/// exist; [`StatusResult::self_user_key_held`] says whether this device holds its key, which is
3146/// what `peer_endorse`, `device_revoke` and `invite { as_self }` all refuse without; `device_revoke`
3147/// now REFUSES on an enrolled device (a bug: it signed with the local key, self-applied the
3148/// revocation and severed sessions, then returned a token no peer would ever accept — a silent
3149/// partial success on the stolen-laptop path); and `invite { as_self }` on an enrolled device is
3150/// refused at mint with [`ERR_SELF_ENROLL_NO_KEY`] rather than one round trip later, on the other
3151/// machine, as the opaque `-32049`. Guard on `>= 62` before offering the detach; the two fields
3152/// read `false` from an older daemon, which is wrong for exactly the case each exists to name
3153/// (`self_user_key_held` for a key-holder, `self_enroll` for an enrollment row), so guard before
3154/// rendering them. Crate-level, this one is a MINOR release of `mcpmesh-node` (0.53 → 0.54), not a
3155/// patch: `InviterCtx::record_pairing`'s closure signature changed (`RecordPairingFn` now takes the
3156/// whole `RecentPairing`) and `MeshState::recent_pairings` became `pub`, both on that crate's
3157/// public surface; to 61 when an IDENTITY revocation (`peer_revoke b64u:`)
3158/// began to hold at every site (#218): `pair` answers [`ERR_PAIR_IDENTITY_REVOKED`] when the
3159/// inviter has revoked the redeemer's proven `user_id`, `peer_introduce` answers
3160/// [`ERR_PRINCIPAL_REVOKED`] for a subject proving one this node revoked, and admission refuses
3161/// any stored row carrying a revoked `user_id` — as does every OUTBOUND dial: `open_session`,
3162/// `peer_services` and `peer_diagnostics` answer the same "REVOKED" refusal an endpoint-revoked
3163/// device gets, and `pair` REDEEMING an invite from an inviter this node revoked (its endpoint, the
3164/// identity its row carries, or the identity it proves in its reply) answers
3165/// [`ERR_PRINCIPAL_REVOKED`] before writing a row or running the grant-back. Below 61 only device attestation consulted the
3166/// identity table: a fresh invite (or an introduction) landed a row for the person's next device,
3167/// the caller was told "paired", and the row's `services[].allow` grant was honoured — which is
3168/// also why minor 60's "a `b64u:` hides only while EVERY device is refused" no longer holds: a
3169/// per-device `peer_unrevoke` under a standing identity revocation re-admits nothing, and the
3170/// entry stays hidden until the identity itself is unrevoked. Guard on `>= 61` before branching
3171/// on the new code; to 60 when `services[].allow` on `status` became
3172/// REVOCATION-AWARE and `service_allow_grant` began refusing a revoked principal with
3173/// [`ERR_PRINCIPAL_REVOKED`] (#212). No shape changed — minor 17's class again. #100 made
3174/// `services[].allow` answer from the live registry so it could not report a grant the accept path
3175/// refuses, and that claim was one gate short: `peer_revoke` writes only the revocation table, the
3176/// registry's `allow` kept the entry, and `status` copied it out unfiltered. An entry whose
3177/// principal is revoked — as admission defines it — is now omitted from `allow` (and, index-aligned,
3178/// from `allow_display`); for a `peer_revoke` revocation `status.revoked` still lists the principal,
3179/// so the fact is not lost, only moved to the surface that means it (a ROSTER-revoked device is
3180/// omitted too, and its record is the roster's own `revoked_endpoints` — it is absent from
3181/// `roster_members` as well). The write path closed with it: the grant used to succeed and
3182/// write an entry admission would never honour. Guard on `>= 60` before treating an `allow` entry's
3183/// absence as "not granted" rather than "granted but refused", and before branching on the new
3184/// code; below it, join `status.revoked` against `allow` yourself; to 59 with [`Request::PeerHintClear`] — FORGET one peer's
3185/// persisted dial hint (#140). An experiment tool and a workaround, not a policy change: nothing
3186/// clears a hint automatically. `PeerEntry.last_addr` is the only durable per-peer state on a node's
3187/// disk that the dial path reads and the only thing a long-lived pairing carries that a freshly
3188/// paired identity does not, so clearing it makes the pairing ADDRESSING-EQUIVALENT to a fresh one —
3189/// which is exactly the difference #140 is about. Advisory, never authorization: the row, its
3190/// `user_id`, its services and its pairing stamp are untouched, and an absent hint is a supported
3191/// state. Guard on `>= 59`; to 58 with the REVERSE-DNS `_meta` key spellings
3192/// `tech.counterpunch.mcpmesh/{service,peer}` alongside the legacy `mcpmesh/{service,peer}` (#49,
3193/// SEP-1788's SHOULD). No shape changed, and **no peer or backend has to change what it READS**:
3194/// both spellings are WRITTEN with identical values and EITHER is accepted, which is why this did
3195/// not need the coordinated wire change #49 assumed. A backend reading `mcpmesh/peer` keeps working.
3196///
3197/// **It is not a no-op for every backend, though.** A handler that rejects unknown `_meta` keys —
3198/// `deny_unknown_fields`, `additionalProperties: false` — now sees a second one and will refuse
3199/// requests it accepted at 57, the same class of break that made 0.50.0 a MINOR. Both prefixes are stripped from caller frames, because a
3200/// prefix mcpmesh writes but does not strip is one a caller can forge. A caller sending the two
3201/// service spellings with DIFFERENT values is REFUSED rather than reconciled. The reserved-key
3202/// enumeration in the 2026-07-28 grammar is `progressToken`, `io.modelcontextprotocol/*`, and bare
3203/// `traceparent`/`tracestate`/`baggage`; a prefixed key is reserved only by its SECOND label, so
3204/// neither of our spellings ever collided. **The legacy
3205/// `mcpmesh/*` spellings are deprecated as of 0.51.0 and will be removed at 1.0** — migrate reads to
3206/// the reverse-DNS form. Guard on `>= 58` only if you need the new spelling to be present; to 57
3207/// when `_meta["mcpmesh/peer"]` began being injected on
3208/// EVERY proxied request rather than only the handshake (#45 ask 2). **No shape changed** — this is
3209/// the same class as 37, on the same field: what changed is WHEN a backend can rely on the value
3210/// being there. Before 57 a served backend learned its caller on the session's first frame and on
3211/// any later `initialize`, and saw nothing on frames 2..N; from 57 every request carrying a `method`
3212/// is attributed. A backend that authorizes per-request rather than binding at session start must
3213/// guard on `>= 57`, exactly as 37's note says to guard before trusting the value at all. Positional
3214/// (array) params are the one exception and are deliberately left un-attributed — see
3215/// `docs/local-protocol.md`. Guard on `>= 57`; to 56 with [`PeerDiagnosticsResult::known_addrs`] and its two
3216/// set-difference companions — IROH's own view of a peer's addresses alongside the hint we stored
3217/// (#140). The verb dumped this node's disk and nothing about what iroh made of it, which is the
3218/// half the standing hypothesis lives in: iroh skips address lookup while a path is selected, so a
3219/// pair holding a relayed connection never re-discovers and the stale hint is the only addressing
3220/// the dial contributes. Read-only (a point read of the remote map), so it stays safe to run on a
3221/// live reproduction — though it does reset iroh's ~60s per-remote idle timer, so polling it keeps
3222/// state alive that would otherwise be reaped. `known_addrs` ABSENT means iroh holds no entry right
3223/// now, which is neither an empty list nor "never heard of": iroh reaps a remote ~60s after its last
3224/// connection closes. Guard on `>= 56`; to 55 with [`StreamFrame::Resumed`] — a SUSPEND/RESUME
3225/// signal on `subscribe` (#167 ask 2). A suspended machine sends nothing, so the peer's idle timer
3226/// tears the connection down before the lid reopens and `keep_alive_secs` cannot help; the frame is
3227/// what lets an embedder re-dial deliberately instead of discovering it on the next send. Detected
3228/// as wall-clock/monotonic skew, so a starved runtime (both clocks run long) does NOT emit. It names
3229/// no session — the daemon cannot know which survived. Guard on `>= 55`; to 54 with
3230/// [`OpenSessionParams::idle_timeout_secs`] — a
3231/// PER-CONNECTION QUIC idle timeout on the dial path (#166). The node-wide `[network]` knob made a
3232/// chat session, a bulk blob transfer and a media flow share one compromise. Only LOWERING is
3233/// unilateral (QUIC negotiates the minimum of both peers), which is also why the absence of an
3234/// accept-side twin is a missing symmetry rather than a missing half: the direction that can work
3235/// one-sidedly is available, and the direction that cannot never worked anywhere. Ignored on a
3236/// RACING dial, which abandons connections (logged at `warn!`, since a caller cannot know how many
3237/// devices a peer has). No per-connection keepalive — iroh caps the per-path
3238/// interval at 5s, so one could only make pings more frequent. Guard on `>= 54`; to 53 with `org_rotate` and the roster's
3239/// `successor_root_pk`/`successor_sig` — ORG ROOT ROTATION (#93 ask c). The schema pinned exactly
3240/// one signature slot against one key, so an operator laptop that died took the org with it 90 days
3241/// later when the roster expired, and the delay is what made it undiagnosable; recovery was O(N)
3242/// fresh ceremonies with every member. A roster now carries a successor root cross-signed by its
3243/// predecessor, and the bridge rides EVERY subsequent roster — so a member offline for the
3244/// announcing publication still catches up, which the obvious one-shot design does not give you. A
3245/// successor is adopted only when the pinned key no longer signs directly, only on a statement that
3246/// key signed, and never resets rollback protection. **A rotated roster declares
3247/// `mcpmesh-roster/2`**, so EVERY member must be on 0.47.0+ before an org rotates — an older binary
3248/// refuses the closed-schema document and stops receiving membership changes entirely; an org that
3249/// never rotates keeps producing `/1` byte-identically. NOT escrow: a LOST root cannot sign a bridge —
3250/// copy `org-root.key` to a second operator machine for that. Guard on `>= 53`; to 52 with `attest_offer` and the DEVICE ATTESTATION
3251/// ceremony (#85 ask 3) — a peer that already holds your `b64u:` admits a replacement device on the
3252/// strength of a user-key binding, with no fresh SAS ceremony with everyone you ever paired with.
3253/// `PeerEntry.user_id` was written once at pairing and never refreshed, so a machine restored from
3254/// a recovery phrase (ask 2) was still a complete stranger. **OFF by default**
3255/// (`[identity].admit_attested_devices`): it changes what a pairing MEANS, from admitting a device
3256/// to admitting a person and their future devices, and that should be chosen rather than inherited
3257/// on upgrade. An attestation cannot admit a stranger — the receiver must already hold a row for
3258/// that `user_id` — cannot resurrect a REVOKED endpoint OR a revoked IDENTITY (ask 4, which is why
3259/// it shipped first; `peer_revoke` on a `b64u:` now revokes the person, because a thief holding the
3260/// disk holds the user key and can mint a fresh endpoint id at will), and
3261/// grants the INTERSECTION of that person's existing services, never the union. Guard on `>= 52`;
3262/// to 51 with the PAIRING-MODE REVOCATION verbs —
3263/// `peer_revoke` / `peer_unrevoke` / `device_revoke` / `device_revocation_import`, plus
3264/// [`StatusResult::revoked`] (#85 ask 4). `revoked_endpoints` was roster-only, so in pairing mode
3265/// the only remedy for a stolen device was every peer independently running `peer_remove`, with
3266/// nothing telling them they should — until the last one did, whoever held the disk authenticated
3267/// as its owner and every message they sent was cryptographically indistinguishable. Two
3268/// directions, deliberately not one verb: `peer_revoke` is MY local decision about YOUR device;
3269/// `device_revoke` signs a portable statement about MY OWN, which is the half my peers cannot
3270/// discover for themselves. An import is honoured only from a `user_id` this node already pairs
3271/// with, and only for that person's OWN devices — a signature proves who asked, not that the
3272/// endpoint was ever theirs. Revocation is IMMEDIATE (live sessions severed, #54) and outlives the
3273/// pair row, so it cannot be undone by re-pairing. Guard on `>= 51`; to 50 with [`SelfNetwork::local_discovery`] — LOCAL (mDNS)
3274/// peer discovery, off unless `[network].local_discovery` asks for it (#68). Peer resolution
3275/// otherwise needs external infrastructure, so two machines on one LAN with no uplink could not
3276/// find each other though the path between them was fine. Three modes: `"off"` (default), `"on"`
3277/// (resolve AND announce), `"resolve"` (resolve without publishing this node's identity — it still
3278/// QUERIES about once a second, so it is quieter, not silent). Reported on `status` because the
3279/// setting was
3280/// otherwise unobservable and because **`"on"` means this node multicasts its endpoint id and
3281/// addresses to every device on the link** — a product backing a privacy switch has to be able to
3282/// show that. Deliberately NOT on by default, against what #68 asked for: pkarr publishes a signed
3283/// record you must already know the endpoint id to look up, while mDNS announces to strangers on a
3284/// café or hotel network, and a multicast packet cannot be un-sent. Guard on `>= 50`; to 49 with [`StorageInfo::blobs_gc`] — app-blob GARBAGE
3285/// COLLECTION, off unless `[blobs].gc_interval` is set (#80). `blob_unpublish` and `blob_revoke`
3286/// closed the AUTHORIZATION half at 15; neither reclaimed a byte, so `<data_dir>/blobs/` grew
3287/// monotonically for the life of the node and an embedder that had told a user "this file is
3288/// deleted" could not deliver that. Opt-in, because a sweep also reclaims blobs this node FETCHED
3289/// and never republished — reclaimable in themselves (the fetch already wrote the caller's
3290/// `dest_path`) but it means `blob_republish` of a hash fetched more than one interval ago fails.
3291/// `blobs_gc` is `None` when collection is not configured, `Some` with `runs: 0` when it is
3292/// configured and has not swept yet — a distinction worth reading, because the collector sleeps a
3293/// full interval before its first run. WATCH `runs`: iroh-blobs ends collection for the process on
3294/// its first sweep error, so a counter that stops advancing is the only signal. Guard on `>= 49`;
3295/// to 48 with `user_key_export` / `user_key_import` — a
3296/// RECOVERY PHRASE for the user key, so a person's `b64u:` survives the hardware (#85 ask 2). It
3297/// lived in one file on one machine with no export, import or escrow verb anywhere, so replacing a
3298/// laptop destroyed the identity peers pin, kb audiences key on, and a roster names — recovery was
3299/// an in-person SAS ceremony with everyone you had ever paired with. **The export response carries
3300/// a PRIVATE KEY**: it is deliberately absent from the audit log, from `status`, and from every
3301/// other surface. Import refuses to overwrite an existing key unless asked, because doing so
3302/// discards a live identity irreversibly. What it does NOT do: get a device admitted. Peers
3303/// authorize per DEVICE, and a restored user key puts this endpoint in nobody's allowlist — that is
3304/// #85 ask 3, unshipped, and the reason a recovered person still pairs. Guard on `>= 48`; to 47 with `BlobFetchParams::from` — ADDITIONAL sources a
3305/// fetch falls back to when the ticket's publisher does not answer (#83). Content addressing makes
3306/// every recipient a potential source, and a one-address ticket made that unusable: a file shared
3307/// with a room became unfetchable the moment the sender closed their laptop, though others in the
3308/// room already held the identical verified bytes. Additive and absent-tolerant — an older caller's
3309/// payload reads as empty, which is the single-source behaviour — so guard on `>= 47` only before
3310/// SENDING the field (`deny_unknown_fields` rejects the whole request below it). The bytes stay
3311/// BLAKE3-verified against the ticket's hash whoever serves them, so an alternate can refuse but
3312/// never substitute; it must have republished the hash into a scope granting the caller
3313/// (`blob_republish`, `api_minor >= 18`). What did NOT land: multi-source PARALLEL fetch — sources
3314/// are tried in order, so an offline publisher costs one dial timeout; to 46 with the roster-mode embedding surface (#66, #93):
3315/// the `org_create` / `org_approve` / `org_revoke` AUTHORING verbs, the `roster_members` read,
3316/// `PresencePeer::display_name` + `groups`, `RosterStatus::groups`, and
3317/// `OrgJoinResult::restart_required`. Two gaps close together. Authoring existed only as CLI
3318/// porcelain, so an embedded node could CONSUME a roster and never author one — no "approve this
3319/// person" button without shelling out to a second binary. And the roster's own contents never
3320/// crossed the seam: an embedder had managed group membership it could not display, and the only
3321/// route to a member list was hand-parsing the daemon-owned `roster.json`. `roster_members` is a
3322/// different question from `status.presence` — that lists reachable DEVICES and omits a person
3323/// whose devices are all down. `restart_required` closes a silent partial success: `roster_mode` is
3324/// a BOOT decision fixing the bound ALPNs and whether gossip/presence/blobs exist at all, so a
3325/// pairing-mode node that ran `org_join` got working MCP sessions with permanently empty presence
3326/// and no way to detect it. Guard on `>= 46` before offering org authoring in a UI; the read fields
3327/// are additive and degrade to empty. What did NOT land: org root ROTATION (#93c) — an operator
3328/// laptop that dies still takes the org with it once the roster expires; to 45 with [`PairParams::allow_self_enroll`] +
3329/// [`ERR_SELF_ENROLL_NOT_OFFERED`] — `pair` now REFUSES a `mcpmesh-enroll:` line unless the caller
3330/// asked for that ceremony. A behaviour change for existing callers, deliberately: at 43-44 a caller
3331/// whose UI only ever offered "add a contact" completed a self-enrollment and learned which
3332/// ceremony it had run from `enrolled_as_self` afterwards — by which point the device→user binding
3333/// was written and irrevocable short of rotating the user key (#178). The refusal is decided from
3334/// the line before any dial, so the invite survives it and the same line works once the ceremony is
3335/// actually offered. Guard on `>= 45` before sending the field — below it `deny_unknown_fields`
3336/// rejects the whole request. Note what the guard means: a daemon BELOW 45 gives a caller no way to
3337/// decline, so a UI that does not offer device enrollment should require `>= 45` rather than pair
3338/// without it; to 44 when control responses stopped arriving in REQUEST
3339/// order and the `blob_fetch_cancel` verb landed (#172). The daemon now dispatches each request
3340/// CONCURRENTLY on its connection, so a `blob_fetch` no longer stalls every other verb behind it —
3341/// and responses arrive in COMPLETION order. JSON-RPC ids make that legal and the in-tree
3342/// `ControlClient` cannot observe it (one request at a time, by construction), but a hand-rolled
3343/// client that pipelines and matches responses POSITIONALLY breaks. A connection also caps
3344/// in-flight requests and refuses over it with [`ERR_TOO_MANY_INFLIGHT`], and closing a control
3345/// connection now genuinely ABORTS its in-flight work rather than letting it run to completion
3346/// unread. Guard on `>= 44` before pipelining, before sending `blob_fetch_cancel`, and before
3347/// treating [`ERR_CANCELLED`] as unexpected; to 43 with `InviteParams::as_self` — SELF-ENROLLMENT, so one
3348/// person's devices share a `user_id` instead of appearing as unrelated strangers (#86). The
3349/// ceremony is ordinary pairing; the outcome is a device→user binding rather than a peer row, and
3350/// the private key never moves. Guard on `>= 43`. What this entry did NOT say, and 45 fixed: the
3351/// distinct scheme closes the version-SKEW hazard (a pre-43 redeemer silently over-granting) and
3352/// closes nothing for a CURRENT redeemer, which had no way to decline a ceremony it never offered
3353/// (#178); to 42 with the `peer_introduce` + `peer_endorse`
3354/// verbs — install a peer from a
3355/// SIGNED endorsement by someone you are already paired with, so a small group onboards in O(N)
3356/// instead of O(N²) two-human ceremonies (#65). It installs IDENTITY only and grants nothing, which
3357/// is what bounds it. Guard on `>= 42`; to 41 with `StreamFrame::BlobTransfer` — live app-blob
3358/// transfer progress on both the serving and fetching side (#82 ask 2), so an embedder can draw a
3359/// real progress bar instead of an indeterminate spinner. Guard on `>= 41` before expecting the
3360/// frame. NOTE what it did NOT bring, and 44 did: at 41 `blob_fetch` still blocked its whole
3361/// control connection for the transfer and nothing could cancel it (#172) — progress arrived on the
3362/// SUBSCRIBE connection, which is a different one; to 40 with `[services.<name>].rate_limit_per_min` +
3363/// `RegisterServiceParams::rate_limit_per_min` — proxied-request buckets became per
3364/// `(service, endpoint)` instead of one shared per-endpoint bucket, so a noisy service can no
3365/// longer starve a quiet one (#63). `-32053` changes meaning with it: it is now per-service, so a
3366/// consumer that backs off globally on one is backing off further than it needs to. Guard on
3367/// `>= 40` before sending the field or narrowing a back-off; to 39 with `PairParams::as_nickname` +
3368/// `InviteParams::peer_nickname` — LOCAL aliases for the other party, so a nickname collision is
3369/// resolvable by the person who hit it instead of requiring the other human to rename a machine or
3370/// re-mint. #147 made the collision diagnosable; this makes it fixable. Guard on `>= 39` before
3371/// offering an alias field in a UI: below it `deny_unknown_fields` rejects the whole request
3372/// (#87); to 38 with `[network].presence_mode` + `SelfNetwork.
3373/// presence_mode` — `reachable: false` gained a new meaning ("up, paired, and deliberately not
3374/// answering"), and `peer_services` flips from "reachable, empty list" to "unreachable" for a
3375/// caller holding no grant. A consumer must guard on `api_minor >= 38` before telling a user their
3376/// peer is offline, since below it that verdict could not mean this (#89); to 37 when the reserved
3377/// `mcpmesh/*` `_meta` namespace began
3378/// being enforced on EVERY proxied frame rather than the session's first. `run_session` treats
3379/// frame 1 as the `initialize` whatever its method is, so a caller could send any other method
3380/// first and put its real `initialize` — with a forged `mcpmesh/peer` naming another principal,
3381/// forged `groups` and all — in frame 2, where nothing stripped or injected. No shape changed;
3382/// what changed is whether `_meta["mcpmesh/peer"]` can be trusted, which is the entire reason a
3383/// backend reads it. Guard on `api_minor >= 37` before keying authorization on that value (#164).
3384///
3385/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
3386/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
3387/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
3388/// be that class and did bump; do not infer from them that every such change will. When bumping
3389/// several minors at once, read this block end to end AND the release notes, not the diff.
3390///
3391/// That class is bigger than it looks: **10, 17, 21, 22, 23, 24 and 37 all shipped with no change
3392/// to any type in this file** — they moved meaning, not shape. Seven of the forty, and 37 is
3393/// a SECURITY fix, which is the case where a consumer most needs the guard. 38 adds a field, but
3394/// its REAL content is a meaning change to `reachable` — the field exists so the new meaning is
3395/// observable at all. A downstream
3396/// that diffs types across a multi-minor bump sees nothing for any of them.
3397pub const API_MINOR: u32 = 63;
3398
3399#[cfg(test)]
3400mod tests {
3401 use super::*;
3402
3403 /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
3404 /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
3405 /// privacy guarantee that daemon never made.
3406 #[test]
3407 fn peer_path_tags_and_defaults_to_unknown() {
3408 let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
3409 assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
3410 assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
3411 let relay = tagged(PeerPath::Relay {
3412 url: Some("https://relay.example/".into()),
3413 });
3414 assert_eq!(relay["kind"], "relay");
3415 assert_eq!(relay["url"], "https://relay.example/");
3416 // A relay whose URL we do not know still tags as relay, with the key elided.
3417 let bare = tagged(PeerPath::Relay { url: None });
3418 assert_eq!(bare["kind"], "relay");
3419 assert!(bare.get("url").is_none(), "elided, not null: {bare}");
3420
3421 // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
3422 // row. Without `#[serde(other)]` an unknown `kind` errors out of
3423 // `PeerReachability` entirely, so one new variant would break every `status` read an
3424 // older pinned client does.
3425 let future: PeerPath =
3426 serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
3427 assert_eq!(future, PeerPath::Unknown);
3428 let row: PeerReachability = serde_json::from_value(serde_json::json!({
3429 "name": "bob", "reachable": true, "path": {"kind": "quantum"}
3430 }))
3431 .expect("an unknown path kind must not fail the whole row");
3432 assert_eq!(row.path, PeerPath::Unknown);
3433 assert!(row.reachable, "the rest of the row survives");
3434
3435 // A pre-#64 row: no `path` key.
3436 let old = serde_json::json!({"name": "bob", "reachable": true});
3437 let parsed: PeerReachability = serde_json::from_value(old).unwrap();
3438 assert_eq!(
3439 parsed.path,
3440 PeerPath::Unknown,
3441 "an older daemon's row must never imply a direct path"
3442 );
3443 }
3444
3445 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
3446 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
3447 /// consumer projects both through one code path.
3448 #[test]
3449 fn reachability_frame_tags_and_round_trips() {
3450 let frame = StreamFrame::Reachability {
3451 peer: PeerReachability {
3452 name: "bob".into(),
3453 reachable: true,
3454 rtt_ms: Some(12),
3455 age_secs: Some(0),
3456 meta: String::new(),
3457 principal: Some("eid:beef".into()),
3458 path: Default::default(),
3459 },
3460 source: ReachabilitySource::Probe,
3461 };
3462 let v = serde_json::to_value(&frame).unwrap();
3463 assert_eq!(v["type"], "reachability");
3464 assert_eq!(v["peer"]["name"], "bob");
3465 assert_eq!(v["peer"]["reachable"], true);
3466 assert_eq!(
3467 v["peer"]["age_secs"], 0,
3468 "a transition frame is fresh by construction: {v}"
3469 );
3470 assert_eq!(v["source"], "probe", "#150: the producer is named: {v}");
3471 let back: StreamFrame = serde_json::from_value(v).unwrap();
3472 assert_eq!(back, frame);
3473 }
3474
3475 /// #150: the frame's `source` wire shape, and the two ways it must degrade.
3476 ///
3477 /// The default is the load-bearing part. An absent key comes from a daemon at `api_minor`
3478 /// 22–29, which ALREADY has both producers — so it must land on `Unknown`, never on `Probe`.
3479 /// Defaulting to `Probe` would tell a consumer "a throwaway dial saw this" about frames that
3480 /// were a live session degrading, which is the ambiguity the field exists to remove.
3481 /// #140: `known_addrs` absent, empty, and populated are three DIFFERENT wire shapes.
3482 ///
3483 /// The distinction is the field's whole reason for existing, and it is carried by
3484 /// `skip_serializing_if` — so it lives on the wire, not in Rust. An embedder checking
3485 /// `known_addrs === null` gets `undefined`, which is why the absent case is asserted as a
3486 /// MISSING KEY rather than a null.
3487 #[test]
3488 fn known_addrs_distinguishes_absent_from_empty_on_the_wire() {
3489 let base = PeerDiagnosticsResult {
3490 nickname: "jetson".into(),
3491 principal: "eid:beef".into(),
3492 hint_usable: true,
3493 ..Default::default()
3494 };
3495
3496 // Absent: the key is OMITTED, never serialized as null.
3497 let v = serde_json::to_value(&base).unwrap();
3498 assert!(
3499 v.get("known_addrs").is_none(),
3500 "an absent iroh entry elides the key — a consumer must test presence, not null: {v}"
3501 );
3502
3503 // Empty: iroh HAS an entry and holds no address. A real, different state.
3504 let empty = PeerDiagnosticsResult {
3505 known_addrs: Some(vec![]),
3506 ..base.clone()
3507 };
3508 let v = serde_json::to_value(&empty).unwrap();
3509 assert_eq!(
3510 v["known_addrs"],
3511 serde_json::json!([]),
3512 "an empty list must survive as `[]` rather than collapsing back to absent: {v}"
3513 );
3514 assert_eq!(
3515 serde_json::from_value::<PeerDiagnosticsResult>(v).unwrap(),
3516 empty,
3517 "and round-trip back to Some(vec![]), not None"
3518 );
3519
3520 // Populated, with the `active` flag per address.
3521 let full = PeerDiagnosticsResult {
3522 known_addrs: Some(vec![
3523 KnownAddr {
3524 addr: "192.168.1.77:4433".into(),
3525 active: true,
3526 },
3527 KnownAddr {
3528 addr: "relay https://r.example:8443".into(),
3529 active: false,
3530 },
3531 ]),
3532 hint_addrs_unknown_to_iroh: vec!["10.0.0.9:4433".into()],
3533 ..base
3534 };
3535 let v = serde_json::to_value(&full).unwrap();
3536 assert_eq!(v["known_addrs"][0]["addr"], "192.168.1.77:4433");
3537 assert_eq!(v["known_addrs"][0]["active"], true);
3538 assert_eq!(v["known_addrs"][1]["active"], false);
3539 assert_eq!(
3540 v["hint_addrs_unknown_to_iroh"],
3541 serde_json::json!(["10.0.0.9:4433"])
3542 );
3543 assert!(
3544 v.get("iroh_addrs_not_in_hint").is_none(),
3545 "an empty difference elides rather than shipping `[]` noise in every capture: {v}"
3546 );
3547 assert_eq!(
3548 serde_json::from_value::<PeerDiagnosticsResult>(v).unwrap(),
3549 full
3550 );
3551 }
3552
3553 #[test]
3554 fn reachability_source_tags_and_defaults_to_unknown() {
3555 let tagged = |s: ReachabilitySource| serde_json::to_value(s).unwrap();
3556 assert_eq!(tagged(ReachabilitySource::Probe), "probe");
3557 assert_eq!(tagged(ReachabilitySource::Session), "session");
3558 assert_eq!(tagged(ReachabilitySource::Unknown), "unknown");
3559 for s in [
3560 ReachabilitySource::Probe,
3561 ReachabilitySource::Session,
3562 ReachabilitySource::Unknown,
3563 ] {
3564 let back: ReachabilitySource = serde_json::from_value(tagged(s)).unwrap();
3565 assert_eq!(back, s, "round trip");
3566 }
3567
3568 let peer = serde_json::json!({"name": "bob", "reachable": true});
3569
3570 // A pre-#150 frame: no `source` key at all.
3571 let old: StreamFrame =
3572 serde_json::from_value(serde_json::json!({"type": "reachability", "peer": peer}))
3573 .expect("an older daemon's frame must still parse");
3574 let StreamFrame::Reachability { source, .. } = old else {
3575 panic!("expected a reachability frame");
3576 };
3577 assert_eq!(
3578 source,
3579 ReachabilitySource::Unknown,
3580 "an api_minor 22-29 daemon has BOTH producers, so an absent key must not claim Probe"
3581 );
3582
3583 // A producer from a NEWER daemon must degrade to Unknown, not fail the whole frame — the
3584 // same stake `PeerPath` buys with `#[serde(other)]`. Without the hand-written Deserialize
3585 // a third producer would break every Reachability frame an older pinned client reads.
3586 let future: StreamFrame = serde_json::from_value(
3587 serde_json::json!({"type": "reachability", "peer": peer, "source": "telemetry"}),
3588 )
3589 .expect("an unknown producer must not fail the whole frame");
3590 let StreamFrame::Reachability { source, peer } = future else {
3591 panic!("expected a reachability frame");
3592 };
3593 assert_eq!(source, ReachabilitySource::Unknown);
3594 assert!(peer.reachable, "the rest of the frame survives");
3595 }
3596
3597 /// #148: a defaulted status is EMPTY and honest — the fixture ergonomic an embedder gets in
3598 /// exchange for us adding fields.
3599 ///
3600 /// Its content is the load-bearing part. A downstream test that omits a field must not thereby
3601 /// assert something: no phantom peers or services, and the optional blocks absent rather than
3602 /// zeroed. `storage: Some(StorageInfo::default())` would read as "0 bytes on disk", which is a
3603 /// measurement nobody took.
3604 #[test]
3605 fn a_defaulted_status_is_empty_and_claims_nothing() {
3606 let d = StatusResult::default();
3607 assert!(d.peers.is_empty() && d.services.is_empty(), "{d:?}");
3608 assert!(d.reachability.is_empty() && d.presence.is_empty(), "{d:?}");
3609 assert!(d.recent_pairings.is_empty(), "{d:?}");
3610 assert_eq!(d.roster, None, "no roster is not an empty roster");
3611 assert_eq!(d.storage, None, "absent, not 0 bytes — nobody measured");
3612 assert_eq!(d.self_network, None, "absent, not offline — nobody looked");
3613 assert_eq!(d.self_user_id, None);
3614 assert!(
3615 d.stack_version.is_empty() && d.self_nickname.is_empty(),
3616 "{d:?}"
3617 );
3618
3619 // The pattern the issue actually asks for: additive growth stops breaking fixtures.
3620 let fixture = StatusResult {
3621 peers: vec![PeerInfo {
3622 name: "bob".into(),
3623 ..Default::default()
3624 }],
3625 ..Default::default()
3626 };
3627 assert_eq!(fixture.peers[0].name, "bob");
3628 assert!(fixture.services.is_empty());
3629
3630 // A default round-trips, so the elide-vs-null discipline holds for one too.
3631 let v = serde_json::to_value(&d).unwrap();
3632 assert!(v.get("roster").is_none(), "elided, not null: {v}");
3633 assert!(v.get("storage").is_none(), "elided, not null: {v}");
3634 let back: StatusResult = serde_json::from_value(v).unwrap();
3635 assert_eq!(back, d);
3636 }
3637
3638 /// #148: a defaulted reachability row is NOT reachable and makes NO path claim.
3639 ///
3640 /// This is the one default where a wrong choice would be a false guarantee rather than a
3641 /// harmless placeholder — the same trap `PeerPath`'s `#[default] Unknown` exists to avoid
3642 /// (#64), now reachable through a second door. A fixture that forgot to set `path` must not
3643 /// thereby assert the peer was reached directly, and one that forgot `reachable` must not
3644 /// claim it was up.
3645 #[test]
3646 fn a_defaulted_reachability_row_asserts_nothing_about_the_peer() {
3647 let d = PeerReachability::default();
3648 assert!(!d.reachable, "an unset row must not claim the peer is up");
3649 assert_eq!(
3650 d.path,
3651 PeerPath::Unknown,
3652 "an unset path must never read as Direct — that is a privacy claim no one made"
3653 );
3654 assert_eq!(d.rtt_ms, None, "no measurement was taken");
3655 assert_eq!(d.age_secs, None, "never probed");
3656 assert_eq!(d.principal, None);
3657 assert!(d.name.is_empty() && d.meta.is_empty());
3658 }
3659
3660 /// #148 gate: the REST of the new defaults, which the first pass left entirely unasserted —
3661 /// moving `BackendKind`'s `#[default]` to `Socket` failed nothing across the whole workspace.
3662 ///
3663 /// Each assertion below is the conservative reading of a field that could otherwise let a
3664 /// fixture assert something by omission.
3665 #[test]
3666 fn the_remaining_defaults_are_conservative() {
3667 let s = ServiceInfo::default();
3668 assert!(
3669 s.allow.is_empty(),
3670 "an unset allow must admit NOBODY — empty is deny (the gate's `any()` is false on an \
3671 empty list), and a permissive default here would be an authz hole reachable from a \
3672 fixture"
3673 );
3674 assert!(s.allow_display.is_empty() && s.name.is_empty());
3675 assert!(
3676 !s.ephemeral,
3677 "persistent is the conservative reading, and matches the wire default"
3678 );
3679 assert_eq!(
3680 s.backend,
3681 BackendKind::Run,
3682 "the documented choice — a convenience, not a claim; pinned so it cannot drift \
3683 silently out of step with its own rustdoc"
3684 );
3685 assert_eq!(BackendKind::default(), BackendKind::Run);
3686
3687 let p = PeerInfo::default();
3688 assert!(p.name.is_empty() && p.services.is_empty());
3689 assert_eq!(p.user_id, None, "no identity was proven");
3690 assert_eq!(p.principal, None);
3691
3692 // The gate's finding: this default is the documented "deliberately LAN-only" posture,
3693 // which the porcelain renders as healthy and NOT as a warning. It is unavoidable (a bool
3694 // has no third state) but it must stay deliberate, so it is pinned rather than left to
3695 // be rediscovered by whoever writes the next fixture.
3696 let n = SelfNetwork::default();
3697 assert!(!n.online, "no relay connection is established");
3698 assert!(
3699 n.relays.is_empty() && n.home_relay.is_none(),
3700 "and none are known — which the renderer reads as LAN-BY-CONFIGURATION, not as an \
3701 outage; say 'nobody looked' with StatusResult.self_network: None instead"
3702 );
3703 assert_eq!(n.last_change_epoch, None, "no transition was observed");
3704
3705 let r = RelayInfo::default();
3706 assert!(
3707 !r.connected,
3708 "an unset relay must not claim a live connection"
3709 );
3710
3711 let st = StorageInfo::default();
3712 assert_eq!(
3713 (st.audit_bytes, st.redb_bytes, st.blobs_bytes),
3714 (0, 0, 0),
3715 "zeros read as MEASURED-and-empty; `StatusResult.storage: None` is 'unmeasured'"
3716 );
3717
3718 let ro = RosterStatus::default();
3719 assert!(
3720 ro.state.is_empty(),
3721 "not a valid state word, deliberately — `doctor` warns on an unknown state rather \
3722 than reporting a healthy roster"
3723 );
3724 assert_eq!(ro.serial, 0);
3725
3726 let pp = PresencePeer::default();
3727 assert!(
3728 !pp.online,
3729 "an unset presence row must not claim the device is up"
3730 );
3731 assert!(pp.role.is_empty() && pp.user_id.is_empty());
3732
3733 let rp = RecentPairing::default();
3734 assert_eq!(rp.paired_at_epoch, 0);
3735 assert!(rp.sas_code.is_empty(), "no ceremony produced a code");
3736 assert!(
3737 !rp.self_enroll,
3738 "an unset row is an ordinary pairing (#214)"
3739 );
3740 }
3741
3742 /// #214: `RecentPairing.self_enroll` is elided when false (an older client's payload
3743 /// round-trips) and rides the wire when true — the field an inviter-side SAS panel routes on,
3744 /// instead of the `"(this person's device)"` prose.
3745 #[test]
3746 fn recent_pairing_self_enroll_is_additive_and_defaults_to_false() {
3747 let legacy: RecentPairing = serde_json::from_value(serde_json::json!({
3748 "peer_nickname": "bob", "sas_code": "tango-fig-cabbage", "paired_at_epoch": 1
3749 }))
3750 .unwrap();
3751 assert!(
3752 !legacy.self_enroll,
3753 "an absent self_enroll is an ordinary pairing"
3754 );
3755
3756 let ordinary = RecentPairing {
3757 peer_nickname: "bob".into(),
3758 sas_code: "tango-fig-cabbage".into(),
3759 paired_at_epoch: 1,
3760 self_enroll: false,
3761 };
3762 let v = serde_json::to_value(&ordinary).unwrap();
3763 assert!(
3764 v.get("self_enroll").is_none(),
3765 "false is elided, like every additive bool on this surface: {v}"
3766 );
3767
3768 let enrolled = RecentPairing {
3769 self_enroll: true,
3770 ..ordinary
3771 };
3772 let v = serde_json::to_value(&enrolled).unwrap();
3773 assert_eq!(v["self_enroll"], true);
3774 let back: RecentPairing = serde_json::from_value(v).unwrap();
3775 assert_eq!(back, enrolled);
3776 }
3777
3778 /// #214: `StatusResult.self_user_key_held` is additive — absent reads `false` — and the detach
3779 /// verb has a parameterless tag plus a result whose `user_id` is optional on the wire.
3780 #[test]
3781 fn self_user_key_held_and_self_enroll_detach_serialize_additively() {
3782 let legacy: StatusResult = serde_json::from_value(serde_json::json!({
3783 "stack_version": "0", "services": [], "peers": []
3784 }))
3785 .unwrap();
3786 assert!(
3787 !legacy.self_user_key_held,
3788 "an older daemon omits the field; it must read false rather than fail the parse"
3789 );
3790 let v = serde_json::to_value(&legacy).unwrap();
3791 assert!(
3792 v.get("self_user_key_held").is_none(),
3793 "false is elided: {v}"
3794 );
3795
3796 let v = serde_json::to_value(&Request::SelfEnrollDetach).unwrap();
3797 assert_eq!(v["method"], "self_enroll_detach");
3798 assert!(v.get("params").is_none(), "parameterless: {v}");
3799
3800 let res = SelfEnrollDetachResult {
3801 user_id: Some("b64u:mine".into()),
3802 detached_from: "b64u:theirs".into(),
3803 };
3804 let v = serde_json::to_value(&res).unwrap();
3805 assert_eq!(v["user_id"], "b64u:mine");
3806 assert_eq!(v["detached_from"], "b64u:theirs");
3807 assert_eq!(
3808 serde_json::from_value::<SelfEnrollDetachResult>(v).unwrap(),
3809 res
3810 );
3811 let keyless: SelfEnrollDetachResult =
3812 serde_json::from_value(serde_json::json!({"detached_from": "b64u:theirs"})).unwrap();
3813 assert_eq!(keyless.user_id, None);
3814
3815 assert_eq!(ERR_NOT_ENROLLED, -32058);
3816 assert_eq!(ERR_SELF_ENROLL_NO_KEY, -32059);
3817 }
3818
3819 /// #150 gate: "an unrecognized value reads as `unknown`" must hold for any VALUE, not just an
3820 /// unrecognized string.
3821 ///
3822 /// `#[serde(default)]` covers an absent key and nothing else, so `"source": null` — what a
3823 /// proxy or non-Rust daemon that normalizes optional fields produces — went through the
3824 /// deserializer and failed the WHOLE frame, silently dropping a liveness transition while the
3825 /// protocol doc promised the field could not break a parse. The container shapes matter
3826 /// separately: a visitor that answers without draining a map/seq desynchronizes the parser and
3827 /// fails the frame anyway, which looks identical from outside.
3828 #[test]
3829 fn a_malformed_source_degrades_instead_of_failing_the_frame() {
3830 let peer = serde_json::json!({"name": "bob", "reachable": true});
3831 for bad in [
3832 serde_json::Value::Null,
3833 serde_json::json!(7),
3834 serde_json::json!(-1),
3835 serde_json::json!(1.5),
3836 serde_json::json!(true),
3837 serde_json::json!({"kind": "probe", "nested": {"deep": [1, 2]}}),
3838 serde_json::json!(["probe", "session"]),
3839 ] {
3840 let frame: StreamFrame = serde_json::from_value(
3841 serde_json::json!({"type": "reachability", "peer": peer, "source": bad}),
3842 )
3843 .unwrap_or_else(|e| panic!("`source: {bad}` must not fail the whole frame: {e}"));
3844 let StreamFrame::Reachability { source, peer } = frame else {
3845 panic!("expected a reachability frame");
3846 };
3847 assert_eq!(source, ReachabilitySource::Unknown, "for source: {bad}");
3848 assert!(peer.reachable, "the rest of the frame survives: {bad}");
3849 }
3850 }
3851
3852 /// #90: the self-network frame tags as `{"type":"self_network","self_network":{…}}` — the
3853 /// SAME block `status` and the snapshot carry. Pinned explicitly (like the reachability
3854 /// tag) so a variant rename cannot slip past a suite whose two ends share the type while
3855 /// breaking every doc-following third-party client.
3856 #[test]
3857 fn self_network_frame_tags_and_round_trips() {
3858 let frame = StreamFrame::SelfNetwork {
3859 self_network: SelfNetwork {
3860 online: true,
3861 home_relay: Some("https://relay.example:443".into()),
3862 relays: vec![RelayInfo {
3863 url: "https://relay.example:443".into(),
3864 connected: true,
3865 }],
3866 direct_addrs: vec!["192.168.1.2:4444".into()],
3867 last_change_epoch: Some(1_753_842_000),
3868 identity_conflict_epoch: None,
3869 // #89: seeded NON-default so the round-trip actually carries it — an empty value
3870 // here would round-trip through a `skip_serializing_if` and prove nothing.
3871 presence_mode: Some("granted".into()),
3872 // #68: seeded `"resolve"`, deliberately NOT the `"off"` default — a fixture equal
3873 // to the default would round-trip identically whether or not the field was carried
3874 // at all, and the assertion below would measure nothing.
3875 local_discovery: Some("resolve".into()),
3876 },
3877 };
3878 let v = serde_json::to_value(&frame).unwrap();
3879 assert_eq!(v["type"], "self_network");
3880 assert_eq!(v["self_network"]["online"], true);
3881 assert_eq!(v["self_network"]["home_relay"], "https://relay.example:443");
3882 assert_eq!(v["self_network"]["relays"][0]["connected"], true);
3883 assert_eq!(
3884 v["self_network"]["presence_mode"], "granted",
3885 "#89: the live presence mode must reach the wire — it is the only way an operator can \
3886 confirm the knob took effect, and a product's privacy switch has nothing to render \
3887 without it"
3888 );
3889 assert_eq!(
3890 v["self_network"]["local_discovery"], "resolve",
3891 "#68: the live local-discovery mode must reach the wire — `\"on\"` means this node is \
3892 multicasting its endpoint id to every device on the link, and a privacy switch has \
3893 nothing to render without it"
3894 );
3895 let back: StreamFrame = serde_json::from_value(v).unwrap();
3896 assert_eq!(back, frame);
3897 }
3898
3899 #[test]
3900 fn peer_reachability_serde_is_additive() {
3901 let r = PeerReachability {
3902 name: "bob".into(),
3903 reachable: true,
3904 rtt_ms: Some(42),
3905 age_secs: Some(3),
3906 meta: String::new(),
3907 principal: None,
3908 path: Default::default(),
3909 };
3910 let v = serde_json::to_value(&r).unwrap();
3911 assert_eq!(v["name"], "bob");
3912 assert_eq!(v["reachable"], true);
3913 assert_eq!(v["rtt_ms"], 42);
3914 assert_eq!(v["age_secs"], 3);
3915 // Never-probed peer: optionals elided, not null.
3916 let unknown = PeerReachability {
3917 name: "carol".into(),
3918 reachable: false,
3919 rtt_ms: None,
3920 age_secs: None,
3921 meta: String::new(),
3922 principal: None,
3923 path: Default::default(),
3924 };
3925 let uv = serde_json::to_value(&unknown).unwrap();
3926 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
3927 // An older StatusResult (no reachability field) still deserializes.
3928 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
3929 let s: StatusResult = serde_json::from_value(old).unwrap();
3930 assert!(s.reachability.is_empty());
3931 }
3932
3933 #[test]
3934 fn subscribe_method_tag_resolves() {
3935 let req = serde_json::to_value(Request::Subscribe).unwrap();
3936 assert_eq!(method_of(&req), Some("subscribe"));
3937 }
3938
3939 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
3940
3941 #[test]
3942 fn invite_params_reject_singular_service_typo() {
3943 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
3944 // `InviteParams { services: [] }` and mint a grants-nothing invite that looked
3945 // successful. With deny_unknown_fields the typo is a loud parse error instead.
3946 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
3947 assert!(
3948 err.is_err(),
3949 "an unknown `service` key must be rejected, not silently ignored"
3950 );
3951 // The correct plural shape still parses.
3952 let ok: InviteParams =
3953 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
3954 assert_eq!(ok.services, vec!["kb".to_string()]);
3955 }
3956
3957 #[test]
3958 fn open_session_params_reject_unknown_field() {
3959 let err = serde_json::from_value::<OpenSessionParams>(
3960 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
3961 );
3962 assert!(err.is_err(), "unknown params keys must be rejected");
3963 }
3964
3965 #[test]
3966 fn set_app_metadata_request_carries_the_method_tag() {
3967 let r = Request::SetAppMetadata(SetAppMetadataParams {
3968 metadata: "v=1.2.3".into(),
3969 });
3970 let v = serde_json::to_value(&r).unwrap();
3971 assert_eq!(v["method"], "set_app_metadata");
3972 assert_eq!(v["params"]["metadata"], "v=1.2.3");
3973 assert_eq!(method_of(&v), Some("set_app_metadata"));
3974 }
3975
3976 #[test]
3977 fn set_app_metadata_params_reject_unknown_field() {
3978 let err = serde_json::from_value::<SetAppMetadataParams>(
3979 serde_json::json!({"metadata": "x", "nonsense": 1}),
3980 );
3981 assert!(err.is_err(), "unknown params keys must be rejected");
3982 }
3983
3984 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
3985 /// empty meta does not serialize.
3986 #[test]
3987 fn peer_info_principal_is_additive() {
3988 // An older payload (no principal) still deserializes; empty does not serialize.
3989 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
3990 let p: PeerInfo = serde_json::from_value(old).unwrap();
3991 assert_eq!(p.principal, None);
3992 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
3993 // A bound peer carries BOTH the person user_id AND the device principal (#41).
3994 let full = PeerInfo {
3995 name: "bob".into(),
3996 services: vec!["notes".into()],
3997 user_id: Some("b64u:BOB".into()),
3998 principal: Some("eid:0707".into()),
3999 };
4000 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
4001 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
4002 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
4003 }
4004
4005 #[test]
4006 fn active_session_principal_is_additive() {
4007 // An OLD payload (no `principal`) must still deserialize — #73 is additive.
4008 let old: ActiveSession =
4009 serde_json::from_str(r#"{"peer":"bob","service":"notes","opened_at":7}"#).unwrap();
4010 assert_eq!(old.principal, None, "serde(default) supplies it");
4011
4012 // And a `None` must not serialize, so an old client sees the shape it expects.
4013 let json = serde_json::to_string(&old).unwrap();
4014 assert!(
4015 !json.contains("principal"),
4016 "skip_serializing_if must omit it: {json}"
4017 );
4018
4019 // A real row round-trips the principal.
4020 let new = ActiveSession {
4021 peer: "bob".into(),
4022 service: "notes".into(),
4023 opened_at: 7,
4024 principal: Some("eid:1f0a".into()),
4025 };
4026 let back: ActiveSession =
4027 serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
4028 assert_eq!(back.principal.as_deref(), Some("eid:1f0a"));
4029 }
4030
4031 #[test]
4032 fn peer_reachability_principal_is_additive() {
4033 // Older payload (no principal) still deserializes; empty does not serialize; a set
4034 // value round-trips alongside the #40 meta so an embedder joins on the principal.
4035 let old = serde_json::json!({"name": "bob", "reachable": true});
4036 let r: PeerReachability = serde_json::from_value(old).unwrap();
4037 assert_eq!(r.principal, None);
4038 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
4039 let full = PeerReachability {
4040 name: "bob".into(),
4041 reachable: true,
4042 rtt_ms: Some(12),
4043 age_secs: Some(3),
4044 meta: "v=1.2.3".into(),
4045 principal: Some("eid:0707".into()),
4046 path: Default::default(),
4047 };
4048 let back: PeerReachability =
4049 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
4050 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
4051 assert_eq!(back.meta, "v=1.2.3");
4052 }
4053
4054 #[test]
4055 fn peer_reachability_meta_is_additive() {
4056 // An older payload (no meta) still deserializes; an empty meta does not serialize.
4057 let old = serde_json::json!({"name": "bob", "reachable": true});
4058 let r: PeerReachability = serde_json::from_value(old).unwrap();
4059 assert_eq!(r.meta, "");
4060 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
4061 // A set value round-trips.
4062 let with = PeerReachability {
4063 name: "bob".into(),
4064 reachable: true,
4065 rtt_ms: Some(12),
4066 age_secs: Some(3),
4067 meta: "v=1.2.3".into(),
4068 principal: None,
4069 path: Default::default(),
4070 };
4071 let back: PeerReachability =
4072 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
4073 assert_eq!(back.meta, "v=1.2.3");
4074 }
4075
4076 #[test]
4077 fn presence_peer_meta_is_additive() {
4078 let old = serde_json::json!({
4079 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
4080 });
4081 let p: PresencePeer = serde_json::from_value(old).unwrap();
4082 assert_eq!(p.meta, "");
4083 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
4084 }
4085
4086 #[test]
4087 fn set_nickname_request_carries_the_method_tag() {
4088 let r = Request::SetNickname(SetNicknameParams {
4089 nickname: "workbench".into(),
4090 });
4091 let v = serde_json::to_value(&r).unwrap();
4092 assert_eq!(v["method"], "set_nickname");
4093 assert_eq!(v["params"]["nickname"], "workbench");
4094 assert_eq!(method_of(&v), Some("set_nickname"));
4095 }
4096
4097 #[test]
4098 fn set_nickname_params_reject_unknown_field() {
4099 let err = serde_json::from_value::<SetNicknameParams>(
4100 serde_json::json!({"nickname": "x", "nonsense": 1}),
4101 );
4102 assert!(err.is_err(), "unknown params keys must be rejected");
4103 }
4104
4105 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
4106 /// the additive-only contract — and an empty name must not serialize at all.
4107 #[test]
4108 fn status_self_nickname_is_additive() {
4109 let old = serde_json::json!({
4110 "stack_version": "0.7.0", "services": [], "peers": []
4111 });
4112 let s: StatusResult = serde_json::from_value(old).unwrap();
4113 assert_eq!(s.self_nickname, "");
4114 let v = serde_json::to_value(&s).unwrap();
4115 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
4116 }
4117
4118 #[test]
4119 fn api_minor_is_present_and_monotonic_from_hello() {
4120 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
4121 // crate/stack version, additive on the Hello frame.
4122 let h = Hello {
4123 api: API_NAME.into(),
4124 api_version: API_VERSION.into(),
4125 api_minor: API_MINOR,
4126 stack_version: "9.9.9".into(),
4127 };
4128 let v = serde_json::to_value(&h).unwrap();
4129 assert_eq!(v["api_minor"], API_MINOR);
4130 // An OLD Hello without api_minor still deserializes (additive contract).
4131 let old = serde_json::json!({
4132 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
4133 });
4134 let back: Hello = serde_json::from_value(old).unwrap();
4135 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
4136 }
4137
4138 #[test]
4139 fn hello_result_roundtrips() {
4140 let h = Hello {
4141 api: "mcpmesh-local/1".into(),
4142 api_version: "1.0".into(),
4143 api_minor: 0,
4144 stack_version: "0.1.0".into(),
4145 };
4146 let v = serde_json::to_value(&h).unwrap();
4147 assert_eq!(v["api"], "mcpmesh-local/1");
4148 let back: Hello = serde_json::from_value(v).unwrap();
4149 assert_eq!(back, h);
4150 }
4151
4152 #[test]
4153 fn request_tagged_by_method() {
4154 let r = Request::Status;
4155 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
4156 let r = Request::OpenSession(OpenSessionParams {
4157 peer: "alice".into(),
4158 service: "notes".into(),
4159 // #166: seeded NON-default so the round-trip carries it. An absent value would be
4160 // elided by `skip_serializing_if` and the assertion below would prove nothing.
4161 idle_timeout_secs: Some(7),
4162 });
4163 let v = serde_json::to_value(&r).unwrap();
4164 assert_eq!(v["method"], "open_session");
4165 assert_eq!(v["params"]["peer"], "alice");
4166 assert_eq!(v["params"]["idle_timeout_secs"], 7);
4167 // …and an absent one really is absent, so an older daemon sees the payload it always saw.
4168 let bare = serde_json::to_value(Request::OpenSession(OpenSessionParams {
4169 peer: "alice".into(),
4170 service: "notes".into(),
4171 idle_timeout_secs: None,
4172 }))
4173 .unwrap();
4174 assert!(bare["params"].get("idle_timeout_secs").is_none());
4175 }
4176
4177 #[test]
4178 fn parameterless_method_tolerates_params_forms() {
4179 // Omitted and null params deserialize straight into the unit variant.
4180 let omitted: Request =
4181 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
4182 assert_eq!(omitted, Request::Status);
4183 let null: Request =
4184 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
4185 .unwrap();
4186 assert_eq!(null, Request::Status);
4187
4188 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
4189 // the server MUST dispatch on the method string rather than deserialize the whole
4190 // message into `Request`. This is the pattern the daemon's dispatcher uses.
4191 let empty = serde_json::json!({"method": "status", "params": {}});
4192 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
4193 match method_of(&empty) {
4194 Some("status") => {} // dispatcher resolves Status via the method string
4195 other => panic!("method_of failed to resolve status: {other:?}"),
4196 }
4197 }
4198
4199 #[test]
4200 fn backend_spec_roundtrips() {
4201 let run = BackendSpec::Run {
4202 cmd: vec!["notes-mcp".into(), "--stdio".into()],
4203 env: Default::default(),
4204 cwd: None,
4205 };
4206 let v = serde_json::to_value(&run).unwrap();
4207 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
4208 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
4209
4210 let sock = BackendSpec::Socket {
4211 path: "/run/notes.sock".into(),
4212 };
4213 let v = serde_json::to_value(&sock).unwrap();
4214 assert_eq!(v["socket"]["path"], "/run/notes.sock");
4215 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
4216 }
4217
4218 #[test]
4219 fn register_service_wire_shape() {
4220 let r = Request::RegisterService(RegisterServiceParams {
4221 name: "notes".into(),
4222 backend: BackendSpec::Run {
4223 cmd: vec!["notes-mcp".into()],
4224 env: Default::default(),
4225 cwd: None,
4226 },
4227 allow: vec!["alice".into()],
4228 ephemeral: false,
4229 rate_limit_per_min: None,
4230 });
4231 let v = serde_json::to_value(&r).unwrap();
4232 assert_eq!(
4233 v,
4234 serde_json::json!({
4235 "method": "register_service",
4236 "params": {
4237 "name": "notes",
4238 "backend": {"run": {"cmd": ["notes-mcp"]}},
4239 "allow": ["alice"],
4240 }
4241 })
4242 );
4243 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4244 }
4245
4246 #[test]
4247 fn invite_request_and_result_roundtrip() {
4248 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
4249 let r = Request::Invite(InviteParams {
4250 services: vec!["notes".into(), "kb".into()],
4251 app_label: None,
4252 max_uses: None,
4253 // #87: seeded NON-None so the round-trip actually carries it — `None` rides
4254 // `skip_serializing_if` straight past the assertion and proves nothing.
4255 peer_nickname: Some("laptop-of-alice".into()),
4256 as_self: false,
4257 });
4258 let v = serde_json::to_value(&r).unwrap();
4259 assert_eq!(v["method"], "invite");
4260 assert_eq!(
4261 v["params"]["peer_nickname"], "laptop-of-alice",
4262 "#87: the inviter's local alias for the redeemer must reach the wire"
4263 );
4264 assert_eq!(v["params"]["services"][0], "notes");
4265 assert_eq!(v["params"]["services"][1], "kb");
4266 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4267 // method_of resolves the tag generically (no per-variant arm).
4268 assert_eq!(
4269 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
4270 Some("invite")
4271 );
4272
4273 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
4274 let res = InviteResult {
4275 invite_line: "mcpmesh-invite:ABCDEF".into(),
4276 expires_at_epoch: 1_800_000_000,
4277 uses_remaining: 1,
4278 };
4279 let v = serde_json::to_value(&res).unwrap();
4280 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
4281 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
4282 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
4283 }
4284
4285 #[test]
4286 fn pair_request_and_result_roundtrip() {
4287 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
4288 let r = Request::Pair(PairParams {
4289 invite_line: "mcpmesh-invite:ABCDEF".into(),
4290 as_nickname: Some("alice-mbp".into()),
4291 allow_self_enroll: true,
4292 });
4293 let v = serde_json::to_value(&r).unwrap();
4294 assert_eq!(v["method"], "pair");
4295 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
4296 assert_eq!(
4297 v["params"]["as_nickname"], "alice-mbp",
4298 "#87: the redeemer's local alias for the inviter must reach the wire"
4299 );
4300 assert_eq!(
4301 v["params"]["allow_self_enroll"], true,
4302 "#178: the caller's consent to a self-enrollment must reach the wire — the daemon \
4303 refuses the ceremony without it"
4304 );
4305 // An OLD caller's payload — no alias — must still decode. The field is additive.
4306 let legacy: PairParams =
4307 serde_json::from_value(serde_json::json!({"invite_line": "x"})).unwrap();
4308 assert_eq!(legacy.as_nickname, None);
4309 // #178: and the consent defaults to REFUSING. A caller that predates the field, or one that
4310 // simply never set it, must not be read as having offered a device enrollment — that is the
4311 // whole guard, and a `#[serde(default)]` flipping to `true` would silently remove it.
4312 assert!(
4313 !legacy.allow_self_enroll,
4314 "an absent allow_self_enroll must default to false (refuse), never to true"
4315 );
4316 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4317 // method_of resolves the tag generically (no per-variant arm).
4318 assert_eq!(
4319 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
4320 Some("pair")
4321 );
4322
4323 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
4324 // the granted services (the porcelain renders each as `<peer>/<service>`).
4325 let res = PairResult {
4326 peer_nickname: "alice".into(),
4327 sas_code: "tango-fig-cabbage".into(),
4328 services: vec!["notes".into(), "kb".into()],
4329 app_label: None,
4330 peer_user_id: None,
4331 enrolled_as_self: false,
4332 };
4333 let v = serde_json::to_value(&res).unwrap();
4334 assert_eq!(v["peer_nickname"], "alice");
4335 assert_eq!(v["sas_code"], "tango-fig-cabbage");
4336 assert_eq!(v["services"][0], "notes");
4337 assert_eq!(v["services"][1], "kb");
4338 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
4339
4340 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
4341 // deserializes — the `#[serde(default)]` fills it with an empty list.
4342 let old_shape = serde_json::json!({
4343 "peer_nickname": "alice",
4344 "sas_code": "tango-fig-cabbage",
4345 });
4346 let back: PairResult = serde_json::from_value(old_shape).unwrap();
4347 assert_eq!(back.peer_nickname, "alice");
4348 assert!(back.services.is_empty());
4349 }
4350
4351 #[test]
4352 fn roster_install_request_and_result_roundtrip() {
4353 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
4354 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
4355 let r = Request::RosterInstall(RosterInstallParams {
4356 path: "/tmp/roster.json".into(),
4357 org_root_pk: Some("b64u:AAAA".into()),
4358 });
4359 let v = serde_json::to_value(&r).unwrap();
4360 assert_eq!(v["method"], "roster_install");
4361 assert_eq!(v["params"]["path"], "/tmp/roster.json");
4362 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
4363 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4364 // method_of resolves the tag generically (no per-variant arm).
4365 assert_eq!(
4366 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
4367 Some("roster_install")
4368 );
4369
4370 // When the pk is omitted (a subsequent install using the pinned value), it is
4371 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
4372 let omit = Request::RosterInstall(RosterInstallParams {
4373 path: "/tmp/roster.json".into(),
4374 org_root_pk: None,
4375 });
4376 let v = serde_json::to_value(&omit).unwrap();
4377 assert!(
4378 v["params"].get("org_root_pk").is_none(),
4379 "an omitted org_root_pk must not appear on the wire: {v}"
4380 );
4381 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
4382
4383 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
4384 let res = RosterInstallResult {
4385 org_id: "acme".into(),
4386 serial: 42,
4387 severed: 1,
4388 };
4389 let v = serde_json::to_value(&res).unwrap();
4390 assert_eq!(v["org_id"], "acme");
4391 assert_eq!(v["serial"], 42u64);
4392 assert_eq!(v["severed"], 1u32);
4393 assert_eq!(
4394 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
4395 res
4396 );
4397
4398 // Additive-only: a result minted by an older daemon (no `severed` key) still
4399 // deserializes — the `#[serde(default)]` fills it with 0.
4400 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
4401 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
4402 assert_eq!(back.serial, 7);
4403 assert_eq!(back.severed, 0);
4404 }
4405
4406 #[test]
4407 fn org_join_request_and_result_roundtrip() {
4408 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
4409 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
4410 let r = Request::OrgJoin(OrgJoinParams {
4411 org_id: "acme".into(),
4412 org_root_pk: "b64u:AAAA".into(),
4413 user_id: "alice".into(),
4414 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
4415 });
4416 let v = serde_json::to_value(&r).unwrap();
4417 assert_eq!(v["method"], "org_join");
4418 assert_eq!(v["params"]["org_id"], "acme");
4419 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
4420 assert_eq!(v["params"]["user_id"], "alice");
4421 assert_eq!(
4422 v["params"]["user_key"],
4423 "/home/alice/.config/mcpmesh/user.key"
4424 );
4425 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4426 // method_of resolves the tag generically (no per-variant arm).
4427 assert_eq!(
4428 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
4429 Some("org_join")
4430 );
4431
4432 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
4433 let res = OrgJoinResult {
4434 org_id: "acme".into(),
4435 restart_required: true,
4436 };
4437 let v = serde_json::to_value(&res).unwrap();
4438 assert_eq!(v["org_id"], "acme");
4439 assert_eq!(
4440 v["restart_required"], true,
4441 "#93: a half-live join must reach the wire — the caller cannot detect it any other way"
4442 );
4443 // Additive: an older daemon omits it, and absent reads as `false` — which was that
4444 // daemon's implicit answer. Pinned so the default cannot silently flip to `true` and start
4445 // telling every caller to restart.
4446 let legacy: OrgJoinResult =
4447 serde_json::from_value(serde_json::json!({"org_id": "acme"})).unwrap();
4448 assert!(!legacy.restart_required);
4449 // …and the false case must not bloat the payload.
4450 let quiet = serde_json::to_value(OrgJoinResult {
4451 org_id: "acme".into(),
4452 restart_required: false,
4453 })
4454 .unwrap();
4455 assert!(quiet.get("restart_required").is_none());
4456 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
4457 }
4458
4459 #[test]
4460 fn set_roster_url_request_roundtrip() {
4461 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
4462 let r = Request::SetRosterUrl(SetRosterUrlParams {
4463 url: "https://intranet.acme.com/roster.json".into(),
4464 });
4465 let v = serde_json::to_value(&r).unwrap();
4466 assert_eq!(v["method"], "set_roster_url");
4467 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
4468 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4469 assert_eq!(
4470 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
4471 Some("set_roster_url")
4472 );
4473 }
4474
4475 #[test]
4476 fn peer_remove_request_roundtrip() {
4477 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
4478 let r = Request::PeerRemove(PeerRemoveParams {
4479 nickname: "bob".into(),
4480 });
4481 let v = serde_json::to_value(&r).unwrap();
4482 assert_eq!(v["method"], "peer_remove");
4483 assert_eq!(v["params"]["nickname"], "bob");
4484 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4485 // method_of resolves the tag generically (no per-variant arm).
4486 assert_eq!(
4487 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
4488 Some("peer_remove")
4489 );
4490 }
4491
4492 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
4493 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
4494 /// defaulting to empty when absent.
4495 /// #65: the wire tags for the introduction pair. The serde tag must equal the dispatch string
4496 /// the daemon matches on — nothing else checks that they agree.
4497 #[test]
4498 fn peer_introduce_and_endorse_roundtrip() {
4499 let r = Request::PeerIntroduce(PeerIntroduceParams {
4500 subject: "eid:aa".into(),
4501 endorsed_by: "b64u:carol".into(),
4502 evidence: "b64u:sig".into(),
4503 subject_user_id: Some("b64u:bob".into()),
4504 subject_binding: Some("b64u:bind".into()),
4505 nickname: "bob".into(),
4506 });
4507 let v = serde_json::to_value(&r).unwrap();
4508 assert_eq!(
4509 v["method"], "peer_introduce",
4510 "the tag must match the daemon's dispatch string exactly"
4511 );
4512 assert_eq!(v["params"]["subject"], "eid:aa");
4513 assert_eq!(v["params"]["subject_binding"], "b64u:bind");
4514 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4515
4516 // The two proof fields are OPTIONAL on the wire and omitted when absent.
4517 let minimal = Request::PeerIntroduce(PeerIntroduceParams {
4518 subject: "eid:aa".into(),
4519 endorsed_by: "b64u:carol".into(),
4520 evidence: "b64u:sig".into(),
4521 subject_user_id: None,
4522 subject_binding: None,
4523 nickname: "bob".into(),
4524 });
4525 let v = serde_json::to_value(&minimal).unwrap();
4526 assert!(v["params"].get("subject_user_id").is_none());
4527 assert!(v["params"].get("subject_binding").is_none());
4528 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), minimal);
4529
4530 let e = Request::PeerEndorse(PeerEndorseParams {
4531 subject: "eid:aa".into(),
4532 subject_user_id: None,
4533 });
4534 let v = serde_json::to_value(&e).unwrap();
4535 assert_eq!(v["method"], "peer_endorse");
4536 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), e);
4537
4538 let res = PeerEndorseResult {
4539 endorsed_by: "b64u:me".into(),
4540 evidence: "b64u:sig".into(),
4541 };
4542 let v = serde_json::to_value(&res).unwrap();
4543 assert_eq!(v["endorsed_by"], "b64u:me");
4544 assert_eq!(serde_json::from_value::<PeerEndorseResult>(v).unwrap(), res);
4545 }
4546
4547 #[test]
4548 fn peer_add_request_roundtrip() {
4549 let r = Request::PeerAdd(PeerAddParams {
4550 nickname: "bob".into(),
4551 endpoint_id: "96246d3f".into(),
4552 allow: vec!["notes".into()],
4553 });
4554 let v = serde_json::to_value(&r).unwrap();
4555 assert_eq!(v["method"], "peer_add");
4556 assert_eq!(v["params"]["nickname"], "bob");
4557 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
4558 assert_eq!(v["params"]["allow"][0], "notes");
4559 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4560 // An absent allow list deserializes to empty (the server-side tolerance).
4561 let p: PeerAddParams =
4562 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
4563 .unwrap();
4564 assert!(p.allow.is_empty());
4565 }
4566
4567 #[test]
4568 fn peer_rename_request_roundtrip() {
4569 // By user_id (renames all of a person's devices in one op).
4570 let r = Request::PeerRename(PeerRenameParams {
4571 user_id: Some("b64u:BOB".into()),
4572 nickname: None,
4573 to: "Bobby".into(),
4574 });
4575 let v = serde_json::to_value(&r).unwrap();
4576 assert_eq!(v["method"], "peer_rename");
4577 assert_eq!(v["params"]["user_id"], "b64u:BOB");
4578 assert_eq!(v["params"]["to"], "Bobby");
4579 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4580 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
4581 assert_eq!(
4582 method_of(
4583 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
4584 ),
4585 Some("peer_rename")
4586 );
4587 }
4588
4589 #[test]
4590 fn status_result_roundtrips() {
4591 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
4592 // older payload with no `roster` key still deserializes to None (serde default).
4593 let s = StatusResult {
4594 stack_version: "0.1.0".into(),
4595 services: vec![ServiceInfo {
4596 name: "notes".into(),
4597 allow: vec!["alice".into()],
4598 allow_display: vec![],
4599 backend: BackendKind::Run,
4600 ephemeral: false,
4601 }],
4602 peers: vec![PeerInfo {
4603 name: "alice".into(),
4604 services: vec!["notes".into()],
4605 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
4606 user_id: Some("b64u:alicepk".into()),
4607 principal: None,
4608 }],
4609 roster: None,
4610 presence: vec![],
4611 self_user_id: Some("b64u:selfpk".into()),
4612 self_user_key_held: true,
4613 recent_pairings: vec![],
4614 reachability: vec![],
4615 self_nickname: String::new(),
4616 storage: None,
4617 revoked: Vec::new(),
4618 self_network: None,
4619 };
4620 let v = serde_json::to_value(&s).unwrap();
4621 assert_eq!(v["services"][0]["backend"], "run");
4622 // The additive identity fields ride the wire when present.
4623 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
4624 assert_eq!(v["self_user_id"], "b64u:selfpk");
4625 assert_eq!(
4626 v["self_user_key_held"], true,
4627 "#214: rides the wire when set"
4628 );
4629 assert!(
4630 v.get("roster").is_none(),
4631 "an absent roster must not appear on the wire: {v}"
4632 );
4633 assert!(
4634 v.get("presence").is_none(),
4635 "an empty presence must not appear on the wire: {v}"
4636 );
4637 assert!(
4638 v.get("recent_pairings").is_none(),
4639 "an empty recent_pairings must not appear on the wire: {v}"
4640 );
4641 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
4642
4643 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
4644 // deserializes — the identity fields default to None / a nickname-only peer.
4645 let old_shape = serde_json::json!({
4646 "stack_version": "0.1.0",
4647 "services": [],
4648 "peers": [{ "name": "bob", "services": [] }],
4649 });
4650 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
4651 assert!(back.roster.is_none());
4652 assert!(back.presence.is_empty());
4653 assert!(back.self_user_id.is_none());
4654 assert!(back.peers[0].user_id.is_none());
4655 assert!(back.recent_pairings.is_empty());
4656
4657 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
4658 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
4659 let s = StatusResult {
4660 stack_version: "0.1.0".into(),
4661 services: vec![],
4662 peers: vec![],
4663 roster: Some(RosterStatus {
4664 org_id: "acme".into(),
4665 serial: 42,
4666 state: "approved".into(),
4667 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
4668 groups: vec!["eng".into(), "ops".into()],
4669 }),
4670 presence: vec![
4671 PresencePeer {
4672 user_id: "alice".into(),
4673 display_name: "Alice Example".into(),
4674 groups: vec!["eng".into()],
4675 device_label: "laptop".into(),
4676 role: "primary".into(),
4677 online: true,
4678 meta: String::new(),
4679 },
4680 PresencePeer {
4681 user_id: "alice".into(),
4682 display_name: "Alice Example".into(),
4683 groups: vec!["eng".into()],
4684 device_label: "desktop".into(),
4685 role: "mirror".into(),
4686 online: false,
4687 meta: String::new(),
4688 },
4689 ],
4690 self_user_id: None,
4691 self_user_key_held: false,
4692 recent_pairings: vec![],
4693 reachability: vec![],
4694 self_nickname: String::new(),
4695 storage: None,
4696 revoked: Vec::new(),
4697 self_network: None,
4698 };
4699 let v = serde_json::to_value(&s).unwrap();
4700 assert_eq!(v["roster"]["org_id"], "acme");
4701 assert_eq!(v["roster"]["serial"], 42u64);
4702 assert_eq!(v["roster"]["state"], "approved");
4703 assert_eq!(
4704 v["roster"]["org_root_fingerprint"],
4705 "tango-fig-cabbage-anchor"
4706 );
4707 assert_eq!(v["presence"][0]["user_id"], "alice");
4708 assert_eq!(v["presence"][0]["device_label"], "laptop");
4709 assert_eq!(v["presence"][0]["role"], "primary");
4710 assert_eq!(v["presence"][0]["online"], true);
4711 assert_eq!(v["presence"][1]["online"], false);
4712 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
4713 }
4714
4715 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
4716 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
4717 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
4718 /// older daemon (no key at all) still deserializes to empty.
4719 #[test]
4720 fn recent_pairings_are_additive_on_status() {
4721 let s = StatusResult {
4722 stack_version: "0.1.0".into(),
4723 services: vec![],
4724 peers: vec![],
4725 roster: None,
4726 presence: vec![],
4727 self_user_id: None,
4728 self_user_key_held: false,
4729 recent_pairings: vec![RecentPairing {
4730 peer_nickname: "bob".into(),
4731 sas_code: "tango-fig-cabbage".into(),
4732 paired_at_epoch: 1_800_000_000,
4733 self_enroll: false,
4734 }],
4735 reachability: vec![],
4736 self_nickname: String::new(),
4737 storage: None,
4738 revoked: Vec::new(),
4739 self_network: None,
4740 };
4741 let v = serde_json::to_value(&s).unwrap();
4742 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
4743 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
4744 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
4745 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
4746
4747 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
4748 // the `#[serde(default)]` fills it with an empty list.
4749 let old_shape = serde_json::json!({
4750 "stack_version": "0.1.0",
4751 "services": [],
4752 "peers": [],
4753 });
4754 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
4755 assert!(back.recent_pairings.is_empty());
4756 }
4757
4758 #[test]
4759 fn blob_requests_and_results_roundtrip() {
4760 // BlobPublish → { method, params: { scope, path } }.
4761 let r = Request::BlobPublish(BlobPublishParams {
4762 scope: "docs".into(),
4763 path: "/tmp/a.bin".into(),
4764 });
4765 let v = serde_json::to_value(&r).unwrap();
4766 assert_eq!(v["method"], "blob_publish");
4767 assert_eq!(v["params"]["scope"], "docs");
4768 assert_eq!(v["params"]["path"], "/tmp/a.bin");
4769 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4770
4771 // BlobGrant → { method, params: { scope, principal } }.
4772 // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
4773 // would otherwise ship undetected — the e2e test calls the provider directly and never
4774 // crosses JSON-RPC.
4775 let rev = Request::BlobRevoke(BlobRevokeParams {
4776 scope: "photos".into(),
4777 principals: vec!["alice".into()],
4778 });
4779 let v = serde_json::to_value(&rev).unwrap();
4780 assert_eq!(v["method"], "blob_revoke");
4781 assert_eq!(v["params"]["principals"][0], "alice");
4782 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
4783
4784 let unp = Request::BlobUnpublish(BlobUnpublishParams {
4785 scope: "photos".into(),
4786 hash: "abc123".into(),
4787 });
4788 let v = serde_json::to_value(&unp).unwrap();
4789 assert_eq!(v["method"], "blob_unpublish");
4790 assert_eq!(v["params"]["hash"], "abc123");
4791 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
4792
4793 let r = Request::BlobGrant(BlobGrantParams {
4794 scope: "docs".into(),
4795 principal: "alice".into(),
4796 });
4797 let v = serde_json::to_value(&r).unwrap();
4798 assert_eq!(v["method"], "blob_grant");
4799 assert_eq!(v["params"]["principal"], "alice");
4800 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4801
4802 // BlobList is parameterless (method_of resolves it).
4803 assert_eq!(
4804 method_of(&serde_json::json!({"method": "blob_list"})),
4805 Some("blob_list")
4806 );
4807
4808 // BlobFetch → { method, params: { ticket, dest_path, from? } }.
4809 let r = Request::BlobFetch(BlobFetchParams {
4810 ticket: "blobAAA".into(),
4811 dest_path: "/tmp/out.bin".into(),
4812 from: vec!["eid:aa".into(), "b64u:bb".into()],
4813 });
4814 let v = serde_json::to_value(&r).unwrap();
4815 assert_eq!(v["method"], "blob_fetch");
4816 assert_eq!(v["params"]["ticket"], "blobAAA");
4817 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
4818 assert_eq!(
4819 v["params"]["from"][0], "eid:aa",
4820 "#83: the alternate sources must reach the wire IN ORDER — the publisher is tried \
4821 first and these follow, so a reordering changes which source answers"
4822 );
4823 assert_eq!(v["params"]["from"][1], "b64u:bb");
4824 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
4825 // Additive: an older caller omits it, and absent reads as EMPTY — the single-source
4826 // behaviour. A default that invented sources would dial peers the caller never named.
4827 let legacy: BlobFetchParams =
4828 serde_json::from_value(serde_json::json!({"ticket": "x", "dest_path": "/tmp/y"}))
4829 .unwrap();
4830 assert!(legacy.from.is_empty());
4831 // …and an empty list must not bloat the payload.
4832 let quiet = serde_json::to_value(Request::BlobFetch(BlobFetchParams {
4833 ticket: "x".into(),
4834 dest_path: "/tmp/y".into(),
4835 from: vec![],
4836 }))
4837 .unwrap();
4838 assert!(quiet["params"].get("from").is_none());
4839
4840 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
4841 let res = BlobPublishResult {
4842 ticket: "blobAAA".into(),
4843 hash: "ab".repeat(32),
4844 };
4845 let v = serde_json::to_value(&res).unwrap();
4846 assert_eq!(v["ticket"], "blobAAA");
4847 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
4848
4849 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
4850 let res = BlobScopeList {
4851 scopes: vec![ScopeInfo {
4852 name: "docs".into(),
4853 hashes: vec!["ab".repeat(32)],
4854 grants: vec!["alice".into()],
4855 withdrawn: vec![],
4856 hash_count: 1,
4857 grant_count: 1,
4858 withdrawn_count: 0,
4859 }],
4860 total: 1,
4861 truncated: false,
4862 };
4863 let v = serde_json::to_value(&res).unwrap();
4864 assert_eq!(v["scopes"][0]["name"], "docs");
4865 assert_eq!(v["scopes"][0]["grants"][0], "alice");
4866 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
4867
4868 // BlobFetchResult carries the verified hash + byte length.
4869 let res = BlobFetchResult {
4870 hash: "ab".repeat(32),
4871 bytes_len: 4194304,
4872 };
4873 let v = serde_json::to_value(&res).unwrap();
4874 assert_eq!(v["bytes_len"], 4194304u64);
4875 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
4876 }
4877
4878 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
4879 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
4880 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
4881 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
4882 #[test]
4883 fn stream_frames_roundtrip_with_the_documented_tags() {
4884 let snap = StreamFrame::Snapshot {
4885 self_network: None,
4886 active_sessions: vec![ActiveSession {
4887 peer: "bob".into(),
4888 service: "notes".into(),
4889 opened_at: 1_751_760_000,
4890 principal: None,
4891 }],
4892 reachability: vec![PeerReachability {
4893 name: "bob".into(),
4894 reachable: true,
4895 rtt_ms: Some(42),
4896 age_secs: Some(3),
4897 meta: String::new(),
4898 principal: None,
4899 path: Default::default(),
4900 }],
4901 };
4902 let v = serde_json::to_value(&snap).unwrap();
4903 assert_eq!(v["type"], "snapshot");
4904 assert_eq!(v["active_sessions"][0]["peer"], "bob");
4905 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
4906 assert_eq!(v["reachability"][0]["name"], "bob");
4907 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
4908
4909 let event = StreamFrame::Event {
4910 record: Box::new(AuditRecord::session_open(
4911 "2026-07-03T14:02:11.480Z".into(),
4912 Some("bob".into()),
4913 "notes".into(),
4914 None,
4915 )),
4916 };
4917 let v = serde_json::to_value(&event).unwrap();
4918 assert_eq!(v["type"], "event");
4919 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
4920 assert_eq!(v["record"]["kind"], "session_open");
4921 assert_eq!(v["record"]["peer"], "bob");
4922 assert_eq!(v["record"]["service"], "notes");
4923 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
4924
4925 // #167 ask 2: the resume frame's wire shape. A consumer dispatches on `type`, so the tag
4926 // is part of the contract, and `at_epoch` is signed on purpose — the wire carries epoch
4927 // seconds as i64 everywhere else in this file.
4928 let resumed = StreamFrame::Resumed {
4929 suspended_secs: 7200,
4930 at_epoch: 1_700_007_202,
4931 };
4932 let v = serde_json::to_value(&resumed).unwrap();
4933 assert_eq!(
4934 v,
4935 serde_json::json!({
4936 "type": "resumed",
4937 "suspended_secs": 7200,
4938 "at_epoch": 1_700_007_202i64,
4939 })
4940 );
4941 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), resumed);
4942
4943 let lagged = StreamFrame::Lagged { dropped: 12 };
4944 let v = serde_json::to_value(&lagged).unwrap();
4945 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
4946 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
4947 }
4948
4949 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
4950 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
4951 /// raw `Value` stream instead (`ControlClient::open_stream`).
4952 #[test]
4953 fn unknown_stream_frame_type_is_rejected() {
4954 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
4955 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
4956 }
4957
4958 #[test]
4959 fn audit_summary_request_and_result_roundtrip() {
4960 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
4961 // tolerates omitted/null params; the server dispatches on the method string (method_of).
4962 let r = Request::AuditSummary;
4963 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
4964 assert_eq!(
4965 method_of(&serde_json::json!({"method": "audit_summary"})),
4966 Some("audit_summary")
4967 );
4968
4969 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
4970 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
4971 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
4972 let res = AuditSummaryResult {
4973 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
4974 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
4975 total_sessions: 4,
4976 };
4977 let v = serde_json::to_value(&res).unwrap();
4978 assert_eq!(v["per_peer"][1][0], "bob");
4979 assert_eq!(v["per_peer"][1][1], 2u64);
4980 assert_eq!(v["per_service"][1][0], "notes");
4981 assert_eq!(v["total_sessions"], 4u64);
4982 assert_eq!(
4983 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
4984 res
4985 );
4986
4987 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
4988 // deserializes — the `#[serde(default)]` fills it with 0.
4989 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
4990 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
4991 assert_eq!(back.total_sessions, 0);
4992 assert!(back.per_peer.is_empty());
4993 }
4994}