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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum BackendKind {
37 Run,
38 Socket,
39}
40
41/// A registered service as reported by `status` (no transport vocabulary).
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ServiceInfo {
44 pub name: String,
45 pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
46 /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
47 /// display nickname by the daemon (which owns the store); an unresolvable stable
48 /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
49 /// ids (surface discipline). Additive: default + skip-if-empty.
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
51 pub allow_display: Vec<String>,
52 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
53 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
54 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
55 /// daemon omits it and it reads as `false` (the persistent default).
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 pub ephemeral: bool,
58}
59
60/// A known peer as reported by `status` (nickname only — never the EndpointId).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PeerInfo {
63 pub name: String,
64 pub services: Vec<String>,
65 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
66 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
67 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
68 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub user_id: Option<String>,
71 /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
72 /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
73 /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
74 /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
75 /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
76 /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
77 /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
78 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub principal: Option<String>,
81}
82
83/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean:
84/// a nickname + a bool + latency/age NUMBERS — never an endpoint-id, key, or transport path.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct PeerReachability {
87 pub name: String, // the peer's nickname
88 pub reachable: bool, // result of the last probe (false if never probed)
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
93 /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
94 /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
95 /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
96 /// display data; never an authz input. Near-real-time when `status` is read (the probe
97 /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
98 #[serde(default, skip_serializing_if = "String::is_empty")]
99 pub meta: String,
100 /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
101 /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
102 /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
103 /// for a real row (`Option` only for additive round-trip). Machine-surface authz
104 /// vocabulary — the human `status` reachability line is unchanged. Additive:
105 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub principal: Option<String>,
108}
109
110/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
111/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
112/// as-transport-vocab. Absent in a pure-pairing daemon.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct RosterStatus {
115 pub org_id: String,
116 pub serial: u64,
117 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
118 pub org_root_fingerprint: String, // short-word form
119}
120
121/// One reachable roster peer device as reported by `status` (the advisory presence read).
122/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
123/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
124/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PresencePeer {
127 pub user_id: String,
128 pub device_label: String,
129 pub role: String, // "primary" | "mirror" (roster vocabulary)
130 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
131 pub online: bool,
132 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
133 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
134 /// data; never an authz input. Additive: default + skip-if-empty.
135 #[serde(default, skip_serializing_if = "String::is_empty")]
136 pub meta: String,
137}
138
139/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
140/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
141/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
142/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
143/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
144/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
145/// an epoch — never an EndpointId.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct RecentPairing {
148 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
149 pub peer_nickname: String,
150 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
151 /// `PairResult.sas_code` carried. Never checked programmatically.
152 pub sas_code: String,
153 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
154 pub paired_at_epoch: u64,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct StatusResult {
159 pub stack_version: String,
160 pub services: Vec<ServiceInfo>,
161 pub peers: Vec<PeerInfo>,
162 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
163 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub roster: Option<RosterStatus>,
166 /// The reachable roster peer devices (the advisory presence read), each with an `online`
167 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
168 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
169 #[serde(default, skip_serializing_if = "Vec::is_empty")]
170 pub presence: Vec<PresencePeer>,
171 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
172 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
173 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
174 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub self_user_id: Option<String>,
177 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
178 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
179 /// that has accepted no pairing since it started. Additive:
180 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
181 #[serde(default, skip_serializing_if = "Vec::is_empty")]
182 pub recent_pairings: Vec<RecentPairing>,
183 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
184 /// first probe completes. Additive: default + skip-if-empty.
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub reachability: Vec<PeerReachability>,
187 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
188 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
189 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
190 /// skip-if-empty so an older payload round-trips.
191 #[serde(default, skip_serializing_if = "String::is_empty")]
192 pub self_nickname: String,
193}
194
195/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct RegisterServiceParams {
199 pub name: String,
200 pub backend: BackendSpec,
201 pub allow: Vec<String>,
202 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
203 /// to the on-disk config, and automatically unregistered when the control connection that
204 /// registered it closes (and gone on daemon restart). For an embedder that serves a
205 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
206 /// socket path solely to keep a persisted registration valid, and the stale-registration
207 /// accumulation that comes with no unregister. Default false = the persistent behavior.
208 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
209 pub ephemeral: bool,
210}
211
212/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
213/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
214/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
215/// list (an invite that grants nothing is useless — #34).
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct InviteParams {
219 #[serde(default)]
220 pub services: Vec<String>,
221 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
222 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
223 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub app_label: Option<String>,
226}
227
228/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
229/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct PairParams {
233 #[serde(default)]
234 pub invite_line: String,
235}
236
237/// Params of [`Request::PeerRemove`]: the nickname to unpair.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(deny_unknown_fields)]
240pub struct PeerRemoveParams {
241 pub nickname: String,
242}
243
244/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
245/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct PeerRenameParams {
249 #[serde(default)]
250 pub user_id: Option<String>,
251 #[serde(default)]
252 pub nickname: Option<String>,
253 pub to: String,
254}
255
256/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
257/// (iroh base32) plus the nickname and service allow list to install it under.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct PeerAddParams {
261 pub nickname: String,
262 pub endpoint_id: String,
263 #[serde(default)]
264 pub allow: Vec<String>,
265}
266
267/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
268/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct OpenSessionParams {
272 #[serde(default)]
273 pub peer: String,
274 #[serde(default)]
275 pub service: String,
276}
277
278/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
279/// on FIRST install (`b64u:`; omit once pinned — config carries it).
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(deny_unknown_fields)]
282pub struct RosterInstallParams {
283 pub path: String,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub org_root_pk: Option<String>,
286}
287
288/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
289/// never crosses the API.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292pub struct OrgJoinParams {
293 pub org_id: String,
294 pub org_root_pk: String,
295 pub user_id: String,
296 pub user_key: String,
297}
298
299/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
300/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
301/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
302/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct SetAppMetadataParams {
306 pub metadata: String,
307}
308
309/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
310/// principal, or a `b64u:` user_id.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct PeerServicesParams {
314 pub peer: String,
315}
316
317/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
318/// caller — computed authoritatively on the peer (which owns the truth), always current, only
319/// the caller's own admitted services (never the peer's full registry).
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321pub struct PeerServicesResult {
322 pub services: Vec<String>,
323}
324
325/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
326/// to remove — the deregistration mirror of `register_service`.
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(deny_unknown_fields)]
329pub struct UnregisterServiceParams {
330 pub name: String,
331}
332
333/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
334/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
335/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338pub struct ServiceAllowParams {
339 pub service: String,
340 pub principal: String,
341}
342
343/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
344/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
345/// they stored at pairing time until a re-invite.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(deny_unknown_fields)]
348pub struct SetNicknameParams {
349 pub nickname: String,
350}
351
352/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(deny_unknown_fields)]
355pub struct SetRosterUrlParams {
356 pub url: String,
357}
358
359/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
360/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
361/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
362/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
363/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
364/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
365/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
366/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct SetRelaysParams {
370 pub relay_urls: Vec<String>,
371}
372
373/// Result of [`Request::SetRelays`] (#53).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375pub struct SetRelaysResult {
376 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
377 pub changed: bool,
378 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
379 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
380 /// live custom→custom path (already applied to the running endpoint).
381 pub restart_required: bool,
382}
383
384/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(deny_unknown_fields)]
387pub struct BlobPublishParams {
388 pub scope: String,
389 pub path: String,
390}
391
392/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394#[serde(deny_unknown_fields)]
395pub struct BlobGrantParams {
396 pub scope: String,
397 pub principal: String,
398}
399
400/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
401#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
402#[serde(deny_unknown_fields)]
403pub struct BlobFetchParams {
404 pub ticket: String,
405 pub dest_path: String,
406}
407
408/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
409/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
410///
411/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
412/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
413/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
414/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
415/// identical to inline variant bodies.
416///
417/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
418/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
419/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
420/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
421/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(tag = "method", content = "params", rename_all = "snake_case")]
424pub enum Request {
425 /// Register/update a `[services.*]` entry idempotently.
426 RegisterService(RegisterServiceParams),
427 Status,
428 /// Mint a one-time pairing invite granting `services`. The daemon
429 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
430 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
431 /// `method` string generically; the tag comes from `rename_all`.
432 Invite(InviteParams),
433 /// Redeem a pairing invite. The daemon dials the inviter named by
434 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
435 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
436 /// (snake_case); `method_of` reads the `method` string generically.
437 ///
438 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
439 Pair(PairParams),
440 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
441 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
442 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
443 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
444 /// NOT severed here: existing sessions run to completion; the peer only loses the
445 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
446 /// `method_of` reads the `method` string generically (no per-variant arm).
447 ///
448 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
449 PeerRemove(PeerRemoveParams),
450 /// Rename a contact's nickname (nickname) authoritatively. Renames the
451 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
452 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
453 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
454 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
455 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
456 /// host-privileged like the other pair ops.
457 PeerRename(PeerRenameParams),
458 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
459 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
460 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
461 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
462 /// vocabulary — do not build on it. Tag `"peer_add"`.
463 PeerAdd(PeerAddParams),
464 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
465 /// Distinct from the proxy's job: this returns a session the client streams.
466 /// Named `open_session` rather than `connect` to avoid colliding
467 /// with the `connect` porcelain.
468 OpenSession(OpenSessionParams),
469 /// Install a signed roster from a local file (the manual `internal roster install` path).
470 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
471 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
472 /// pins the org root on FIRST install (`b64u:`); omit it
473 /// once pinned (config carries it). Tag `"roster_install"`.
474 RosterInstall(RosterInstallParams),
475 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
476 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
477 /// `user_key` is a LOCAL path
478 /// (the key never crosses the API). Tag `"org_join"`.
479 OrgJoin(OrgJoinParams),
480 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
481 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
482 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
483 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
484 /// `"set_roster_url"`.
485 SetRosterUrl(SetRosterUrlParams),
486 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
487 /// daemon's own serialized config-write path (no lost-update window against a
488 /// concurrent grant/registration) and update the in-memory name future invites
489 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
490 SetNickname(SetNicknameParams),
491 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
492 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
493 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
494 /// on restart; the embedder re-sets on startup).
495 SetAppMetadata(SetAppMetadataParams),
496 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
497 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
498 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
499 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
500 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
501 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
502 /// [`SetRelaysResult`]. Tag `"set_relays"`.
503 SetRelays(SetRelaysParams),
504 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
505 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
506 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
507 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
508 /// hot-reloads. Idempotent. Ack result.
509 UnregisterService(UnregisterServiceParams),
510 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
511 /// and returns the service names whose allow admits the caller's principal. Answers
512 /// [`PeerServicesResult`].
513 PeerServices(PeerServicesParams),
514 ServiceAllowGrant(ServiceAllowParams),
515 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
516 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
517 /// Idempotent. Ack result.
518 ServiceAllowRevoke(ServiceAllowParams),
519 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
520 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
521 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
522 /// Tag `"blob_publish"`.
523 BlobPublish(BlobPublishParams),
524 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
525 /// nickname (the shared `principal_set` expansion). Tag
526 /// `"blob_grant"`.
527 BlobGrant(BlobGrantParams),
528 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
529 BlobList,
530 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
531 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
532 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
533 BlobFetch(BlobFetchParams),
534 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
535 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
536 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
537 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
538 /// `method_of` reads the `method` string generically (no per-variant arm).
539 AuditSummary,
540 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
541 /// connection STOPS being request/response after this call and becomes a one-way push stream
542 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
543 Subscribe,
544}
545
546/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
547/// computed porcelain-side from the invite's org_root_pk). Additive-only.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549pub struct OrgJoinResult {
550 pub org_id: String,
551}
552
553/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
554/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
555/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
556///
557/// Additive-only: any future field MUST land as
558/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
560pub struct RosterInstallResult {
561 pub org_id: String,
562 pub serial: u64,
563 /// How many live sessions were severed, for the porcelain's confirmation line.
564 #[serde(default)]
565 pub severed: u32,
566}
567
568/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
569/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
570/// carve-out as the pairing invite line). Additive-only.
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct BlobPublishResult {
573 pub ticket: String,
574 pub hash: String, // bare blake3 hex
575}
576
577/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
578/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580pub struct ScopeInfo {
581 pub name: String,
582 pub hashes: Vec<String>,
583 pub grants: Vec<String>,
584}
585
586/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
587#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
588pub struct BlobScopeList {
589 pub scopes: Vec<ScopeInfo>,
590}
591
592/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
593/// Additive-only.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595pub struct BlobFetchResult {
596 pub hash: String,
597 pub bytes_len: u64,
598}
599
600/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
601/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
602/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
603/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
604/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
605/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
606///
607/// Additive-only: any future field MUST land as
608/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610pub struct AuditSummaryResult {
611 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
612 /// peer to attribute) but IS in `total_sessions`.
613 pub per_peer: Vec<(String, u64)>,
614 /// Sessions opened per registered service name.
615 pub per_service: Vec<(String, u64)>,
616 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
617 #[serde(default)]
618 pub total_sessions: u64,
619}
620
621/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
622/// (the ONE pairing artifact deliberately carved out of the
623/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
624/// absolute expiry in epoch seconds (≤ now + 24h).
625///
626/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
627/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
628/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
629/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
630/// ceremony" note in `docs/local-protocol.md` (#35).
631///
632/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
633/// so older payloads still deserialize.
634#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
635pub struct InviteResult {
636 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
637 pub invite_line: String,
638 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
639 pub expires_at_epoch: u64,
640}
641
642/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
643/// redeemer's local name for the new peer) plus the display-only short authentication
644/// code (SAS) — a few words the human reads aloud to a second channel to
645/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
646/// artifact (like the invite line), NOT a transport-vocabulary leak.
647///
648/// Additive-only: any future field MUST land as
649/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
650#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
651pub struct PairResult {
652 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
653 pub peer_nickname: String,
654 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
655 /// sides for the out-of-band human check. Never sent on the wire, never checked
656 /// programmatically.
657 pub sas_code: String,
658 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
659 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
660 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
661 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
662 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
663 #[serde(default, skip_serializing_if = "Vec::is_empty")]
664 pub services: Vec<String>,
665 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
666 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub app_label: Option<String>,
669 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
670 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
671 /// can align with its own — and the same value it may later pass to `open_session` to dial
672 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
673 /// binding (a legacy/keyless peer). Additive.
674 #[serde(default, skip_serializing_if = "Option::is_none")]
675 pub peer_user_id: Option<String>,
676}
677
678/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
679/// top of the base record schema: it removes no field and makes the JSONL self-describing so
680/// a consumer can filter by class without guessing from which optional fields are present.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682#[serde(rename_all = "snake_case")]
683pub enum AuditKind {
684 /// A mesh session opened (a backend was selected for an authenticated peer).
685 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
686 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
687 SessionOpen,
688 /// A mesh session closed (the backend returned / the session tore down).
689 SessionClose,
690 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
691 Request,
692 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
693 BlobFetch,
694 /// A trust mutation (pair, unpair, roster install/swap, revoke).
695 Trust,
696}
697
698/// One audit record — the union of the event classes, and the `record` payload of a
699/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
700/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
701/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
702/// `bytes_out`).
703///
704/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
705/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
706/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
707#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
708pub struct AuditRecord {
709 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
710 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
711 pub ts: String,
712 pub kind: AuditKind,
713 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
714 /// local-only events with no remote peer (a manual roster install).
715 #[serde(skip_serializing_if = "Option::is_none")]
716 pub peer: Option<String>,
717 #[serde(skip_serializing_if = "Option::is_none")]
718 pub service: Option<String>,
719 #[serde(skip_serializing_if = "Option::is_none")]
720 pub method: Option<String>,
721 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
722 #[serde(skip_serializing_if = "Option::is_none")]
723 pub tool: Option<String>,
724 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
725 #[serde(skip_serializing_if = "Option::is_none")]
726 pub args_hash: Option<String>,
727 /// Byte COUNT of the response sent back to the peer — a count, never the content.
728 #[serde(skip_serializing_if = "Option::is_none")]
729 pub bytes_out: Option<u64>,
730 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
731 #[serde(skip_serializing_if = "Option::is_none")]
732 pub status: Option<String>,
733 #[serde(skip_serializing_if = "Option::is_none")]
734 pub latency_ms: Option<u64>,
735 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
736 #[serde(skip_serializing_if = "Option::is_none")]
737 pub event: Option<String>,
738 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
739 /// nickname or `org/serial` (`Trust`).
740 #[serde(skip_serializing_if = "Option::is_none")]
741 pub target: Option<String>,
742}
743
744impl AuditRecord {
745 fn base(ts: String, kind: AuditKind) -> Self {
746 Self {
747 ts,
748 kind,
749 peer: None,
750 service: None,
751 method: None,
752 tool: None,
753 args_hash: None,
754 bytes_out: None,
755 status: None,
756 latency_ms: None,
757 event: None,
758 target: None,
759 }
760 }
761
762 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
763 let mut r = Self::base(ts, AuditKind::SessionOpen);
764 r.peer = peer;
765 r.service = Some(service);
766 r
767 }
768
769 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
770 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
771 /// reaches no backend and so is never audited by the far side's session guard — without a
772 /// dedicated constructor. DRY: reuses the existing optional `status` field.
773 pub fn with_status(mut self, status: &str) -> Self {
774 self.status = Some(status.into());
775 self
776 }
777
778 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
779 let mut r = Self::base(ts, AuditKind::SessionClose);
780 r.peer = peer;
781 r.service = Some(service);
782 r
783 }
784
785 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
786 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
787 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
788 #[allow(clippy::too_many_arguments)]
789 pub fn proxied_request(
790 ts: String,
791 peer: Option<String>,
792 service: String,
793 method: String,
794 tool: Option<String>,
795 args_hash: String,
796 bytes_out: u64,
797 status: String,
798 latency_ms: u64,
799 ) -> Self {
800 let mut r = Self::base(ts, AuditKind::Request);
801 r.peer = peer;
802 r.service = Some(service);
803 r.method = Some(method);
804 r.tool = tool;
805 r.args_hash = Some(args_hash);
806 r.bytes_out = Some(bytes_out);
807 r.status = Some(status);
808 r.latency_ms = Some(latency_ms);
809 r
810 }
811
812 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
813 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
814 pub fn proxied_notification(
815 ts: String,
816 peer: Option<String>,
817 service: String,
818 method: String,
819 tool: Option<String>,
820 args_hash: String,
821 ) -> Self {
822 let mut r = Self::base(ts, AuditKind::Request);
823 r.peer = peer;
824 r.service = Some(service);
825 r.method = Some(method);
826 r.tool = tool;
827 r.args_hash = Some(args_hash);
828 r
829 }
830
831 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
832 let mut r = Self::base(ts, AuditKind::BlobFetch);
833 r.peer = peer;
834 r.target = Some(hash);
835 r.status = Some(status);
836 r
837 }
838
839 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
840 let mut r = Self::base(ts, AuditKind::Trust);
841 r.event = Some(event);
842 r.target = target;
843 r
844 }
845}
846
847/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
848/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
850pub struct ActiveSession {
851 pub peer: String,
852 pub service: String,
853 pub opened_at: i64,
854}
855
856/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
857/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
858/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
859/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
860/// them (see `docs/local-protocol.md` "Live event stream").
861#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
862#[serde(tag = "type", rename_all = "snake_case")]
863pub enum StreamFrame {
864 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
865 /// reachability) so a fresh subscriber renders immediately without replaying history.
866 Snapshot {
867 active_sessions: Vec<ActiveSession>,
868 reachability: Vec<PeerReachability>,
869 },
870 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
871 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
872 /// `Box`, so the wire shape is the record's fields verbatim.
873 Event { record: Box<AuditRecord> },
874 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
875 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
876 Lagged { dropped: u64 },
877}
878
879/// Extract the `method` tag from a raw request value without deserializing the whole
880/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
881/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
882/// methods (adjacent tagging rejects `params:{}` on unit variants).
883pub fn method_of(v: &serde_json::Value) -> Option<&str> {
884 v.get("method").and_then(serde_json::Value::as_str)
885}
886
887/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
888/// Config→BackendSpec is a hand-written match, not a serde passthrough.
889#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
890#[serde(rename_all = "snake_case")]
891pub enum BackendSpec {
892 Run {
893 cmd: Vec<String>,
894 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
895 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
896 /// these (identity is not spoofable by a service definition). Default empty.
897 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
898 env: BTreeMap<String, String>,
899 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
900 #[serde(default, skip_serializing_if = "Option::is_none")]
901 cwd: Option<String>,
902 },
903 Socket {
904 path: String,
905 },
906}
907
908pub const API_NAME: &str = "mcpmesh-local/1";
909/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
910///
911/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
912/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
913/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
914/// new methods, or a strictness change like params validation — bumped in the same change that
915/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
916/// older than a minor it requires. It never resets except on a MAJOR bump.
917pub const API_VERSION: &str = "1.10";
918/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
919/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
920/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
921/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
922/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
923/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
924/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
925/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
926/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
927/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
928/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
929/// observable contract did: a revoked principal's next session is refused even on a connection it
930/// already holds, and its live connections are severed. Previously both waited for the peer to
931/// disconnect on its own, which is unbounded (#54). A consumer can guard on
932/// `api_minor >= 10` before telling a user that revocation has taken effect.
933pub const API_MINOR: u32 = 10;
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938
939 #[test]
940 fn peer_reachability_serde_is_additive() {
941 let r = PeerReachability {
942 name: "bob".into(),
943 reachable: true,
944 rtt_ms: Some(42),
945 age_secs: Some(3),
946 meta: String::new(),
947 principal: None,
948 };
949 let v = serde_json::to_value(&r).unwrap();
950 assert_eq!(v["name"], "bob");
951 assert_eq!(v["reachable"], true);
952 assert_eq!(v["rtt_ms"], 42);
953 assert_eq!(v["age_secs"], 3);
954 // Never-probed peer: optionals elided, not null.
955 let unknown = PeerReachability {
956 name: "carol".into(),
957 reachable: false,
958 rtt_ms: None,
959 age_secs: None,
960 meta: String::new(),
961 principal: None,
962 };
963 let uv = serde_json::to_value(&unknown).unwrap();
964 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
965 // An older StatusResult (no reachability field) still deserializes.
966 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
967 let s: StatusResult = serde_json::from_value(old).unwrap();
968 assert!(s.reachability.is_empty());
969 }
970
971 #[test]
972 fn subscribe_method_tag_resolves() {
973 let req = serde_json::to_value(Request::Subscribe).unwrap();
974 assert_eq!(method_of(&req), Some("subscribe"));
975 }
976
977 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
978
979 #[test]
980 fn invite_params_reject_singular_service_typo() {
981 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
982 // InviteParams { services: [] } and mint a grants-nothing invite that looked
983 // successful. With deny_unknown_fields the typo is a loud parse error instead.
984 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
985 assert!(
986 err.is_err(),
987 "an unknown `service` key must be rejected, not silently ignored"
988 );
989 // The correct plural shape still parses.
990 let ok: InviteParams =
991 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
992 assert_eq!(ok.services, vec!["kb".to_string()]);
993 }
994
995 #[test]
996 fn open_session_params_reject_unknown_field() {
997 let err = serde_json::from_value::<OpenSessionParams>(
998 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
999 );
1000 assert!(err.is_err(), "unknown params keys must be rejected");
1001 }
1002
1003 #[test]
1004 fn set_app_metadata_request_carries_the_method_tag() {
1005 let r = Request::SetAppMetadata(SetAppMetadataParams {
1006 metadata: "v=1.2.3".into(),
1007 });
1008 let v = serde_json::to_value(&r).unwrap();
1009 assert_eq!(v["method"], "set_app_metadata");
1010 assert_eq!(v["params"]["metadata"], "v=1.2.3");
1011 assert_eq!(method_of(&v), Some("set_app_metadata"));
1012 }
1013
1014 #[test]
1015 fn set_app_metadata_params_reject_unknown_field() {
1016 let err = serde_json::from_value::<SetAppMetadataParams>(
1017 serde_json::json!({"metadata": "x", "nonsense": 1}),
1018 );
1019 assert!(err.is_err(), "unknown params keys must be rejected");
1020 }
1021
1022 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1023 /// empty meta does not serialize.
1024 #[test]
1025 fn peer_info_principal_is_additive() {
1026 // An older payload (no principal) still deserializes; empty does not serialize.
1027 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1028 let p: PeerInfo = serde_json::from_value(old).unwrap();
1029 assert_eq!(p.principal, None);
1030 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1031 // A bound peer carries BOTH the person user_id AND the device principal (#41).
1032 let full = PeerInfo {
1033 name: "bob".into(),
1034 services: vec!["notes".into()],
1035 user_id: Some("b64u:BOB".into()),
1036 principal: Some("eid:0707".into()),
1037 };
1038 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1039 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1040 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1041 }
1042
1043 #[test]
1044 fn peer_reachability_principal_is_additive() {
1045 // Older payload (no principal) still deserializes; empty does not serialize; a set
1046 // value round-trips alongside the #40 meta so an embedder joins on the principal.
1047 let old = serde_json::json!({"name": "bob", "reachable": true});
1048 let r: PeerReachability = serde_json::from_value(old).unwrap();
1049 assert_eq!(r.principal, None);
1050 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1051 let full = PeerReachability {
1052 name: "bob".into(),
1053 reachable: true,
1054 rtt_ms: Some(12),
1055 age_secs: Some(3),
1056 meta: "v=1.2.3".into(),
1057 principal: Some("eid:0707".into()),
1058 };
1059 let back: PeerReachability =
1060 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1061 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1062 assert_eq!(back.meta, "v=1.2.3");
1063 }
1064
1065 #[test]
1066 fn peer_reachability_meta_is_additive() {
1067 // An older payload (no meta) still deserializes; an empty meta does not serialize.
1068 let old = serde_json::json!({"name": "bob", "reachable": true});
1069 let r: PeerReachability = serde_json::from_value(old).unwrap();
1070 assert_eq!(r.meta, "");
1071 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1072 // A set value round-trips.
1073 let with = PeerReachability {
1074 name: "bob".into(),
1075 reachable: true,
1076 rtt_ms: Some(12),
1077 age_secs: Some(3),
1078 meta: "v=1.2.3".into(),
1079 principal: None,
1080 };
1081 let back: PeerReachability =
1082 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1083 assert_eq!(back.meta, "v=1.2.3");
1084 }
1085
1086 #[test]
1087 fn presence_peer_meta_is_additive() {
1088 let old = serde_json::json!({
1089 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1090 });
1091 let p: PresencePeer = serde_json::from_value(old).unwrap();
1092 assert_eq!(p.meta, "");
1093 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1094 }
1095
1096 #[test]
1097 fn set_nickname_request_carries_the_method_tag() {
1098 let r = Request::SetNickname(SetNicknameParams {
1099 nickname: "workbench".into(),
1100 });
1101 let v = serde_json::to_value(&r).unwrap();
1102 assert_eq!(v["method"], "set_nickname");
1103 assert_eq!(v["params"]["nickname"], "workbench");
1104 assert_eq!(method_of(&v), Some("set_nickname"));
1105 }
1106
1107 #[test]
1108 fn set_nickname_params_reject_unknown_field() {
1109 let err = serde_json::from_value::<SetNicknameParams>(
1110 serde_json::json!({"nickname": "x", "nonsense": 1}),
1111 );
1112 assert!(err.is_err(), "unknown params keys must be rejected");
1113 }
1114
1115 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1116 /// the additive-only contract — and an empty name must not serialize at all.
1117 #[test]
1118 fn status_self_nickname_is_additive() {
1119 let old = serde_json::json!({
1120 "stack_version": "0.7.0", "services": [], "peers": []
1121 });
1122 let s: StatusResult = serde_json::from_value(old).unwrap();
1123 assert_eq!(s.self_nickname, "");
1124 let v = serde_json::to_value(&s).unwrap();
1125 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1126 }
1127
1128 #[test]
1129 fn api_minor_is_present_and_monotonic_from_hello() {
1130 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1131 // crate/stack version, additive on the Hello frame.
1132 let h = Hello {
1133 api: API_NAME.into(),
1134 api_version: API_VERSION.into(),
1135 api_minor: API_MINOR,
1136 stack_version: "9.9.9".into(),
1137 };
1138 let v = serde_json::to_value(&h).unwrap();
1139 assert_eq!(v["api_minor"], API_MINOR);
1140 // An OLD Hello without api_minor still deserializes (additive contract).
1141 let old = serde_json::json!({
1142 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1143 });
1144 let back: Hello = serde_json::from_value(old).unwrap();
1145 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1146 }
1147
1148 #[test]
1149 fn hello_result_roundtrips() {
1150 let h = Hello {
1151 api: "mcpmesh-local/1".into(),
1152 api_version: "1.0".into(),
1153 api_minor: 0,
1154 stack_version: "0.1.0".into(),
1155 };
1156 let v = serde_json::to_value(&h).unwrap();
1157 assert_eq!(v["api"], "mcpmesh-local/1");
1158 let back: Hello = serde_json::from_value(v).unwrap();
1159 assert_eq!(back, h);
1160 }
1161
1162 #[test]
1163 fn request_tagged_by_method() {
1164 let r = Request::Status;
1165 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1166 let r = Request::OpenSession(OpenSessionParams {
1167 peer: "alice".into(),
1168 service: "notes".into(),
1169 });
1170 let v = serde_json::to_value(&r).unwrap();
1171 assert_eq!(v["method"], "open_session");
1172 assert_eq!(v["params"]["peer"], "alice");
1173 }
1174
1175 #[test]
1176 fn parameterless_method_tolerates_params_forms() {
1177 // Omitted and null params deserialize straight into the unit variant.
1178 let omitted: Request =
1179 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1180 assert_eq!(omitted, Request::Status);
1181 let null: Request =
1182 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1183 .unwrap();
1184 assert_eq!(null, Request::Status);
1185
1186 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1187 // the server MUST dispatch on the method string rather than deserialize the whole
1188 // message into `Request`. This is the pattern the daemon's dispatcher uses.
1189 let empty = serde_json::json!({"method": "status", "params": {}});
1190 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1191 match method_of(&empty) {
1192 Some("status") => {} // dispatcher resolves Status via the method string
1193 other => panic!("method_of failed to resolve status: {other:?}"),
1194 }
1195 }
1196
1197 #[test]
1198 fn backend_spec_roundtrips() {
1199 let run = BackendSpec::Run {
1200 cmd: vec!["notes-mcp".into(), "--stdio".into()],
1201 env: Default::default(),
1202 cwd: None,
1203 };
1204 let v = serde_json::to_value(&run).unwrap();
1205 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1206 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1207
1208 let sock = BackendSpec::Socket {
1209 path: "/run/notes.sock".into(),
1210 };
1211 let v = serde_json::to_value(&sock).unwrap();
1212 assert_eq!(v["socket"]["path"], "/run/notes.sock");
1213 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1214 }
1215
1216 #[test]
1217 fn register_service_wire_shape() {
1218 let r = Request::RegisterService(RegisterServiceParams {
1219 name: "notes".into(),
1220 backend: BackendSpec::Run {
1221 cmd: vec!["notes-mcp".into()],
1222 env: Default::default(),
1223 cwd: None,
1224 },
1225 allow: vec!["alice".into()],
1226 ephemeral: false,
1227 });
1228 let v = serde_json::to_value(&r).unwrap();
1229 assert_eq!(
1230 v,
1231 serde_json::json!({
1232 "method": "register_service",
1233 "params": {
1234 "name": "notes",
1235 "backend": {"run": {"cmd": ["notes-mcp"]}},
1236 "allow": ["alice"],
1237 }
1238 })
1239 );
1240 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1241 }
1242
1243 #[test]
1244 fn invite_request_and_result_roundtrip() {
1245 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1246 let r = Request::Invite(InviteParams {
1247 services: vec!["notes".into(), "kb".into()],
1248 app_label: None,
1249 });
1250 let v = serde_json::to_value(&r).unwrap();
1251 assert_eq!(v["method"], "invite");
1252 assert_eq!(v["params"]["services"][0], "notes");
1253 assert_eq!(v["params"]["services"][1], "kb");
1254 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1255 // method_of resolves the tag generically (no per-variant arm).
1256 assert_eq!(
1257 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1258 Some("invite")
1259 );
1260
1261 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1262 let res = InviteResult {
1263 invite_line: "mcpmesh-invite:ABCDEF".into(),
1264 expires_at_epoch: 1_800_000_000,
1265 };
1266 let v = serde_json::to_value(&res).unwrap();
1267 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1268 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1269 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1270 }
1271
1272 #[test]
1273 fn pair_request_and_result_roundtrip() {
1274 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1275 let r = Request::Pair(PairParams {
1276 invite_line: "mcpmesh-invite:ABCDEF".into(),
1277 });
1278 let v = serde_json::to_value(&r).unwrap();
1279 assert_eq!(v["method"], "pair");
1280 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1281 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1282 // method_of resolves the tag generically (no per-variant arm).
1283 assert_eq!(
1284 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1285 Some("pair")
1286 );
1287
1288 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1289 // the granted services (the porcelain renders each as `<peer>/<service>`).
1290 let res = PairResult {
1291 peer_nickname: "alice".into(),
1292 sas_code: "tango-fig-cabbage".into(),
1293 services: vec!["notes".into(), "kb".into()],
1294 app_label: None,
1295 peer_user_id: None,
1296 };
1297 let v = serde_json::to_value(&res).unwrap();
1298 assert_eq!(v["peer_nickname"], "alice");
1299 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1300 assert_eq!(v["services"][0], "notes");
1301 assert_eq!(v["services"][1], "kb");
1302 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1303
1304 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1305 // deserializes — the `#[serde(default)]` fills it with an empty list.
1306 let old_shape = serde_json::json!({
1307 "peer_nickname": "alice",
1308 "sas_code": "tango-fig-cabbage",
1309 });
1310 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1311 assert_eq!(back.peer_nickname, "alice");
1312 assert!(back.services.is_empty());
1313 }
1314
1315 #[test]
1316 fn roster_install_request_and_result_roundtrip() {
1317 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1318 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1319 let r = Request::RosterInstall(RosterInstallParams {
1320 path: "/tmp/roster.json".into(),
1321 org_root_pk: Some("b64u:AAAA".into()),
1322 });
1323 let v = serde_json::to_value(&r).unwrap();
1324 assert_eq!(v["method"], "roster_install");
1325 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1326 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1327 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1328 // method_of resolves the tag generically (no per-variant arm).
1329 assert_eq!(
1330 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1331 Some("roster_install")
1332 );
1333
1334 // When the pk is omitted (a subsequent install using the pinned value), it is
1335 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1336 let omit = Request::RosterInstall(RosterInstallParams {
1337 path: "/tmp/roster.json".into(),
1338 org_root_pk: None,
1339 });
1340 let v = serde_json::to_value(&omit).unwrap();
1341 assert!(
1342 v["params"].get("org_root_pk").is_none(),
1343 "an omitted org_root_pk must not appear on the wire: {v}"
1344 );
1345 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1346
1347 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1348 let res = RosterInstallResult {
1349 org_id: "acme".into(),
1350 serial: 42,
1351 severed: 1,
1352 };
1353 let v = serde_json::to_value(&res).unwrap();
1354 assert_eq!(v["org_id"], "acme");
1355 assert_eq!(v["serial"], 42u64);
1356 assert_eq!(v["severed"], 1u32);
1357 assert_eq!(
1358 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1359 res
1360 );
1361
1362 // Additive-only: a result minted by an older daemon (no `severed` key) still
1363 // deserializes — the `#[serde(default)]` fills it with 0.
1364 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1365 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1366 assert_eq!(back.serial, 7);
1367 assert_eq!(back.severed, 0);
1368 }
1369
1370 #[test]
1371 fn org_join_request_and_result_roundtrip() {
1372 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1373 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1374 let r = Request::OrgJoin(OrgJoinParams {
1375 org_id: "acme".into(),
1376 org_root_pk: "b64u:AAAA".into(),
1377 user_id: "alice".into(),
1378 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1379 });
1380 let v = serde_json::to_value(&r).unwrap();
1381 assert_eq!(v["method"], "org_join");
1382 assert_eq!(v["params"]["org_id"], "acme");
1383 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1384 assert_eq!(v["params"]["user_id"], "alice");
1385 assert_eq!(
1386 v["params"]["user_key"],
1387 "/home/alice/.config/mcpmesh/user.key"
1388 );
1389 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1390 // method_of resolves the tag generically (no per-variant arm).
1391 assert_eq!(
1392 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1393 Some("org_join")
1394 );
1395
1396 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1397 let res = OrgJoinResult {
1398 org_id: "acme".into(),
1399 };
1400 let v = serde_json::to_value(&res).unwrap();
1401 assert_eq!(v["org_id"], "acme");
1402 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1403 }
1404
1405 #[test]
1406 fn set_roster_url_request_roundtrip() {
1407 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1408 let r = Request::SetRosterUrl(SetRosterUrlParams {
1409 url: "https://intranet.acme.com/roster.json".into(),
1410 });
1411 let v = serde_json::to_value(&r).unwrap();
1412 assert_eq!(v["method"], "set_roster_url");
1413 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1414 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1415 assert_eq!(
1416 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1417 Some("set_roster_url")
1418 );
1419 }
1420
1421 #[test]
1422 fn peer_remove_request_roundtrip() {
1423 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1424 let r = Request::PeerRemove(PeerRemoveParams {
1425 nickname: "bob".into(),
1426 });
1427 let v = serde_json::to_value(&r).unwrap();
1428 assert_eq!(v["method"], "peer_remove");
1429 assert_eq!(v["params"]["nickname"], "bob");
1430 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1431 // method_of resolves the tag generically (no per-variant arm).
1432 assert_eq!(
1433 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1434 Some("peer_remove")
1435 );
1436 }
1437
1438 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1439 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1440 /// defaulting to empty when absent.
1441 #[test]
1442 fn peer_add_request_roundtrip() {
1443 let r = Request::PeerAdd(PeerAddParams {
1444 nickname: "bob".into(),
1445 endpoint_id: "96246d3f".into(),
1446 allow: vec!["notes".into()],
1447 });
1448 let v = serde_json::to_value(&r).unwrap();
1449 assert_eq!(v["method"], "peer_add");
1450 assert_eq!(v["params"]["nickname"], "bob");
1451 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1452 assert_eq!(v["params"]["allow"][0], "notes");
1453 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1454 // An absent allow list deserializes to empty (the server-side tolerance).
1455 let p: PeerAddParams =
1456 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1457 .unwrap();
1458 assert!(p.allow.is_empty());
1459 }
1460
1461 #[test]
1462 fn peer_rename_request_roundtrip() {
1463 // By user_id (renames all of a person's devices in one op).
1464 let r = Request::PeerRename(PeerRenameParams {
1465 user_id: Some("b64u:BOB".into()),
1466 nickname: None,
1467 to: "Bobby".into(),
1468 });
1469 let v = serde_json::to_value(&r).unwrap();
1470 assert_eq!(v["method"], "peer_rename");
1471 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1472 assert_eq!(v["params"]["to"], "Bobby");
1473 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1474 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1475 assert_eq!(
1476 method_of(
1477 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1478 ),
1479 Some("peer_rename")
1480 );
1481 }
1482
1483 #[test]
1484 fn status_result_roundtrips() {
1485 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1486 // older payload with no `roster` key still deserializes to None (serde default).
1487 let s = StatusResult {
1488 stack_version: "0.1.0".into(),
1489 services: vec![ServiceInfo {
1490 name: "notes".into(),
1491 allow: vec!["alice".into()],
1492 allow_display: vec![],
1493 backend: BackendKind::Run,
1494 ephemeral: false,
1495 }],
1496 peers: vec![PeerInfo {
1497 name: "alice".into(),
1498 services: vec!["notes".into()],
1499 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1500 user_id: Some("b64u:alicepk".into()),
1501 principal: None,
1502 }],
1503 roster: None,
1504 presence: vec![],
1505 self_user_id: Some("b64u:selfpk".into()),
1506 recent_pairings: vec![],
1507 reachability: vec![],
1508 self_nickname: String::new(),
1509 };
1510 let v = serde_json::to_value(&s).unwrap();
1511 assert_eq!(v["services"][0]["backend"], "run");
1512 // The additive identity fields ride the wire when present.
1513 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1514 assert_eq!(v["self_user_id"], "b64u:selfpk");
1515 assert!(
1516 v.get("roster").is_none(),
1517 "an absent roster must not appear on the wire: {v}"
1518 );
1519 assert!(
1520 v.get("presence").is_none(),
1521 "an empty presence must not appear on the wire: {v}"
1522 );
1523 assert!(
1524 v.get("recent_pairings").is_none(),
1525 "an empty recent_pairings must not appear on the wire: {v}"
1526 );
1527 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1528
1529 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1530 // deserializes — the identity fields default to None / a nickname-only peer.
1531 let old_shape = serde_json::json!({
1532 "stack_version": "0.1.0",
1533 "services": [],
1534 "peers": [{ "name": "bob", "services": [] }],
1535 });
1536 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1537 assert!(back.roster.is_none());
1538 assert!(back.presence.is_empty());
1539 assert!(back.self_user_id.is_none());
1540 assert!(back.peers[0].user_id.is_none());
1541 assert!(back.recent_pairings.is_empty());
1542
1543 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1544 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1545 let s = StatusResult {
1546 stack_version: "0.1.0".into(),
1547 services: vec![],
1548 peers: vec![],
1549 roster: Some(RosterStatus {
1550 org_id: "acme".into(),
1551 serial: 42,
1552 state: "approved".into(),
1553 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1554 }),
1555 presence: vec![
1556 PresencePeer {
1557 user_id: "alice".into(),
1558 device_label: "laptop".into(),
1559 role: "primary".into(),
1560 online: true,
1561 meta: String::new(),
1562 },
1563 PresencePeer {
1564 user_id: "alice".into(),
1565 device_label: "desktop".into(),
1566 role: "mirror".into(),
1567 online: false,
1568 meta: String::new(),
1569 },
1570 ],
1571 self_user_id: None,
1572 recent_pairings: vec![],
1573 reachability: vec![],
1574 self_nickname: String::new(),
1575 };
1576 let v = serde_json::to_value(&s).unwrap();
1577 assert_eq!(v["roster"]["org_id"], "acme");
1578 assert_eq!(v["roster"]["serial"], 42u64);
1579 assert_eq!(v["roster"]["state"], "approved");
1580 assert_eq!(
1581 v["roster"]["org_root_fingerprint"],
1582 "tango-fig-cabbage-anchor"
1583 );
1584 assert_eq!(v["presence"][0]["user_id"], "alice");
1585 assert_eq!(v["presence"][0]["device_label"], "laptop");
1586 assert_eq!(v["presence"][0]["role"], "primary");
1587 assert_eq!(v["presence"][0]["online"], true);
1588 assert_eq!(v["presence"][1]["online"], false);
1589 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1590 }
1591
1592 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1593 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1594 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1595 /// older daemon (no key at all) still deserializes to empty.
1596 #[test]
1597 fn recent_pairings_are_additive_on_status() {
1598 let s = StatusResult {
1599 stack_version: "0.1.0".into(),
1600 services: vec![],
1601 peers: vec![],
1602 roster: None,
1603 presence: vec![],
1604 self_user_id: None,
1605 recent_pairings: vec![RecentPairing {
1606 peer_nickname: "bob".into(),
1607 sas_code: "tango-fig-cabbage".into(),
1608 paired_at_epoch: 1_800_000_000,
1609 }],
1610 reachability: vec![],
1611 self_nickname: String::new(),
1612 };
1613 let v = serde_json::to_value(&s).unwrap();
1614 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1615 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1616 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1617 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1618
1619 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1620 // the `#[serde(default)]` fills it with an empty list.
1621 let old_shape = serde_json::json!({
1622 "stack_version": "0.1.0",
1623 "services": [],
1624 "peers": [],
1625 });
1626 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1627 assert!(back.recent_pairings.is_empty());
1628 }
1629
1630 #[test]
1631 fn blob_requests_and_results_roundtrip() {
1632 // BlobPublish → { method, params: { scope, path } }.
1633 let r = Request::BlobPublish(BlobPublishParams {
1634 scope: "docs".into(),
1635 path: "/tmp/a.bin".into(),
1636 });
1637 let v = serde_json::to_value(&r).unwrap();
1638 assert_eq!(v["method"], "blob_publish");
1639 assert_eq!(v["params"]["scope"], "docs");
1640 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1641 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1642
1643 // BlobGrant → { method, params: { scope, principal } }.
1644 let r = Request::BlobGrant(BlobGrantParams {
1645 scope: "docs".into(),
1646 principal: "alice".into(),
1647 });
1648 let v = serde_json::to_value(&r).unwrap();
1649 assert_eq!(v["method"], "blob_grant");
1650 assert_eq!(v["params"]["principal"], "alice");
1651 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1652
1653 // BlobList is parameterless (method_of resolves it).
1654 assert_eq!(
1655 method_of(&serde_json::json!({"method": "blob_list"})),
1656 Some("blob_list")
1657 );
1658
1659 // BlobFetch → { method, params: { ticket, dest_path } }.
1660 let r = Request::BlobFetch(BlobFetchParams {
1661 ticket: "blobAAA".into(),
1662 dest_path: "/tmp/out.bin".into(),
1663 });
1664 let v = serde_json::to_value(&r).unwrap();
1665 assert_eq!(v["method"], "blob_fetch");
1666 assert_eq!(v["params"]["ticket"], "blobAAA");
1667 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1668 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1669
1670 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1671 let res = BlobPublishResult {
1672 ticket: "blobAAA".into(),
1673 hash: "ab".repeat(32),
1674 };
1675 let v = serde_json::to_value(&res).unwrap();
1676 assert_eq!(v["ticket"], "blobAAA");
1677 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1678
1679 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1680 let res = BlobScopeList {
1681 scopes: vec![ScopeInfo {
1682 name: "docs".into(),
1683 hashes: vec!["ab".repeat(32)],
1684 grants: vec!["alice".into()],
1685 }],
1686 };
1687 let v = serde_json::to_value(&res).unwrap();
1688 assert_eq!(v["scopes"][0]["name"], "docs");
1689 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1690 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1691
1692 // BlobFetchResult carries the verified hash + byte length.
1693 let res = BlobFetchResult {
1694 hash: "ab".repeat(32),
1695 bytes_len: 4194304,
1696 };
1697 let v = serde_json::to_value(&res).unwrap();
1698 assert_eq!(v["bytes_len"], 4194304u64);
1699 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1700 }
1701
1702 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1703 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1704 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1705 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1706 #[test]
1707 fn stream_frames_roundtrip_with_the_documented_tags() {
1708 let snap = StreamFrame::Snapshot {
1709 active_sessions: vec![ActiveSession {
1710 peer: "bob".into(),
1711 service: "notes".into(),
1712 opened_at: 1_751_760_000,
1713 }],
1714 reachability: vec![PeerReachability {
1715 name: "bob".into(),
1716 reachable: true,
1717 rtt_ms: Some(42),
1718 age_secs: Some(3),
1719 meta: String::new(),
1720 principal: None,
1721 }],
1722 };
1723 let v = serde_json::to_value(&snap).unwrap();
1724 assert_eq!(v["type"], "snapshot");
1725 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1726 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1727 assert_eq!(v["reachability"][0]["name"], "bob");
1728 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1729
1730 let event = StreamFrame::Event {
1731 record: Box::new(AuditRecord::session_open(
1732 "2026-07-03T14:02:11.480Z".into(),
1733 Some("bob".into()),
1734 "notes".into(),
1735 )),
1736 };
1737 let v = serde_json::to_value(&event).unwrap();
1738 assert_eq!(v["type"], "event");
1739 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1740 assert_eq!(v["record"]["kind"], "session_open");
1741 assert_eq!(v["record"]["peer"], "bob");
1742 assert_eq!(v["record"]["service"], "notes");
1743 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1744
1745 let lagged = StreamFrame::Lagged { dropped: 12 };
1746 let v = serde_json::to_value(&lagged).unwrap();
1747 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1748 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1749 }
1750
1751 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1752 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1753 /// raw `Value` stream instead (`ControlClient::open_stream`).
1754 #[test]
1755 fn unknown_stream_frame_type_is_rejected() {
1756 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1757 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1758 }
1759
1760 #[test]
1761 fn audit_summary_request_and_result_roundtrip() {
1762 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1763 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1764 let r = Request::AuditSummary;
1765 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1766 assert_eq!(
1767 method_of(&serde_json::json!({"method": "audit_summary"})),
1768 Some("audit_summary")
1769 );
1770
1771 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1772 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1773 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1774 let res = AuditSummaryResult {
1775 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1776 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1777 total_sessions: 4,
1778 };
1779 let v = serde_json::to_value(&res).unwrap();
1780 assert_eq!(v["per_peer"][1][0], "bob");
1781 assert_eq!(v["per_peer"][1][1], 2u64);
1782 assert_eq!(v["per_service"][1][0], "notes");
1783 assert_eq!(v["total_sessions"], 4u64);
1784 assert_eq!(
1785 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1786 res
1787 );
1788
1789 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1790 // deserializes — the `#[serde(default)]` fills it with 0.
1791 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1792 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1793 assert_eq!(back.total_sessions, 0);
1794 assert!(back.per_peer.is_empty());
1795 }
1796}