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