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