mcpmesh_local_api/client.rs
1//! A no-iroh mcpmesh-local/1 client: connect the UDS, read the server's `Hello`
2//! first frame, assert the api name, then issue typed request/response frames. Distinct
3//! from the CLI crate (`cli/`)'s ControlClient (which uses mcpmesh_net::framing) — this one links no
4//! iroh, so kb and the host shell can use it. kb calls this to self-register
5//! its `[services.kb]` socket backend with the running mcpmesh daemon.
6use std::path::Path;
7
8use serde_json::Value;
9
10use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES, write_frame};
11use crate::protocol::{
12 AuditSummaryResult, BackendSpec, BlobFetchCancelParams, BlobFetchCancelResult, BlobFetchParams,
13 BlobFetchResult, BlobGrantParams, BlobPublishParams, BlobPublishResult, BlobScopeList, Hello,
14 InviteParams, InviteResult, OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams,
15 PairResult, PeerDiagnosticsParams, PeerDiagnosticsResult, PeerEndorseParams, PeerEndorseResult,
16 PeerHintClearParams, PeerHintClearResult, PeerIntroduceParams, PeerRemoveParams,
17 PeerRenameParams, PeerServicesParams, PeerServicesResult, RegisterServiceParams, Request,
18 RosterInstallParams, RosterInstallResult, ServiceAllowParams, SetAppMetadataParams,
19 SetNicknameParams, SetRelaysParams, SetRelaysResult, SetRosterUrlParams, StatusResult,
20 StreamFrame, UnregisterServiceParams,
21};
22use crate::transport::{connect_local, split_local};
23
24/// The client's read half — boxed so ONE `ControlClient` serves every transport (the
25/// platform socket/pipe via [`connect_control`], or an embedder's in-memory duplex via
26/// [`connect_control_io`]).
27pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
28/// The client's write half — see [`ControlRead`].
29pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
30
31/// A connected mcpmesh-local/1 client: the framed stream + the server's `Hello`.
32pub struct ControlClient {
33 hello: Hello,
34 reader: FrameReader<ControlRead>,
35 writer: ControlWrite,
36}
37
38/// Hand-rolled (the boxed transport halves are not `Debug`): the `Hello` is the one
39/// diagnostic a `{:?}` needs — tests format `Result<ControlClient, _>` this way.
40impl std::fmt::Debug for ControlClient {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 f.debug_struct("ControlClient")
43 .field("hello", &self.hello)
44 .finish_non_exhaustive()
45 }
46}
47
48/// The error surface of the client — thin, so callers can `anyhow`-wrap it.
49///
50/// The `Display`/`Error`/`From` impls below are hand-rolled rather than derived: the
51/// `client` feature deliberately pulls ONLY tokio (no `thiserror`), and the hand-rolled
52/// impls are behavior-identical (same messages, same `?`-conversion from `io::Error`)
53/// with zero extra dependencies.
54#[derive(Debug)]
55pub enum ClientError {
56 Io(std::io::Error),
57 Closed(&'static str),
58 Malformed(&'static str),
59 WrongApi { got: String, want: &'static str },
60 Api(Value),
61}
62
63impl std::fmt::Display for ClientError {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 match self {
66 ClientError::Io(err) => write!(f, "io: {err}"),
67 ClientError::Closed(what) => write!(f, "connection closed before {what}"),
68 ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
69 ClientError::WrongApi { got, want } => {
70 write!(f, "unexpected api: got {got:?}, want {want:?}")
71 }
72 ClientError::Api(err) => write!(f, "control API error: {err}"),
73 }
74 }
75}
76
77impl std::error::Error for ClientError {}
78
79impl From<std::io::Error> for ClientError {
80 fn from(err: std::io::Error) -> Self {
81 ClientError::Io(err)
82 }
83}
84
85impl ControlClient {
86 pub fn hello(&self) -> &Hello {
87 &self.hello
88 }
89
90 /// Issue a typed request; return the JSON-RPC `result` (or `ClientError::Api` on a
91 /// JSON-RPC `error`).
92 pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
93 let frame = serde_json::to_value(&request).expect("Request serializes");
94 self.request_value(&frame).await
95 }
96
97 /// Issue a RAW request frame — the escape hatch for methods outside the typed
98 /// [`Request`] surface (the daemon-internal `shutdown`, third-party
99 /// `{"method":..,"params":{}}` shapes the dispatcher tolerates). Returns the JSON-RPC
100 /// `result` value (or `ClientError::Api` on a JSON-RPC `error`).
101 pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
102 write_frame(&mut self.writer, request).await?;
103 match self.reader.next().await? {
104 Some(Inbound::Frame(resp)) => {
105 if let Some(err) = resp.get("error") {
106 return Err(ClientError::Api(err.clone()));
107 }
108 Ok(resp.get("result").cloned().unwrap_or(Value::Null))
109 }
110 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
111 None => Err(ClientError::Closed("response")),
112 }
113 }
114
115 /// Send a request WITHOUT reading a response — for `OpenSession`, after which the
116 /// socket stops being JSON-RPC and becomes a raw MCP byte pipe (protocol.rs). Returns
117 /// the framed halves so the caller can pump the session — the SAME `FrameReader` that
118 /// read the Hello, so bytes the daemon pipelined behind it are never lost. A caller
119 /// that must re-box the read half calls `FrameReader::into_inner`, which returns the
120 /// BUFFERED reader (its read-ahead travels with it — see the pipelining test below).
121 pub async fn open_session(
122 self,
123 peer: String,
124 service: String,
125 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
126 self.open_session_with_idle_timeout(peer, service, None)
127 .await
128 }
129
130 /// [`open_session`](Self::open_session) with a per-session QUIC idle timeout (#166).
131 ///
132 /// See [`OpenSessionParams::idle_timeout_secs`] for what it can and cannot do — in short, it
133 /// can always make this session die sooner when it goes quiet, and can never make it outlive
134 /// what the peer allows.
135 ///
136 /// [`OpenSessionParams::idle_timeout_secs`]: crate::protocol::OpenSessionParams::idle_timeout_secs
137 pub async fn open_session_with_idle_timeout(
138 mut self,
139 peer: String,
140 service: String,
141 idle_timeout_secs: Option<u64>,
142 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
143 let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams {
144 peer,
145 service,
146 idle_timeout_secs,
147 }))
148 .expect("Request serializes");
149 write_frame(&mut self.writer, &frame).await?;
150 Ok((self.reader, self.writer))
151 }
152
153 /// Send a parameterless stream-upgrade request WITHOUT reading a response — like
154 /// [`open_session`](Self::open_session), but generic on the `method`: after this call the
155 /// socket stops being request/response and becomes a one-way push stream of frames the caller
156 /// READS (the `subscribe` telemetry surface). Returns the framed halves — the SAME
157 /// `FrameReader` that read the Hello, so any frame the daemon pipelined behind it is never
158 /// lost. The write half is handed back so the caller can hold the connection open (a watcher
159 /// only reads, but dropping the writer would half-close the socket).
160 pub async fn open_stream(
161 mut self,
162 method: &str,
163 ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
164 let frame = serde_json::json!({ "method": method });
165 write_frame(&mut self.writer, &frame).await?;
166 Ok((self.reader, self.writer))
167 }
168
169 /// Issue `request` and deserialize the JSON-RPC `result` into `T` — the shared core of every
170 /// typed helper below. `what` names the result in the [`ClientError::Malformed`] surface. The
171 /// wrong-type hazard the raw [`request`](Self::request) leaves to the caller is closed here:
172 /// each helper pairs its Request variant with its result type once, in this crate.
173 async fn request_typed<T: serde::de::DeserializeOwned>(
174 &mut self,
175 request: Request,
176 what: &'static str,
177 ) -> Result<T, ClientError> {
178 let v = self.request(request).await?;
179 serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
180 }
181
182 /// Issue `request` and discard the ack body (the daemon answers `{}` for verbs with no result
183 /// vocabulary). A JSON-RPC error still surfaces as [`ClientError::Api`].
184 async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
185 self.request(request).await.map(|_| ())
186 }
187
188 /// The daemon's `status` picture: services served, known peers, roster/presence state,
189 /// self identity, recent pairings, and advisory reachability.
190 pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
191 self.request_typed(Request::Status, "status result").await
192 }
193
194 /// Register/update a `[services.*]` entry idempotently (the daemon persists it and hot-reloads
195 /// serving). The daemon acks; the ack body is discarded.
196 pub async fn register_service(
197 &mut self,
198 name: &str,
199 backend: BackendSpec,
200 allow: Vec<String>,
201 ) -> Result<(), ClientError> {
202 self.register_service_with(name, backend, allow, false)
203 .await
204 }
205
206 /// [`register_service`](Self::register_service) with an explicit `ephemeral` flag (#36). When
207 /// `ephemeral` is true the registration lives only in daemon memory and is unregistered
208 /// automatically when THIS control connection closes — no config write, nothing to clean up.
209 /// Ideal for an embedder serving a `socket` backend from a fresh path each run.
210 pub async fn register_service_with(
211 &mut self,
212 name: &str,
213 backend: BackendSpec,
214 allow: Vec<String>,
215 ephemeral: bool,
216 ) -> Result<(), ClientError> {
217 self.request_ack(Request::RegisterService(RegisterServiceParams {
218 name: name.to_string(),
219 backend,
220 allow,
221 ephemeral,
222 rate_limit_per_min: None,
223 }))
224 .await
225 }
226
227 /// Mint a single-use pairing invite granting `services` (see `invite_multi` for more than
228 /// one); return the copyable
229 /// `mcpmesh-invite:` line + its expiry.
230 pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
231 self.invite_with(services, None).await
232 }
233
234 /// [`invite`](Self::invite) with an opaque `app_label` (#31) carried through to the redeemer's
235 /// `pair` result. mcpmesh never interprets the label; the embedder does (e.g. its own URN).
236 pub async fn invite_with(
237 &mut self,
238 services: Vec<String>,
239 app_label: Option<String>,
240 ) -> Result<InviteResult, ClientError> {
241 self.invite_multi(services, app_label, None).await
242 }
243
244 /// `invite_with`, plus `max_uses` (#87): an invite redeemable up to that many times, each
245 /// redemption running its own SAS ceremony and writing its own peer rows.
246 ///
247 /// `None` = 1, the single-use default. The value is clamped daemon-side to
248 /// [`MAX_INVITE_USES`](crate::MAX_INVITE_USES) — read
249 /// [`InviteResult::uses_remaining`](crate::InviteResult::uses_remaining) for what you actually
250 /// got rather than assuming the request was honoured verbatim.
251 pub async fn invite_multi(
252 &mut self,
253 services: Vec<String>,
254 app_label: Option<String>,
255 max_uses: Option<u32>,
256 ) -> Result<InviteResult, ClientError> {
257 self.invite_named(services, app_label, max_uses, None).await
258 }
259
260 /// Mint an invite, optionally under YOUR OWN local name for whoever redeems it (#87).
261 ///
262 /// `peer_nickname` overrides the name they claim for themselves — the fix for two same-model
263 /// machines that does not require the other person to rename theirs. Never sent to them, and
264 /// rejected alongside `max_uses > 1` (one name for every redeemer collides on the second).
265 pub async fn invite_named(
266 &mut self,
267 services: Vec<String>,
268 app_label: Option<String>,
269 max_uses: Option<u32>,
270 peer_nickname: Option<String>,
271 ) -> Result<InviteResult, ClientError> {
272 self.invite_full(services, app_label, max_uses, peer_nickname, false)
273 .await
274 }
275
276 /// Mint an invite, optionally as a SELF-ENROLLMENT (#86): the redeemer becomes another device
277 /// of YOU rather than a peer, so both present one identity.
278 ///
279 /// `as_self` requires an empty `services` and `max_uses` of 1 — it grants nothing, and a
280 /// multi-use identity invite is a standing offer to become you.
281 pub async fn invite_full(
282 &mut self,
283 services: Vec<String>,
284 app_label: Option<String>,
285 max_uses: Option<u32>,
286 peer_nickname: Option<String>,
287 as_self: bool,
288 ) -> Result<InviteResult, ClientError> {
289 self.request_typed(
290 Request::Invite(InviteParams {
291 services,
292 app_label,
293 max_uses,
294 peer_nickname,
295 as_self,
296 }),
297 "invite result",
298 )
299 .await
300 }
301
302 /// Produce an endorsement of `subject` for someone else to redeem (#65).
303 ///
304 /// Signs with THIS node's user key. It is a statement for the recipient — it changes nothing
305 /// about your own trust in the subject, and only resolves for someone paired with you. Refused
306 /// when this node holds no user key of its own (enrolled, or none on disk — `api_minor >= 63`).
307 pub async fn endorse_peer(
308 &mut self,
309 subject: &str,
310 subject_user_id: Option<String>,
311 ) -> Result<PeerEndorseResult, ClientError> {
312 self.request_typed(
313 Request::PeerEndorse(PeerEndorseParams {
314 subject: subject.to_string(),
315 subject_user_id,
316 }),
317 "peer endorse result",
318 )
319 .await
320 }
321
322 /// Dump the durable per-peer state this node carries for `peer` (#140), `api_minor >= 33`.
323 ///
324 /// The persisted dial hint verbatim, whether the DIAL actually uses it, the addresses inside it,
325 /// iroh's own view (`api_minor >= 56`), the pairing stamp and the live reachability row — one
326 /// capture, intended to be run on BOTH ends of a stuck pairing and compared.
327 ///
328 /// **Read-only, but NOT inert.** It probes nothing, dials nothing and writes nothing — but
329 /// reading iroh's view delivers a message to that remote's actor, which resets its ~60s idle
330 /// timer. Polling this keeps remote state alive (a selected path included) that would otherwise
331 /// be reaped.
332 ///
333 /// That matters for the one experiment this method exists to support: #140's step A is "close
334 /// every session, **wait >60s**, then probe". Poll during the wait and you preserve the very
335 /// state you are trying to clear, and get a false negative.
336 ///
337 /// Existed as a verb since 0.35.0 with no typed method here, so an embedder had to hand-build
338 /// the request — which the one embedder who needs it most (a node embedder debugging #140)
339 /// would have to do at exactly the wrong moment.
340 pub async fn peer_diagnostics(
341 &mut self,
342 peer: &str,
343 ) -> Result<PeerDiagnosticsResult, ClientError> {
344 self.request_typed(
345 Request::PeerDiagnostics(PeerDiagnosticsParams {
346 peer: peer.to_string(),
347 }),
348 "peer diagnostics result",
349 )
350 .await
351 }
352
353 /// Forget this node's stored dial hint for `peer` (#140), `api_minor >= 59`.
354 ///
355 /// The hint is the only durable per-peer state on this node's disk that the dial path reads, and
356 /// the only thing a long-lived pairing carries that a freshly paired identity does not — so
357 /// clearing it makes the pairing address like a fresh one. Advisory, never authorization: the
358 /// peer row, its `user_id`, its services and its pairing stamp are untouched, and an absent hint
359 /// is a supported state (the dial degrades to id-only). Errors for an unknown peer; `cleared`
360 /// is `false` for a known peer that had no hint.
361 pub async fn peer_hint_clear(
362 &mut self,
363 peer: &str,
364 ) -> Result<PeerHintClearResult, ClientError> {
365 self.request_typed(
366 Request::PeerHintClear(PeerHintClearParams {
367 peer: peer.to_string(),
368 }),
369 "peer hint clear result",
370 )
371 .await
372 }
373
374 /// Install a peer from an endorsement by someone you are already paired with (#65).
375 ///
376 /// Installs IDENTITY, not authorization — the peer becomes resolvable and is granted nothing.
377 /// `subject_user_id` requires `subject_binding`, the subject's OWN device→user binding: a
378 /// `user_id` is authorization-bearing and public, so an endorser alone must not attach one.
379 pub async fn introduce_peer(&mut self, params: PeerIntroduceParams) -> Result<(), ClientError> {
380 self.request_ack(Request::PeerIntroduce(params)).await
381 }
382
383 /// Redeem a pairing invite; return the inviter's suggested nickname, the display-only SAS
384 /// code, and the granted services.
385 pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
386 self.pair_as(invite_line, None).await
387 }
388
389 /// Redeem an invite, optionally under YOUR OWN local name for the inviter (#87).
390 ///
391 /// `as_nickname` overrides the name the invite suggests. Use it when that name is already
392 /// taken locally — otherwise the pairing is refused and the only other fixes are asking the
393 /// inviter to re-mint or renaming your existing peer. It does not bypass the collision check:
394 /// an alias that itself collides is refused the same way.
395 pub async fn pair_as(
396 &mut self,
397 invite_line: &str,
398 as_nickname: Option<String>,
399 ) -> Result<PairResult, ClientError> {
400 self.pair_opts(invite_line, as_nickname, false).await
401 }
402
403 /// Redeem an invite, stating whether a SELF-ENROLLMENT is a ceremony you offered (#178).
404 ///
405 /// [`pair`](Self::pair) and [`pair_as`](Self::pair_as) pass `false`, so a `mcpmesh-enroll:` line
406 /// pasted into an ordinary "join" field is refused with
407 /// [`ERR_SELF_ENROLL_NOT_OFFERED`](crate::ERR_SELF_ENROLL_NOT_OFFERED) before anything is
408 /// dialled — the invite survives, so the same line still works once the person is offered the
409 /// real choice. Pass `true` only from a path that actually means "add another of my own
410 /// devices": the ceremony writes a device→user binding that is irrevocable short of rotating
411 /// the user key.
412 ///
413 /// `mcpmesh_node::pairing::is_enrollment_line` answers which kind of line you are holding without
414 /// dialling, for a UI that wants to PROMPT rather than recover from a refusal.
415 pub async fn pair_opts(
416 &mut self,
417 invite_line: &str,
418 as_nickname: Option<String>,
419 allow_self_enroll: bool,
420 ) -> Result<PairResult, ClientError> {
421 self.request_typed(
422 Request::Pair(PairParams {
423 invite_line: invite_line.to_string(),
424 as_nickname,
425 allow_self_enroll,
426 }),
427 "pair result",
428 )
429 .await
430 }
431
432 /// Unpair a peer by nickname: drops its identity row AND its every-`allow` membership
433 /// (idempotent; live sessions are not severed). The daemon acks; the ack body is discarded.
434 pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
435 self.request_ack(Request::PeerRemove(PeerRemoveParams {
436 nickname: nickname.to_string(),
437 }))
438 .await
439 }
440
441 /// Rename a contact's nickname to `to` — every device sharing `user_id` when given, else the
442 /// single provisional `nickname` entry — carrying its grants along. The daemon refuses (a
443 /// [`ClientError::Api`]) when `to` is empty or already names a different identity. The daemon
444 /// acks; the ack body is discarded.
445 pub async fn peer_rename(
446 &mut self,
447 user_id: Option<String>,
448 nickname: Option<String>,
449 to: &str,
450 ) -> Result<(), ClientError> {
451 self.request_ack(Request::PeerRename(PeerRenameParams {
452 user_id,
453 nickname,
454 to: to.to_string(),
455 }))
456 .await
457 }
458
459 /// Install a signed roster from the LOCAL file at `path` (`org_root_pk` pins the org root on
460 /// FIRST install); return the installed org id + serial + severed-session count.
461 pub async fn roster_install(
462 &mut self,
463 path: &str,
464 org_root_pk: Option<String>,
465 ) -> Result<RosterInstallResult, ClientError> {
466 self.request_typed(
467 Request::RosterInstall(RosterInstallParams {
468 path: path.to_string(),
469 org_root_pk,
470 }),
471 "roster_install result",
472 )
473 .await
474 }
475
476 /// Read the installed roster's MEMBERSHIP (#93): the declared groups, and every person with
477 /// their display name, groups, and devices.
478 ///
479 /// Distinct from [`status`](Self::status)'s `presence`, which enumerates reachable DEVICES and
480 /// omits a person entirely when none of theirs is up. This is the member list — everyone the
481 /// roster carries, with `online` per device, so one read serves both questions.
482 ///
483 /// Advisory: display and authoring input, never an authorization answer. Empty in a
484 /// pure-pairing daemon and before the first roster is installed. `api_minor >= 46`.
485 pub async fn roster_members(
486 &mut self,
487 ) -> Result<crate::protocol::RosterMembersResult, ClientError> {
488 self.request_typed(Request::RosterMembers, "roster_members result")
489 .await
490 }
491
492 /// AUTHOR an org (#66): mint this node's org root key, sign an empty roster, install it (which
493 /// pins the root), and return the copyable invite plus the root's fingerprint.
494 ///
495 /// **One-time per node** — a second call is refused rather than replacing the key, which would
496 /// orphan every roster already signed with it.
497 ///
498 /// Show `org_root_fingerprint` to the operator: it is what every joiner reads back
499 /// out-of-band, and it is the only thing anchoring their trust in the org. `api_minor >= 46`.
500 pub async fn org_create(
501 &mut self,
502 name: &str,
503 expires_secs: Option<i64>,
504 roster_url: Option<String>,
505 ) -> Result<crate::protocol::OrgCreateResult, ClientError> {
506 self.request_typed(
507 Request::OrgCreate(crate::protocol::OrgCreateParams {
508 name: name.to_string(),
509 expires_secs,
510 roster_url,
511 }),
512 "org_create result",
513 )
514 .await
515 }
516
517 /// APPROVE a join code into the roster (#66): verify its device→user-key binding, add the
518 /// member with `groups`, re-sign, install.
519 ///
520 /// **The result's `join_code_fingerprint` is not decoration.** Nothing in a join code binds it
521 /// to a human, so a substituted code is caught by the two people comparing that fingerprint
522 /// out-of-band, or it is not caught at all. Show it and have the operator confirm it.
523 ///
524 /// Each group must already be declared in the roster; an undeclared one is refused. `user_id`
525 /// overrides the id the joiner requested — worth using, since that id is chosen by the person
526 /// being approved and is what every `allow` entry will name. `api_minor >= 46`.
527 pub async fn org_approve(
528 &mut self,
529 join_code: &str,
530 groups: Vec<String>,
531 user_id: Option<String>,
532 ) -> Result<crate::protocol::OrgApproveResult, ClientError> {
533 self.request_typed(
534 Request::OrgApprove(crate::protocol::OrgApproveParams {
535 join_code: join_code.to_string(),
536 groups,
537 user_id,
538 }),
539 "org_approve result",
540 )
541 .await
542 }
543
544 /// Rotate the org root (#93 ask c), publishing a bridge members adopt as they receive it.
545 pub async fn org_rotate(
546 &mut self,
547 new_key_path: Option<String>,
548 ) -> Result<crate::protocol::OrgRotateResult, ClientError> {
549 self.request_typed(
550 Request::OrgRotate(crate::protocol::OrgRotateParams { new_key_path }),
551 "org_rotate result",
552 )
553 .await
554 }
555
556 /// Mint an attestation offer (#85 ask 3) — where another of this person's devices should dial.
557 pub async fn attest_offer(
558 &mut self,
559 ) -> Result<crate::protocol::AttestOfferResult, ClientError> {
560 self.request_typed(Request::AttestOffer, "attest_offer result")
561 .await
562 }
563
564 /// Present this device's identity to a peer, using their `mcpmesh-attest:` line (#85 ask 3).
565 pub async fn attest_to(
566 &mut self,
567 offer: impl Into<String>,
568 ) -> Result<crate::protocol::PairResult, ClientError> {
569 self.request_typed(
570 Request::AttestTo(crate::protocol::AttestToParams {
571 offer: offer.into(),
572 }),
573 "attest_to result",
574 )
575 .await
576 }
577
578 /// Refuse a peer's device on this node (#85 ask 4). Immediate: live sessions are severed.
579 pub async fn peer_revoke(
580 &mut self,
581 peer: impl Into<String>,
582 reason: Option<String>,
583 ) -> Result<crate::protocol::PeerRevokeResult, ClientError> {
584 self.request_typed(
585 Request::PeerRevoke(crate::protocol::PeerRevokeParams {
586 peer: peer.into(),
587 reason,
588 }),
589 "peer_revoke result",
590 )
591 .await
592 }
593
594 /// Lift a local revocation (#85 ask 4). Idempotent.
595 pub async fn peer_unrevoke(
596 &mut self,
597 peer: impl Into<String>,
598 ) -> Result<crate::protocol::PeerUnrevokeResult, ClientError> {
599 self.request_typed(
600 Request::PeerUnrevoke(crate::protocol::PeerUnrevokeParams { peer: peer.into() }),
601 "peer_unrevoke result",
602 )
603 .await
604 }
605
606 /// Sign a portable revocation of one of THIS person's own devices (#85 ask 4).
607 pub async fn device_revoke(
608 &mut self,
609 endpoint: impl Into<String>,
610 reason: Option<String>,
611 ) -> Result<crate::protocol::DeviceRevokeResult, ClientError> {
612 self.request_typed(
613 Request::DeviceRevoke(crate::protocol::DeviceRevokeParams {
614 endpoint: endpoint.into(),
615 reason,
616 }),
617 "device_revoke result",
618 )
619 .await
620 }
621
622 /// Apply a peer's signed device revocation (#85 ask 4).
623 pub async fn device_revocation_import(
624 &mut self,
625 token: impl Into<String>,
626 ) -> Result<crate::protocol::DeviceRevocationImportResult, ClientError> {
627 self.request_typed(
628 Request::DeviceRevocationImport(crate::protocol::DeviceRevocationImportParams {
629 token: token.into(),
630 }),
631 "device_revocation_import result",
632 )
633 .await
634 }
635
636 /// EXPORT this node's user key as a RECOVERY PHRASE (#85 ask 2).
637 ///
638 /// **The phrase is the private key**, in a form a person can write down. Anyone who reads it
639 /// can present this identity. Show it once, to the person who owns it, and do not persist it
640 /// anywhere you would not persist the key file. It is deliberately not logged or audited by the
641 /// daemon; this response is the only place it exists.
642 ///
643 /// `user_id` is safe to display and record — compare it after an import to confirm the right
644 /// identity came back. `api_minor >= 48`. Refused (`-32602`) on a device ENROLLED into another
645 /// identity, whose local key is not the one it presents (`api_minor >= 63`, #219).
646 pub async fn user_key_export(
647 &mut self,
648 ) -> Result<crate::protocol::UserKeyExportResult, ClientError> {
649 self.request_typed(Request::UserKeyExport, "user_key_export result")
650 .await
651 }
652
653 /// IMPORT a user key from a recovery phrase (#85 ask 2), so a person's `b64u:` survives the
654 /// hardware.
655 ///
656 /// Refuses to overwrite an existing key unless `replace` is set: importing over a live key
657 /// discards the identity this node presents, irreversibly without that key's own phrase.
658 ///
659 /// **Check the returned `user_id` against the one you are recovering.** The phrase's checksum
660 /// catches most transcription errors, but the `user_id` is the definitive answer, and the only
661 /// thing that distinguishes "restored the wrong key" from "my peers have not seen me yet".
662 ///
663 /// It does NOT get this device admitted by anyone: peers authorize per DEVICE, and a restored
664 /// user key does not put this endpoint in anybody's allowlist. That is #85 ask 3, not shipped.
665 /// `api_minor >= 48`. Without `replace` it refuses to overwrite a key an earlier import wrote,
666 /// including within the same daemon lifetime (`api_minor >= 63`, #221).
667 pub async fn user_key_import(
668 &mut self,
669 recovery_phrase: &str,
670 replace: bool,
671 ) -> Result<crate::protocol::UserKeyImportResult, ClientError> {
672 self.request_typed(
673 Request::UserKeyImport(crate::protocol::UserKeyImportParams {
674 recovery_phrase: recovery_phrase.to_string(),
675 replace,
676 }),
677 "user_key_import result",
678 )
679 .await
680 }
681
682 /// DETACH this device from an identity it was enrolled into (#214) — the inverse of
683 /// `pair_opts(.., allow_self_enroll: true)`. Drops the adopted binding live and on disk; the
684 /// node goes back to presenting its own identity (imported, else boot-derived), returned as
685 /// `user_id`.
686 ///
687 /// Local only: peers who already learned this endpoint as that person's device are not told —
688 /// that is `device_revoke`, from the device holding the key. Refused with `ERR_NOT_ENROLLED`
689 /// when nothing is adopted. `api_minor >= 62`.
690 pub async fn self_enroll_detach(
691 &mut self,
692 ) -> Result<crate::protocol::SelfEnrollDetachResult, ClientError> {
693 self.request_typed(Request::SelfEnrollDetach, "self_enroll_detach result")
694 .await
695 }
696
697 /// INSPECT a join code without approving it (#66): what it claims, and the fingerprint that
698 /// decides whether to believe it. Read-only — nothing is signed or installed.
699 ///
700 /// **Call this before [`org_approve`](Self::org_approve), show
701 /// `join_code_fingerprint`, and have the operator confirm it out-of-band.** Nothing in a join
702 /// code binds it to a person; a substituted one carries a different key and diverges here. The
703 /// fingerprint on the approval RESULT is the same words, but by then the member is in the
704 /// signed roster — too late to decline.
705 ///
706 /// The claims (`display_name`, `requested_user_id`, `device_label`) are chosen by the sender.
707 /// Render them; do not trust them. A forged binding is refused rather than described.
708 /// `api_minor >= 46`.
709 pub async fn org_join_code(
710 &mut self,
711 join_code: &str,
712 ) -> Result<crate::protocol::OrgJoinCodeResult, ClientError> {
713 self.request_typed(
714 Request::OrgJoinCode(crate::protocol::OrgJoinCodeParams {
715 join_code: join_code.to_string(),
716 }),
717 "org_join_code result",
718 )
719 .await
720 }
721
722 /// REVOKE from the roster (#66) — and sever the cut devices' live sessions, immediately.
723 ///
724 /// Three readings, and picking the wrong one is destructive, so the result reports which
725 /// `mode` was applied: `"<user_id>/<label>"` cuts ONE device; a bare `user_id` removes the
726 /// person and revokes ALL their devices; `user_key = true` is a key ROTATION — the person is
727 /// removed but their devices stay un-revoked so the same hardware re-enrolls under a fresh
728 /// user key. `api_minor >= 46`.
729 pub async fn org_revoke(
730 &mut self,
731 target: &str,
732 user_key: bool,
733 ) -> Result<crate::protocol::OrgRevokeResult, ClientError> {
734 self.request_typed(
735 Request::OrgRevoke(crate::protocol::OrgRevokeParams {
736 target: target.to_string(),
737 user_key,
738 }),
739 "org_revoke result",
740 )
741 .await
742 }
743
744 /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
745 /// crosses the API. Returns the pinned org id.
746 pub async fn org_join(
747 &mut self,
748 org_id: &str,
749 org_root_pk: &str,
750 user_id: &str,
751 user_key: &str,
752 ) -> Result<OrgJoinResult, ClientError> {
753 self.request_typed(
754 Request::OrgJoin(OrgJoinParams {
755 org_id: org_id.to_string(),
756 org_root_pk: org_root_pk.to_string(),
757 user_id: user_id.to_string(),
758 user_key: user_key.to_string(),
759 }),
760 "org_join result",
761 )
762 .await
763 }
764
765 /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
766 /// ack body is discarded.
767 pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
768 self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
769 url: url.to_string(),
770 }))
771 .await
772 }
773
774 /// Discover which services a paired `peer` (a nickname, `eid:`, or `b64u:`) CURRENTLY grants
775 /// the caller (#52) — dials the peer and returns the service names its allow admits for the
776 /// caller's principal (only your own admitted services, never the peer's full registry).
777 pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
778 self.request_typed::<PeerServicesResult>(
779 Request::PeerServices(PeerServicesParams {
780 peer: peer.to_string(),
781 }),
782 "peer_services",
783 )
784 .await
785 .map(|r| r.services)
786 }
787
788 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
789 /// Removes the whole entry (allow included) + any ephemeral registration of the name, then
790 /// hot-reloads. Idempotent: an unknown name is a clean no-op.
791 pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
792 self.request_ack(Request::UnregisterService(UnregisterServiceParams {
793 name: name.to_string(),
794 }))
795 .await
796 }
797
798 /// Grant a stable `principal` (`b64u:`/`eid:`) access to `service` WITHOUT (re)pairing (#44)
799 /// — the per-peer "sharing on" toggle. Idempotent; an unknown service is a clean no-op.
800 pub async fn service_allow_grant(
801 &mut self,
802 service: &str,
803 principal: &str,
804 ) -> Result<(), ClientError> {
805 self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
806 service: service.to_string(),
807 principal: principal.to_string(),
808 }))
809 .await
810 }
811
812 /// Revoke a stable `principal` from `service`'s allow WITHOUT unpairing (#44) — the
813 /// "sharing off" toggle. The peer's identity row is untouched; it just cannot open NEW
814 /// sessions (in-flight ones run to completion). Idempotent.
815 pub async fn service_allow_revoke(
816 &mut self,
817 service: &str,
818 principal: &str,
819 ) -> Result<(), ClientError> {
820 self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
821 service: service.to_string(),
822 principal: principal.to_string(),
823 }))
824 .await
825 }
826
827 /// Set this node's opaque app-metadata blob (#39, roster mode): ≤256 bytes, folded
828 /// signed into each presence heartbeat so paired peers read it in `status` presence —
829 /// no per-peer session. `""` clears it; in-memory (re-set on startup).
830 pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
831 self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
832 metadata: metadata.to_string(),
833 }))
834 .await
835 }
836
837 /// Set this node's CUSTOM relay set LIVE (#53). `relay_urls` is the desired set (each must
838 /// parse as an iroh `RelayUrl`; empty is rejected). When the node is already in
839 /// `relay_mode = "custom"`, the daemon diffs against the running endpoint and applies the
840 /// delta live (iroh `insert_relay`/`remove_relay`) — no restart, no dropped sessions — then
841 /// persists `[network]`. When the node is currently `default`/`disabled`, the config is
842 /// persisted but the live mode transition isn't possible: the returned
843 /// [`SetRelaysResult::restart_required`] is `true`. Idempotent (an unchanged set → `changed:
844 /// false`, no writes).
845 pub async fn set_relays(
846 &mut self,
847 relay_urls: &[String],
848 ) -> Result<SetRelaysResult, ClientError> {
849 self.request_typed::<SetRelaysResult>(
850 Request::SetRelays(SetRelaysParams {
851 relay_urls: relay_urls.to_vec(),
852 }),
853 "set_relays",
854 )
855 .await
856 }
857
858 /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
859 /// under its own config lock and updates the name future invites present — no restart.
860 /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
861 pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
862 self.request_ack(Request::SetNickname(SetNicknameParams {
863 nickname: nickname.to_string(),
864 }))
865 .await
866 }
867
868 /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
869 /// (local-only — nothing is transmitted).
870 pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
871 self.request_typed(Request::AuditSummary, "audit_summary result")
872 .await
873 }
874
875 /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
876 pub async fn blob_publish(
877 &mut self,
878 scope: &str,
879 path: &str,
880 ) -> Result<BlobPublishResult, ClientError> {
881 self.request_typed(
882 Request::BlobPublish(BlobPublishParams {
883 scope: scope.to_string(),
884 path: path.to_string(),
885 }),
886 "blob_publish result",
887 )
888 .await
889 }
890
891 /// List the daemon's blob scopes (name → hashes + grants + withdrawn).
892 ///
893 /// A DEFAULT LIMIT applies (#84b) — check `truncated` and page with
894 /// [`blob_list_paged`](Self::blob_list_paged) rather than assuming you saw everything.
895 pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
896 self.blob_list_paged(Default::default()).await
897 }
898
899 /// List blob scopes with filters + paging (#84b, `api_minor >= 20`).
900 pub async fn blob_list_paged(
901 &mut self,
902 params: crate::BlobListParams,
903 ) -> Result<BlobScopeList, ClientError> {
904 self.request_typed(Request::BlobList(params), "blob_list result")
905 .await
906 }
907
908 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
909 /// `dest_path`; return the verified hash + byte length.
910 pub async fn blob_fetch(
911 &mut self,
912 ticket: &str,
913 dest_path: &str,
914 ) -> Result<BlobFetchResult, ClientError> {
915 self.blob_fetch_from(ticket, dest_path, Vec::new()).await
916 }
917
918 /// [`blob_fetch`](Self::blob_fetch) with ADDITIONAL sources to try when the ticket's publisher
919 /// does not answer (#83).
920 ///
921 /// Content addressing makes every recipient a potential source; a single-address ticket made
922 /// that unusable, so a file shared with a room became unfetchable the moment the sender closed
923 /// their laptop — even though others in the room already held the identical verified bytes.
924 ///
925 /// `from` takes stable principals (`eid:`, `b64u:`) or paired nicknames — the same vocabulary
926 /// `open_session` takes, and naming a PERSON offers every device of theirs. They are tried in
927 /// order, **after** the publisher, so a live publisher costs nothing and an offline one costs
928 /// one dial timeout.
929 ///
930 /// **The bytes are BLAKE3-verified against the ticket's hash whoever serves them**, so an
931 /// alternate cannot substitute content. It can refuse: an alternate serves only hashes it has
932 /// republished into a scope that grants you (see `blob_republish`), and an ungranted one
933 /// answers a permission error and the fetch moves on. Every failure mode falls through, not
934 /// only an unreachable dial — a refusal, a missing hash, a reset, and a stalled transfer all
935 /// move to the next source. `api_minor >= 47`.
936 pub async fn blob_fetch_from(
937 &mut self,
938 ticket: &str,
939 dest_path: &str,
940 from: Vec<String>,
941 ) -> Result<BlobFetchResult, ClientError> {
942 self.request_typed(
943 Request::BlobFetch(BlobFetchParams {
944 ticket: ticket.to_string(),
945 dest_path: dest_path.to_string(),
946 from,
947 }),
948 "blob_fetch result",
949 )
950 .await
951 }
952
953 /// Stop every in-flight [`blob_fetch`](Self::blob_fetch) of `hash` (#172).
954 ///
955 /// **Send this on a DIFFERENT connection than the fetch it cancels.** This client is one
956 /// request at a time — `&mut self` is borrowed until the fetch answers — so a cancel issued on
957 /// the same client can only run after the thing it would cancel is already over. The cancelled
958 /// fetch answers [`ERR_CANCELLED`](crate::ERR_CANCELLED) on its own connection.
959 ///
960 /// `cancelled: false` means nothing was fetching that blob here. That is the honest answer to a
961 /// cancel that raced a fetch to completion, not an error.
962 ///
963 /// Needs `api_minor >= 44`; below it the method is unknown.
964 pub async fn blob_fetch_cancel(
965 &mut self,
966 hash: &str,
967 ) -> Result<BlobFetchCancelResult, ClientError> {
968 self.request_typed(
969 Request::BlobFetchCancel(BlobFetchCancelParams {
970 hash: hash.to_string(),
971 }),
972 "blob_fetch_cancel result",
973 )
974 .await
975 }
976
977 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
978 /// or a nickname (the shared `principal_set` expansion).
979 /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
980 /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
981 /// person's devices.
982 pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
983 self.request_ack(Request::BlobGrant(BlobGrantParams {
984 scope: scope.to_string(),
985 principal: principal.to_string(),
986 }))
987 .await
988 }
989
990 /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
991 /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
992 /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
993 /// types newer than this crate), use `open_stream("subscribe")` instead.
994 pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
995 let (reader, writer) = self.open_stream("subscribe").await?;
996 Ok(StreamSubscription {
997 reader,
998 _writer: writer,
999 })
1000 }
1001}
1002
1003/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
1004/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
1005/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
1006/// the subscription to disconnect (there is no request channel back).
1007pub struct StreamSubscription {
1008 reader: FrameReader<ControlRead>,
1009 _writer: ControlWrite,
1010}
1011
1012/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
1013impl std::fmt::Debug for StreamSubscription {
1014 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1015 f.debug_struct("StreamSubscription").finish_non_exhaustive()
1016 }
1017}
1018
1019impl StreamSubscription {
1020 /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
1021 /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
1022 /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
1023 /// [`ControlClient::open_stream`] instead.
1024 pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
1025 match self.reader.next().await? {
1026 Some(Inbound::Frame(v)) => serde_json::from_value(v)
1027 .map(Some)
1028 .map_err(|_| ClientError::Malformed("stream frame")),
1029 Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
1030 None => Ok(None),
1031 }
1032 }
1033}
1034
1035/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
1036/// the transport-agnostic core of [`connect_control`], and the front door for in-process
1037/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
1038pub async fn connect_control_io(
1039 reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
1040 writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
1041) -> Result<ControlClient, ClientError> {
1042 let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
1043 let hello: Hello = match reader.next().await? {
1044 Some(Inbound::Frame(v)) => {
1045 serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
1046 }
1047 Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
1048 None => return Err(ClientError::Closed("hello")),
1049 };
1050 if hello.api != crate::protocol::API_NAME {
1051 return Err(ClientError::WrongApi {
1052 got: hello.api,
1053 want: crate::protocol::API_NAME,
1054 });
1055 }
1056 Ok(ControlClient {
1057 hello,
1058 reader,
1059 writer: Box::new(writer) as ControlWrite,
1060 })
1061}
1062
1063/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
1064pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
1065 let stream = connect_local(path).await?;
1066 let (read_half, write_half) = split_local(stream);
1067 connect_control_io(read_half, write_half).await
1068}
1069
1070/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
1071/// the quickstart front door — a consumer dials the running daemon without reimplementing
1072/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
1073/// (`NotFound`), same as a daemon that is not running.
1074pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
1075 connect_control(&crate::paths::default_endpoint()?).await
1076}
1077
1078// Seam-ported (Task 6): every stub daemon binds via the platform seam
1079// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
1080// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
1081// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
1082// `cargo test --workspace` feature unification turns `service` on for this crate (cli
1083// depends on local-api with features=["service"]), so the module compiles and RUNS on the
1084// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
1085#[cfg(all(test, feature = "service"))]
1086mod tests {
1087 use super::*;
1088 use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
1089 use crate::transport::{LocalListener, bind_local, split_local};
1090 use tokio::io::AsyncWriteExt;
1091
1092 /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
1093 /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
1094 /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
1095 /// on windows, whose pipe namespace needs no filesystem cleanup).
1096 #[cfg(unix)]
1097 fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
1098 let dir = tempfile::tempdir().unwrap();
1099 let path = dir.path().join(format!("{tag}.sock"));
1100 (path, dir)
1101 }
1102 #[cfg(windows)]
1103 fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
1104 use std::sync::atomic::{AtomicU64, Ordering};
1105 static SEQ: AtomicU64 = AtomicU64::new(0);
1106 let n = SEQ.fetch_add(1, Ordering::Relaxed);
1107 let path = std::path::PathBuf::from(format!(
1108 r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
1109 std::process::id()
1110 ));
1111 (path, ())
1112 }
1113
1114 /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
1115 async fn stub_daemon(mut listener: LocalListener) {
1116 let stream = listener.accept().await.unwrap();
1117 let (read_half, mut writer) = split_local(stream);
1118 write_frame(
1119 &mut writer,
1120 &serde_json::to_value(Hello {
1121 api: API_NAME.into(),
1122 api_version: API_VERSION.into(),
1123 api_minor: 0,
1124 stack_version: "0.1.0".into(),
1125 })
1126 .unwrap(),
1127 )
1128 .await
1129 .unwrap();
1130 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1131 let req = match reader.next().await.unwrap().unwrap() {
1132 Inbound::Frame(v) => v,
1133 Inbound::Violation(_) => panic!("violation"),
1134 };
1135 assert_eq!(req["method"], "status");
1136 let result = StatusResult {
1137 stack_version: "0.1.0".into(),
1138 services: vec![ServiceInfo {
1139 name: "kb".into(),
1140 allow: vec![],
1141 allow_display: vec![],
1142 backend: BackendKind::Socket,
1143 ephemeral: false,
1144 }],
1145 peers: vec![],
1146 roster: None,
1147 presence: vec![],
1148 self_user_id: None,
1149 self_user_key_held: false,
1150 recent_pairings: vec![],
1151 reachability: vec![],
1152 self_nickname: String::new(),
1153 storage: None,
1154 revoked: Vec::new(),
1155 self_network: None,
1156 };
1157 write_frame(
1158 &mut writer,
1159 &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
1160 )
1161 .await
1162 .unwrap();
1163 writer.flush().await.unwrap();
1164 }
1165
1166 /// The transport-agnostic front door: the same hello handshake over a plain in-memory
1167 /// duplex — what an embedded node's `Node::control` dials through.
1168 #[tokio::test]
1169 async fn connect_control_io_handshakes_over_a_duplex() {
1170 let (client_io, mut server_io) = tokio::io::duplex(4096);
1171 tokio::spawn(async move {
1172 write_frame(
1173 &mut server_io,
1174 &serde_json::to_value(Hello {
1175 api: API_NAME.into(),
1176 api_version: API_VERSION.into(),
1177 api_minor: 0,
1178 stack_version: "in-proc".into(),
1179 })
1180 .unwrap(),
1181 )
1182 .await
1183 .unwrap();
1184 });
1185 let (r, w) = tokio::io::split(client_io);
1186 let client = connect_control_io(r, w).await.expect("handshake");
1187 assert_eq!(client.hello().stack_version, "in-proc");
1188 }
1189
1190 #[tokio::test]
1191 async fn connect_reads_hello_asserts_api_and_requests() {
1192 let (sock, _guard) = test_endpoint("status");
1193 let listener = bind_local(&sock).unwrap();
1194 let server = tokio::spawn(stub_daemon(listener));
1195
1196 let mut client = connect_control(&sock).await.unwrap();
1197 assert_eq!(client.hello().api, API_NAME);
1198 let result = client.request(Request::Status).await.unwrap();
1199 assert_eq!(result["services"][0]["name"], "kb");
1200 assert_eq!(result["services"][0]["backend"], "socket");
1201 server.await.unwrap();
1202 }
1203
1204 #[tokio::test]
1205 async fn wrong_api_hello_is_rejected() {
1206 let (sock, _guard) = test_endpoint("wrongapi");
1207 let listener = bind_local(&sock).unwrap();
1208 tokio::spawn(async move {
1209 let mut listener = listener;
1210 let stream = listener.accept().await.unwrap();
1211 let (_r, mut w) = split_local(stream);
1212 write_frame(
1213 &mut w,
1214 &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
1215 )
1216 .await
1217 .unwrap();
1218 w.flush().await.unwrap();
1219 });
1220 match connect_control(&sock).await {
1221 Err(ClientError::WrongApi { got, want }) => {
1222 assert_eq!(got, "other/1");
1223 assert_eq!(want, API_NAME);
1224 }
1225 other => panic!("expected WrongApi, got {other:?}"),
1226 }
1227 }
1228
1229 #[tokio::test]
1230 async fn blob_fetch_and_publish_deserialize_typed_results() {
1231 use crate::protocol::{BlobFetchResult, BlobPublishResult};
1232 let (sock, _guard) = test_endpoint("blob");
1233 let listener = bind_local(&sock).unwrap();
1234 let server = tokio::spawn(async move {
1235 let mut listener = listener;
1236 let stream = listener.accept().await.unwrap();
1237 let (read_half, mut writer) = split_local(stream);
1238 write_frame(
1239 &mut writer,
1240 &serde_json::to_value(Hello {
1241 api: API_NAME.into(),
1242 api_version: API_VERSION.into(),
1243 api_minor: 0,
1244 stack_version: "0.1.0".into(),
1245 })
1246 .unwrap(),
1247 )
1248 .await
1249 .unwrap();
1250 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1251 // First request: blob_publish -> a ticket + hash.
1252 let req = match reader.next().await.unwrap().unwrap() {
1253 Inbound::Frame(v) => v,
1254 Inbound::Violation(_) => panic!("violation"),
1255 };
1256 assert_eq!(req["method"], "blob_publish");
1257 assert_eq!(req["params"]["scope"], "eng");
1258 write_frame(
1259 &mut writer,
1260 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
1261 )
1262 .await
1263 .unwrap();
1264 // Second request: blob_fetch -> a verified hash + length.
1265 let req = match reader.next().await.unwrap().unwrap() {
1266 Inbound::Frame(v) => v,
1267 Inbound::Violation(_) => panic!("violation"),
1268 };
1269 assert_eq!(req["method"], "blob_fetch");
1270 assert_eq!(req["params"]["ticket"], "blobT");
1271 assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
1272 write_frame(
1273 &mut writer,
1274 &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
1275 )
1276 .await
1277 .unwrap();
1278 let _ = (
1279 BlobFetchResult {
1280 hash: "cd".into(),
1281 bytes_len: 7,
1282 },
1283 BlobPublishResult {
1284 ticket: "blobT".into(),
1285 hash: "ab".into(),
1286 },
1287 );
1288 });
1289
1290 let mut client = connect_control(&sock).await.unwrap();
1291 let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
1292 assert_eq!(pub_res.ticket, "blobT");
1293 assert_eq!(pub_res.hash, "ab");
1294 let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
1295 assert_eq!(fetch_res.hash, "cd");
1296 assert_eq!(fetch_res.bytes_len, 7);
1297 server.await.unwrap();
1298 }
1299
1300 /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
1301 /// the Hello must survive `open_session` + kb's production re-box shape
1302 /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
1303 /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
1304 /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
1305 /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
1306 #[tokio::test]
1307 async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
1308 use tokio::io::AsyncRead;
1309
1310 let (sock, _guard) = test_endpoint("pipelined");
1311 let listener = bind_local(&sock).unwrap();
1312 let server = tokio::spawn(async move {
1313 let mut listener = listener;
1314 let stream = listener.accept().await.unwrap();
1315 let (read_half, mut writer) = split_local(stream);
1316 // ONE write carrying the Hello AND a session frame → both land in the
1317 // client's first BufReader fill (the read-ahead under test).
1318 let mut bytes = serde_json::to_vec(
1319 &serde_json::to_value(Hello {
1320 api: API_NAME.into(),
1321 api_version: API_VERSION.into(),
1322 api_minor: 0,
1323 stack_version: "0.1.0".into(),
1324 })
1325 .unwrap(),
1326 )
1327 .unwrap();
1328 bytes.push(b'\n');
1329 bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
1330 writer.write_all(&bytes).await.unwrap();
1331 writer.flush().await.unwrap();
1332 // Absorb the client's open_session frame so its write never sees EPIPE.
1333 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1334 let req = match reader.next().await.unwrap().unwrap() {
1335 Inbound::Frame(v) => v,
1336 Inbound::Violation(_) => panic!("violation"),
1337 };
1338 assert_eq!(req["method"], "open_session");
1339 });
1340
1341 let client = connect_control(&sock).await.unwrap();
1342 let (reader, _writer) = client
1343 .open_session("peer".into(), "kb".into())
1344 .await
1345 .unwrap();
1346 // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
1347 let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
1348 let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
1349 match reframed.next().await.unwrap() {
1350 Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
1351 other => panic!("pipelined frame was lost across the rebox: {other:?}"),
1352 }
1353 server.await.unwrap();
1354 }
1355
1356 #[tokio::test]
1357 async fn blob_grant_issues_request_and_acks() {
1358 let (sock, _guard) = test_endpoint("grant");
1359 let listener = bind_local(&sock).unwrap();
1360 let server = tokio::spawn(async move {
1361 let mut listener = listener;
1362 let stream = listener.accept().await.unwrap();
1363 let (read_half, mut writer) = split_local(stream);
1364 write_frame(
1365 &mut writer,
1366 &serde_json::to_value(Hello {
1367 api: API_NAME.into(),
1368 api_version: API_VERSION.into(),
1369 api_minor: 0,
1370 stack_version: "0.1.0".into(),
1371 })
1372 .unwrap(),
1373 )
1374 .await
1375 .unwrap();
1376 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1377 let req = match reader.next().await.unwrap().unwrap() {
1378 Inbound::Frame(v) => v,
1379 Inbound::Violation(_) => panic!("violation"),
1380 };
1381 assert_eq!(req["method"], "blob_grant");
1382 assert_eq!(req["params"]["scope"], "kb-sync");
1383 assert_eq!(req["params"]["principal"], "alice");
1384 write_frame(
1385 &mut writer,
1386 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
1387 )
1388 .await
1389 .unwrap();
1390 });
1391 let mut client = connect_control(&sock).await.unwrap();
1392 client.blob_grant("kb-sync", "alice").await.unwrap();
1393 server.await.unwrap();
1394 }
1395
1396 /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
1397 /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
1398 /// `ClientError::Malformed`, never a silently-wrong type).
1399 #[tokio::test]
1400 async fn typed_status_helper_deserializes_the_result() {
1401 let (sock, _guard) = test_endpoint("typedstatus");
1402 let listener = bind_local(&sock).unwrap();
1403 let server = tokio::spawn(stub_daemon(listener));
1404
1405 let mut client = connect_control(&sock).await.unwrap();
1406 let status = client.status().await.unwrap();
1407 assert_eq!(status.stack_version, "0.1.0");
1408 assert_eq!(status.services[0].name, "kb");
1409 assert_eq!(status.services[0].backend, BackendKind::Socket);
1410 assert!(status.peers.is_empty());
1411 server.await.unwrap();
1412 }
1413
1414 /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
1415 /// JSON-RPC error frame surfaces as `ClientError::Api`.
1416 #[tokio::test]
1417 async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
1418 let (sock, _guard) = test_endpoint("typedack");
1419 let listener = bind_local(&sock).unwrap();
1420 let server = tokio::spawn(async move {
1421 let mut listener = listener;
1422 let stream = listener.accept().await.unwrap();
1423 let (read_half, mut writer) = split_local(stream);
1424 write_frame(
1425 &mut writer,
1426 &serde_json::to_value(Hello {
1427 api: API_NAME.into(),
1428 api_version: API_VERSION.into(),
1429 api_minor: 0,
1430 stack_version: "0.1.0".into(),
1431 })
1432 .unwrap(),
1433 )
1434 .await
1435 .unwrap();
1436 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1437 // peer_remove → ack.
1438 let req = match reader.next().await.unwrap().unwrap() {
1439 Inbound::Frame(v) => v,
1440 Inbound::Violation(_) => panic!("violation"),
1441 };
1442 assert_eq!(req["method"], "peer_remove");
1443 assert_eq!(req["params"]["nickname"], "bob");
1444 write_frame(
1445 &mut writer,
1446 &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1447 )
1448 .await
1449 .unwrap();
1450 // peer_rename → an error frame (collision refusal).
1451 let req = match reader.next().await.unwrap().unwrap() {
1452 Inbound::Frame(v) => v,
1453 Inbound::Violation(_) => panic!("violation"),
1454 };
1455 assert_eq!(req["method"], "peer_rename");
1456 assert_eq!(req["params"]["to"], "Bobby");
1457 write_frame(
1458 &mut writer,
1459 &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1460 )
1461 .await
1462 .unwrap();
1463 });
1464
1465 let mut client = connect_control(&sock).await.unwrap();
1466 client.peer_remove("bob").await.unwrap();
1467 match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1468 Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1469 other => panic!("expected Api error, got {other:?}"),
1470 }
1471 server.await.unwrap();
1472 }
1473
1474 /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
1475 /// `None` when the daemon side closes.
1476 #[tokio::test]
1477 async fn typed_subscribe_yields_frames_then_end() {
1478 use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1479
1480 let (sock, _guard) = test_endpoint("subscribe");
1481 let listener = bind_local(&sock).unwrap();
1482 let server = tokio::spawn(async move {
1483 let mut listener = listener;
1484 let stream = listener.accept().await.unwrap();
1485 let (read_half, mut writer) = split_local(stream);
1486 write_frame(
1487 &mut writer,
1488 &serde_json::to_value(Hello {
1489 api: API_NAME.into(),
1490 api_version: API_VERSION.into(),
1491 api_minor: 0,
1492 stack_version: "0.1.0".into(),
1493 })
1494 .unwrap(),
1495 )
1496 .await
1497 .unwrap();
1498 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1499 let req = match reader.next().await.unwrap().unwrap() {
1500 Inbound::Frame(v) => v,
1501 Inbound::Violation(_) => panic!("violation"),
1502 };
1503 assert_eq!(req["method"], "subscribe");
1504 for frame in [
1505 StreamFrame::Snapshot {
1506 self_network: None,
1507 active_sessions: vec![ActiveSession {
1508 peer: "bob".into(),
1509 service: "notes".into(),
1510 opened_at: 7,
1511 principal: Some("eid:bob".into()),
1512 }],
1513 reachability: vec![PeerReachability {
1514 name: "bob".into(),
1515 reachable: true,
1516 rtt_ms: Some(42),
1517 age_secs: Some(3),
1518 meta: String::new(),
1519 principal: None,
1520 path: Default::default(),
1521 }],
1522 },
1523 StreamFrame::Event {
1524 record: Box::new(AuditRecord::session_open(
1525 "2026-07-03T14:02:11.480Z".into(),
1526 Some("bob".into()),
1527 "notes".into(),
1528 None,
1529 )),
1530 },
1531 StreamFrame::Lagged { dropped: 12 },
1532 ] {
1533 write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1534 .await
1535 .unwrap();
1536 }
1537 writer.flush().await.unwrap();
1538 // Drop the connection: the client must see the stream END (Ok(None)), not an error.
1539 });
1540
1541 let client = connect_control(&sock).await.unwrap();
1542 let mut sub = client.subscribe().await.unwrap();
1543 match sub.next().await.unwrap().unwrap() {
1544 StreamFrame::Snapshot {
1545 active_sessions,
1546 reachability,
1547 ..
1548 } => {
1549 assert_eq!(active_sessions[0].peer, "bob");
1550 assert_eq!(reachability[0].rtt_ms, Some(42));
1551 }
1552 other => panic!("expected the snapshot first, got {other:?}"),
1553 }
1554 match sub.next().await.unwrap().unwrap() {
1555 StreamFrame::Event { record } => {
1556 assert_eq!(record.peer.as_deref(), Some("bob"));
1557 assert_eq!(record.service.as_deref(), Some("notes"));
1558 }
1559 other => panic!("expected the event, got {other:?}"),
1560 }
1561 assert_eq!(
1562 sub.next().await.unwrap(),
1563 Some(StreamFrame::Lagged { dropped: 12 })
1564 );
1565 assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1566 server.await.unwrap();
1567 }
1568}