Skip to main content

rings_node/native/
cli.rs

1//! Native CLI JSON-RPC client wrapper for `rings` subcommands.
2//!
3//! Wraps [`rings_rpc::jsonrpc::Client`] for a running `rings-node` daemon. Construct unauthenticated
4//! clients with [`Client::new`] or Bearer-authenticated clients with [`Client::with_api_token`].
5//!
6//! # Capabilities
7//!
8//! - Establish WebRTC connections via HTTP signaling, seed documents, DHT routing, or manual SDP offers/answers.
9//! - Send namespace-scoped backend messages over the overlay.
10//! - Publish and subscribe to DHT data topics.
11//! - Register and look up services in the DHT.
12//! - Inspect swarm peers, Chord ring topology, and storage state.
13
14use std::time::Duration;
15
16use async_stream::stream;
17use futures::pin_mut;
18use futures::select;
19use futures::FutureExt;
20use futures::Stream;
21use rings_rpc::jsonrpc::Client as RpcClient;
22use rings_rpc::protos::rings_node::AcceptAnswerRequest;
23use rings_rpc::protos::rings_node::AnswerOfferRequest;
24use rings_rpc::protos::rings_node::ConnectPeerViaHttpRequest;
25use rings_rpc::protos::rings_node::ConnectWithDidRequest;
26use rings_rpc::protos::rings_node::CreateOfferRequest;
27use rings_rpc::protos::rings_node::DisconnectRequest;
28use rings_rpc::protos::rings_node::FetchTopicMessagesRequest;
29use rings_rpc::protos::rings_node::ListPeersRequest;
30use rings_rpc::protos::rings_node::LookupServiceRequest;
31use rings_rpc::protos::rings_node::NodeInfoRequest;
32use rings_rpc::protos::rings_node::PublishMessageToTopicRequest;
33use rings_rpc::protos::rings_node::RegisterServiceRequest;
34use rings_rpc::protos::rings_node::SendBackendMessageRequest;
35use rings_rpc::protos::rings_node::SwarmInfo;
36
37pub use crate::processor::handshake::OfferReplyKind;
38use crate::seed::Seed;
39use crate::util::loader::ResourceLoader;
40
41/// Alias about `Result<ClientOutput<T>, E>`.
42type Output<T> = anyhow::Result<ClientOutput<T>>;
43
44/// Wrap json_client send request between nodes or browsers.
45pub struct Client {
46    client: RpcClient,
47}
48
49/// Wrap client output contain raw result and humanreadable display.
50pub struct ClientOutput<T> {
51    /// Output data.
52    pub result: T,
53    display: String,
54    stderr_notice: Option<String>,
55}
56
57impl OfferReplyKind {
58    /// Operator notice printed to stderr so stdout stays the raw base58 payload for piping.
59    pub const fn stderr_notice(self) -> &'static str {
60        match self {
61            Self::Answer => {
62                "Answered peer's offer (answer); return this payload to the offerer for `rings connect accept`."
63            }
64            Self::CounterOffer => {
65                "Counter-offer (offer, answered: false): this node's pending offer prevailed on the DID tie-break. \
66                 Pass this counter-offer to the peer for `rings connect answer`, then complete on this node with `rings connect accept`."
67            }
68        }
69    }
70}
71
72/// Build the `ClientOutput` for an encoded `answerOffer` reply.
73pub fn format_answer_offer_output(reply: String) -> Output<String> {
74    let notice = match OfferReplyKind::from_encoded_reply(reply.as_str()) {
75        Ok(kind) => kind.stderr_notice().to_owned(),
76        Err(_) => OfferReplyKind::Answer.stderr_notice().to_owned(),
77    };
78    ClientOutput::ok_with_stderr(reply.clone(), reply, notice)
79}
80
81/// Reject an encoded `ConnectNodeSend` counter-offer passed to `connect accept` with a clear
82/// operator message pointing to `rings connect answer`.
83pub fn ensure_accept_answer_is_not_counter_offer(answer: &str) -> anyhow::Result<()> {
84    if matches!(
85        OfferReplyKind::from_encoded_reply(answer),
86        Ok(OfferReplyKind::CounterOffer)
87    ) {
88        anyhow::bail!(
89            "payload is a counter-offer (`ConnectNodeSend`), not an answer (`ConnectNodeReport`); \
90             answer it with `rings connect answer <counter_offer>` and pass the resulting answer \
91             to the peer's `rings connect accept`"
92        );
93    }
94    Ok(())
95}
96
97impl Client {
98    /// Creates an unauthenticated JSON-RPC client targeting `endpoint_url`.
99    pub fn new(endpoint_url: &str) -> anyhow::Result<Self> {
100        let rpc_client =
101            RpcClient::new(endpoint_url).map_err(|error| anyhow::anyhow!("{error}"))?;
102        Ok(Self { client: rpc_client })
103    }
104
105    /// Creates a client for an endpoint protected by the supplied API Bearer token.
106    pub fn with_api_token(endpoint_url: &str, api_token: String) -> anyhow::Result<Self> {
107        let rpc_client = RpcClient::new(endpoint_url)
108            .and_then(|client| client.with_bearer_token(api_token))
109            .map_err(|error| anyhow::anyhow!("{error}"))?;
110        Ok(Self { client: rpc_client })
111    }
112
113    /// Establishes a WebRTC connection with a remote peer using HTTP as the signaling channel.
114    ///
115    /// This function allows two peers to establish a WebRTC connection using HTTP,
116    /// which can be useful in scenarios where a direct peer-to-peer connection is not possible due to firewall restrictions or other network issues.
117    /// The function sends ICE candidates and Session Description Protocol (SDP) messages over HTTP as a form of signaling to establish the connection.
118    ///
119    /// Takes a URL for an HTTP server that will be used as the signaling channel to exchange ICE candidates and SDP with the remote peer.
120    /// Returns a Did that can be used to refer to this connection in subsequent WebRTC operations.
121    pub async fn connect_peer_via_http(&mut self, url: &str) -> Output<String> {
122        self.connect_peer_via_http_with_token(url, None).await
123    }
124
125    /// Establishes a WebRTC connection through a remote API, presenting a Bearer token only
126    /// when the remote gates its otherwise public handshake.
127    pub async fn connect_peer_via_http_with_token(
128        &mut self,
129        url: &str,
130        remote_api_token: Option<String>,
131    ) -> Output<String> {
132        let peer_did = self
133            .client
134            .connect_peer_via_http(&ConnectPeerViaHttpRequest {
135                url: url.to_string(),
136                api_token: remote_api_token,
137            })
138            .await
139            .map_err(|e| anyhow::anyhow!("{}", e))?
140            .did;
141
142        ClientOutput::ok(format!("Remote did: {peer_did}"), peer_did)
143    }
144
145    /// Attempts to connect to a peer using a seed file located at the specified source path.
146    pub async fn connect_with_seed(&mut self, source: &str) -> Output<()> {
147        let seed = Seed::load(source).await?;
148        let req = seed.into_connect_with_seed_request();
149
150        self.client
151            .connect_with_seed(&req)
152            .await
153            .map_err(|e| anyhow::anyhow!("{}", e))?;
154
155        ClientOutput::ok("Successful!".to_string(), ())
156    }
157
158    /// Attempts to connect to a peer using a DID stored in a Distributed Hash Table (DHT).
159    pub async fn connect_with_did(&mut self, did: &str) -> Output<()> {
160        self.client
161            .connect_with_did(&ConnectWithDidRequest {
162                did: did.to_string(),
163            })
164            .await
165            .map_err(|e| anyhow::anyhow!("{}", e))?;
166        ClientOutput::ok("Successful!".to_owned(), ())
167    }
168
169    /// Creates a local WebRTC offer targeting `did` for a manual, out-of-band handshake.
170    ///
171    /// Returns the base58-check encoded offer payload, which the remote peer feeds to
172    /// [`answer_offer`](Self::answer_offer). Use this when the peers cannot signal over
173    /// HTTP and the offer/answer strings are exchanged by other means (copy/paste, QR, chat).
174    pub async fn create_offer(&mut self, did: &str) -> Output<String> {
175        let offer = self
176            .client
177            .create_offer(&CreateOfferRequest {
178                did: did.to_string(),
179            })
180            .await
181            .map_err(|e| anyhow::anyhow!("{}", e))?
182            .offer;
183
184        ClientOutput::ok(offer.clone(), offer)
185    }
186
187    /// Answers a peer's offer, producing the encoded answer (or counter-offer) to return to the
188    /// offerer.
189    ///
190    /// Consumes the encoded offer emitted by [`create_offer`](Self::create_offer) and returns the
191    /// base58-check encoded reply payload. When the reply is an answer (`ConnectNodeReport`), the
192    /// offerer feeds it to [`accept_answer`](Self::accept_answer). When the reply is a
193    /// counter-offer (`ConnectNodeSend`), the peer answers it with `answer_offer` and returns
194    /// that answer to this node's [`accept_answer`](Self::accept_answer).
195    pub async fn answer_offer(&mut self, offer: &str) -> Output<String> {
196        let answer = self
197            .client
198            .answer_offer(&AnswerOfferRequest {
199                offer: offer.to_string(),
200            })
201            .await
202            .map_err(|e| anyhow::anyhow!("{}", e))?
203            .answer;
204
205        format_answer_offer_output(answer)
206    }
207
208    /// Accepts a peer's answer, completing the manual handshake initiated by
209    /// [`create_offer`](Self::create_offer).
210    ///
211    /// Refuses a counter-offer (`ConnectNodeSend`) before sending the RPC request, pointing the
212    /// operator to `rings connect answer` instead.
213    pub async fn accept_answer(&mut self, answer: &str) -> Output<()> {
214        ensure_accept_answer_is_not_counter_offer(answer)?;
215        self.client
216            .accept_answer(&AcceptAnswerRequest {
217                answer: answer.to_string(),
218            })
219            .await
220            .map_err(|e| anyhow::anyhow!("{}", e))?;
221
222        ClientOutput::ok("Done.".into(), ())
223    }
224
225    /// Lists all connected peers and their status.
226    ///
227    /// Returns an Output containing a formatted string representation of the list of peers if successful, or an anyhow::Error if an error occurred.
228    pub async fn list_peers(&mut self) -> Output<()> {
229        let peers = self
230            .client
231            .list_peers(&ListPeersRequest {})
232            .await
233            .map_err(|e| anyhow::anyhow!("{}", e))?
234            .peers;
235
236        let mut display = String::new();
237        display.push_str("Did, TransportId, Status\n");
238        display.push_str(
239            peers
240                .iter()
241                .map(|peer| format!("{}, {}, {}", peer.did, peer.did, peer.state))
242                .collect::<Vec<_>>()
243                .join("\n")
244                .as_str(),
245        );
246
247        ClientOutput::ok(display, ())
248    }
249
250    /// Disconnects from the peer with the specified DID.
251    pub async fn disconnect(&mut self, did: &str) -> Output<()> {
252        self.client
253            .disconnect(&DisconnectRequest {
254                did: did.to_string(),
255            })
256            .await
257            .map_err(|e| anyhow::anyhow!("{}", e))?;
258
259        ClientOutput::ok("Done.".into(), ())
260    }
261
262    /// Sends a namespaced message to the specified peer, routed to the peer's protocol
263    /// registered under `namespace` (the extension `Envelope` model).
264    pub async fn send_message(&self, did: &str, namespace: &str, data: &str) -> Output<()> {
265        self.client
266            .send_backend_message(&SendBackendMessageRequest {
267                destination_did: did.to_string(),
268                namespace: namespace.to_string(),
269                // The wire field is base64 (binary-safe); encode the raw input bytes.
270                data: base64::encode(data.as_bytes()),
271            })
272            .await
273            .map_err(|e| anyhow::anyhow!("{}", e))?;
274        ClientOutput::ok("Done.".into(), ())
275    }
276
277    /// Registers a new service with the given name.
278    pub async fn register_service(&self, name: &str) -> Output<()> {
279        self.client
280            .register_service(&RegisterServiceRequest {
281                name: name.to_string(),
282            })
283            .await
284            .map_err(|e| anyhow::anyhow!("{}", e))?;
285        ClientOutput::ok("Done.".into(), ())
286    }
287
288    /// Looks up the DIDs of services registered with the given name.
289    pub async fn lookup_service(&self, name: &str) -> Output<()> {
290        let dids = self
291            .client
292            .lookup_service(&LookupServiceRequest {
293                name: name.to_string(),
294            })
295            .await
296            .map_err(|e| anyhow::anyhow!("{}", e))?
297            .dids;
298
299        ClientOutput::ok(dids.join("\n"), ())
300    }
301
302    /// Publishes a message to the specified topic.
303    pub async fn publish_message_to_topic(&self, topic: &str, data: &str) -> Output<()> {
304        self.client
305            .publish_message_to_topic(&PublishMessageToTopicRequest {
306                topic: topic.to_string(),
307                data: data.to_string(),
308            })
309            .await
310            .map_err(|e| anyhow::anyhow!("{}", e))?;
311        ClientOutput::ok("Done.".into(), ())
312    }
313
314    /// Subscribes to the specified topic and returns a stream of messages published to the topic.
315    pub async fn subscribe_topic<'a, 'b>(
316        &'a self,
317        topic: String,
318    ) -> impl Stream<Item = String> + 'b
319    where
320        'a: 'b,
321    {
322        let mut skip = 0usize;
323
324        stream! {
325            loop {
326                let timeout = rings_runtime::sleep(Duration::from_secs(5)).fuse();
327                pin_mut!(timeout);
328
329                select! {
330                    _ = timeout => {
331                        let result = self
332                            .client
333                            .fetch_topic_messages(&FetchTopicMessagesRequest {
334                                topic: topic.clone(),
335                                skip: skip as i64,
336                            })
337                            .await;
338
339                        let messages = match result {
340                            Ok(result) => result.data,
341                            Err(e) => {
342                                tracing::error!("Failed to fetch messages of topic: {}, {}", topic, e);
343                                continue;
344                            }
345                        };
346                        for msg in messages.iter().cloned() {
347                            yield msg
348                        }
349                        skip += messages.len();
350                    }
351                }
352            }
353        }
354    }
355
356    /// Query for swarm inspect info.
357    pub async fn inspect(&self) -> Output<SwarmInfo> {
358        let swarm_info = self
359            .client
360            .node_info(&NodeInfoRequest {})
361            .await
362            .map_err(|e| anyhow::anyhow!("{}", e))?
363            .swarm
364            .ok_or_else(|| anyhow::anyhow!("node_info response did not include swarm info"))?;
365
366        let display =
367            serde_json::to_string_pretty(&swarm_info).map_err(|e| anyhow::anyhow!("{}", e))?;
368
369        ClientOutput::ok(display, swarm_info)
370    }
371}
372
373impl<T> ClientOutput<T> {
374    /// Put display ahead to avoid moved value error.
375    pub fn ok(display: String, result: T) -> anyhow::Result<Self> {
376        Ok(Self {
377            result,
378            display,
379            stderr_notice: None,
380        })
381    }
382
383    /// Construct a `ClientOutput` with an additional operator notice printed to stderr.
384    pub fn ok_with_stderr(
385        display: String,
386        result: T,
387        stderr_notice: String,
388    ) -> anyhow::Result<Self> {
389        Ok(Self {
390            result,
391            display,
392            stderr_notice: Some(stderr_notice),
393        })
394    }
395
396    /// Human-readable stdout string.
397    pub fn display_text(&self) -> &str {
398        self.display.as_str()
399    }
400
401    /// Optional operator notice printed to stderr.
402    pub fn stderr_notice(&self) -> Option<&str> {
403        self.stderr_notice.as_deref()
404    }
405
406    /// Prints the display value of this ClientOutput instance to the console, and any operator
407    /// notice to stderr.
408    pub fn display(&self) {
409        if let Some(notice) = &self.stderr_notice {
410            eprintln!("{notice}");
411        }
412        println!("{}", self.display);
413    }
414}
415
416/// CLI constructors must preserve the shared RPC credential transport boundary.
417#[cfg(test)]
418mod credential_transport_tests {
419    use rings_core::delegation::DelegateeKey;
420    use rings_core::dht::delivery::NextHop;
421    use rings_core::dht::Did;
422    use rings_core::dht::RelayCustody;
423    use rings_core::ecc::SecretKey;
424    use rings_core::message::ConnectNodeReport;
425    use rings_core::message::ConnectNodeSend;
426    use rings_core::message::DhtProtocolMode;
427    use rings_core::message::Encoder;
428    use rings_core::message::Message;
429    use rings_core::message::MessagePayload;
430    use rings_core::message::MessageSigner;
431
432    use super::ensure_accept_answer_is_not_counter_offer;
433    use super::format_answer_offer_output;
434    use super::Client;
435    use super::OfferReplyKind;
436
437    fn encoded_handshake_payload(message: Message) -> String {
438        let key = SecretKey::random();
439        let delegatee_key = DelegateeKey::new_with_seckey(&key).expect("test delegatee key");
440        let signer = MessageSigner::new(&delegatee_key, 1);
441        let destination: Did = SecretKey::random().address().into();
442        let payload = MessagePayload::new_send_with_sequence(
443            message,
444            signer,
445            NextHop::toward(destination),
446            destination,
447            0,
448            None,
449        )
450        .expect("signed handshake payload");
451        payload.encode().expect("encoded payload").to_string()
452    }
453
454    fn encoded_answer_fixture() -> String {
455        encoded_handshake_payload(Message::ConnectNodeReport(ConnectNodeReport {
456            step_index: 1,
457            final_step: true,
458            session_id: None,
459            handshake: bytes::Bytes::from_static(b"{\"type\":\"answer\"}"),
460            dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
461            relay_custody: RelayCustody::Holds,
462        }))
463    }
464
465    fn encoded_counter_offer_fixture() -> String {
466        encoded_handshake_payload(Message::ConnectNodeSend(ConnectNodeSend {
467            step_index: 0,
468            final_step: false,
469            session_id: None,
470            handshake: bytes::Bytes::from_static(b"{\"type\":\"offer\"}"),
471            dht_protocol_mode: DhtProtocolMode::new(1, 1, 1),
472            relay_custody: RelayCustody::Holds,
473        }))
474    }
475
476    /// An endpoint override cannot carry the API credential over remote cleartext HTTP.
477    #[test]
478    fn authenticated_cli_rejects_remote_http() {
479        for endpoint in [
480            "http://example.com",
481            "http://localhost.example.com",
482            "http://127.0.0.1.example.com",
483        ] {
484            assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_err());
485        }
486    }
487
488    /// Explicit loopback IP endpoints and HTTPS remain available through the CLI wrapper.
489    #[test]
490    fn authenticated_cli_accepts_https_and_literal_loopback() {
491        for endpoint in [
492            "https://example.com",
493            "http://127.0.0.1:50000",
494            "http://[::1]:50000",
495        ] {
496            assert!(Client::with_api_token(endpoint, "fixture-token".to_owned()).is_ok());
497        }
498    }
499
500    /// `answer_offer` output for an answer (`ConnectNodeReport`, `answered: true`) keeps the
501    /// raw payload on stdout and labels the reply as an answer for `connect accept` on stderr.
502    #[test]
503    fn answer_offer_formats_answer_reply() {
504        let answer = encoded_answer_fixture();
505        assert_eq!(
506            OfferReplyKind::from_encoded_reply(answer.as_str()).expect("classify answer"),
507            OfferReplyKind::Answer
508        );
509
510        let output = format_answer_offer_output(answer.clone()).expect("format answer output");
511        assert_eq!(output.result, answer);
512        assert_eq!(output.display_text(), answer);
513        let notice = output.stderr_notice().expect("stderr notice for answer");
514        assert!(notice.contains("answer"), "unexpected notice: {notice}");
515        assert!(
516            notice.contains("rings connect accept"),
517            "unexpected notice: {notice}"
518        );
519    }
520
521    /// `answer_offer` output for a counter-offer (`ConnectNodeSend`, `answered: false`) keeps
522    /// the raw payload on stdout and explains on stderr that the peer must run `connect answer`
523    /// and return that answer to this node's `connect accept`.
524    #[test]
525    fn answer_offer_formats_counter_offer_reply() {
526        let counter_offer = encoded_counter_offer_fixture();
527        assert_eq!(
528            OfferReplyKind::from_encoded_reply(counter_offer.as_str())
529                .expect("classify counter-offer"),
530            OfferReplyKind::CounterOffer
531        );
532
533        let output =
534            format_answer_offer_output(counter_offer.clone()).expect("format counter-offer output");
535        assert_eq!(output.result, counter_offer);
536        assert_eq!(output.display_text(), counter_offer);
537        let notice = output
538            .stderr_notice()
539            .expect("stderr notice for counter-offer");
540        assert!(
541            notice.contains("Counter-offer"),
542            "unexpected notice: {notice}"
543        );
544        assert!(
545            notice.contains("answered: false"),
546            "unexpected notice: {notice}"
547        );
548        assert!(
549            notice.contains("rings connect answer"),
550            "unexpected notice: {notice}"
551        );
552        assert!(
553            notice.contains("rings connect accept"),
554            "unexpected notice: {notice}"
555        );
556    }
557
558    /// `connect accept` refuses a counter-offer (`ConnectNodeSend`) with an explanation pointing
559    /// to `rings connect answer`, while allowing an answer (`ConnectNodeReport`).
560    #[test]
561    fn accept_answer_refuses_counter_offer_with_clear_instruction() {
562        let answer = encoded_answer_fixture();
563        assert!(ensure_accept_answer_is_not_counter_offer(answer.as_str()).is_ok());
564
565        let counter_offer = encoded_counter_offer_fixture();
566        let err = ensure_accept_answer_is_not_counter_offer(counter_offer.as_str())
567            .expect_err("counter-offer must be refused by connect accept");
568        let msg = err.to_string();
569        assert!(msg.contains("counter-offer"), "unexpected error: {msg}");
570        assert!(
571            msg.contains("rings connect answer"),
572            "unexpected error: {msg}"
573        );
574        assert!(
575            msg.contains("rings connect accept"),
576            "unexpected error: {msg}"
577        );
578    }
579}