plexus-core 0.11.3

Core infrastructure for Plexus RPC: Activation trait, DynamicHub, schemas
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! VISION-5 (LOCAL-5) · dial-out: a service with no listening port opens one
//! WebSocket to another service (a relay), signs in with its key on the
//! upgrade (spec/00), offers an activation on that socket (spec/14,
//! `{svc}.offer`) and serves it there — the far side of spec/12, the calls
//! coming in on the socket it opened. The same socket carries its own calls
//! out ([`Exposed::call`]): to the relay, and through it to every other
//! peer connected there.
//!
//! ```ignore
//! let exposed = Exposed::new(DialOut::new("wss://relay.example/ws", "~/.plexus/keys/alice.key").trust("key:<relay's>").mount("alice"));
//! exposed.serve(Greeter::new(exposed.clone()));   // reconnects, within its backoff, until stopped
//! exposed.mounted(Duration::from_secs(10)).await?; // `peers.alice` at the relay
//! let items = exposed.call("peers.bob.hello", json!({ "name": "alice" })).await;
//! ```
//!
//! | when | then |
//! | -- | -- |
//! | the socket opens | `_info` names the relay's `{svc}`; the offer goes as `{svc}.offer {namespace, activations, mount?}`; the relay asks the schema over the socket and answers the offer once mounted |
//! | no trusted key ([`DialOut::trust`]) | refused before dialing (KEEL-8) |
//! | the socket opens | the relay proves the trusted key at `_info {nonce}` (DYNAUTH-5's proof); none, or another: refused, nothing it sends served |
//! | the relay calls `{ns}.call {method, params, hop}` | served as a child serves (RETURNS-47's host) on a proven connection: each call in the hop's context, the hop believed only when it names the proven key |
//! | this side calls [`Exposed::call`] | `{svc}.call {method, params}` on the same socket: decided by the relay's gate as this key |
//! | the socket drops | every call either way ends; the state is `down`; it dials again within [`DialOut::backoff`] and offers again |
//! | the offer is refused | the state is `refused` naming why; it does not dial again until [`Exposed::serve`] is called again |
//! | NEST-25: no `trust`, a known-hosts file ([`Exposed::with_first_contact`]) | the key pinned there for the URL is the trusted one; another key presented is refused loudly, never asked again |
//! | NEST-25: first contact (no key known) | the relay proves a key at `_info`; nothing more is sent or served until the callback says yes (none: refused) — shown the key, its fingerprint and the pairing code; a yes pins it in the file |
//! | NEST-25: the host holds the offer pending | the state stays `connecting`, [`Exposed::pending`] names the pairing code, the socket is kept within [`Exposed::with_pending_for`] |
//! | NEST-25: this side's activation calls back (`_host.call`) | sent on the socket in an id space of its own (`h:<n>`), its answers and items routed back to it |

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures::future::BoxFuture;
use futures::{SinkExt, StreamExt};
use serde::Serialize;
use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::{header::AUTHORIZATION, HeaderValue};
use tokio_tungstenite::tungstenite::Message;

use super::host::ChildPeer;
use super::link::{unavailable, Conn, Counters, SubKey};
use super::pairing::{commitment, key_fingerprint, pairing_code, KnownHosts};
use super::spec::{check_ws_url, is_insecure_ws, INSECURE_TRANSPORT};
use super::upcall::{HOST_CALL, HOST_CALL_UNSUB};
use super::ws::{key_proof, principal_of, read_seed};
use ed25519_dalek::Signer;
use super::Backoff;
use crate::plexus::plexus::Activation;
use crate::plexus::streaming::PlexusStream;
use crate::plexus::types::PlexusStreamItem;

/// Where a service dials out to, as whom, and under what name it asks to be
/// mounted.
#[derive(Debug, Clone)]
pub struct DialOut {
    /// The relay's socket: `ws://HOST:PORT/ws` (`wss://` with `child-wss`).
    pub url: String,
    /// The key file the upgrade's proof is signed with (spec/00): synapse's
    /// `~/.plexus/keys/<name>.key`, 0600. Read at each dial, never kept.
    pub key: PathBuf,
    /// The proof's agent id.
    pub agent: String,
    /// The mount name asked for (`peers.<mount>`); none: the activation's
    /// namespace.
    pub mount: Option<String>,
    /// The relay's key (`key:<64 hex>`), pinned (spec/14 rule 4). KEEL-8:
    /// required — none, and the dial-out is refused before dialing. At each
    /// connect the relay proves it at `_info` (the nonce signed, as a
    /// mount's child proves its key, DYNAUTH-5); a relay that proves none,
    /// or another, is refused and nothing it sends is served. A hop is
    /// believed only when it names this key as the service acting.
    pub trust: Option<String>,
    /// Dialing again after the socket drops.
    pub backoff: Backoff,
    /// `_info`, the offer's answer, and each of this side's calls' opens.
    pub timeout: Duration,
    /// KEEL-7: dial plain `ws://` beyond loopback (`transport.insecure_ws`,
    /// a test network's). Off: such a relay is refused before a socket opens
    /// ([`check_ws_url`]); on: dialed, and [`DialState::Mounted`] says
    /// `insecure`.
    pub insecure_ws: bool,
    /// KEEL-8 (DYNAUTH-8): a PEM file of certificate authorities a `wss://`
    /// relay's certificate may chain to, beside the webpki roots — as a
    /// mount's [`ChildOptions::tls_roots`](super::ChildOptions::tls_roots).
    pub tls_roots: Option<PathBuf>,
}

impl DialOut {
    /// Dial `url`, signed in with the key in `key`.
    pub fn new(url: impl Into<String>, key: impl Into<PathBuf>) -> Self {
        Self {
            url: url.into(),
            key: key.into(),
            agent: "plexus-service".into(),
            mount: None,
            trust: None,
            backoff: Backoff { initial: Duration::from_millis(250), max: Duration::from_secs(10), per_minute: usize::MAX },
            timeout: Duration::from_secs(10),
            insecure_ws: false,
            tls_roots: None,
        }
    }

    /// Ask to be mounted as `name`.
    pub fn mount(mut self, name: impl Into<String>) -> Self {
        self.mount = Some(name.into());
        self
    }

    /// The relay's key (`key:<64 hex>`): it must prove it at each connect,
    /// and hops are believed only from it (pinned).
    pub fn trust(mut self, principal: impl Into<String>) -> Self {
        self.trust = Some(principal.into());
        self
    }

    /// The proof's agent id.
    pub fn agent(mut self, agent: impl Into<String>) -> Self {
        self.agent = agent.into();
        self
    }

    /// KEEL-7: allow plain `ws://` beyond loopback ([`DialOut::insecure_ws`]).
    pub fn insecure_ws(mut self, on: bool) -> Self {
        self.insecure_ws = on;
        self
    }

    /// KEEL-8: a PEM file of CAs a `wss://` relay may chain to
    /// ([`DialOut::tls_roots`]).
    pub fn tls_roots(mut self, roots: impl Into<PathBuf>) -> Self {
        self.tls_roots = Some(roots.into());
        self
    }

    /// KEEL-7: [`DialOut::insecure_ws`] as `transport.insecure_ws` in `c`
    /// says, when it says more than its default; KEEL-8: and
    /// [`DialOut::tls_roots`] as `transport.tls_roots` says.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn configured(mut self, c: &crate::plexus::config::Config) -> Self {
        use crate::plexus::config::{settings::{TRANSPORT_INSECURE_WS, TRANSPORT_TLS_ROOTS}, Source};
        if c.source(&TRANSPORT_INSECURE_WS) != Source::Default {
            self.insecure_ws = c.get(&TRANSPORT_INSECURE_WS);
        }
        if c.source(&TRANSPORT_TLS_ROOTS) != Source::Default {
            self.tls_roots = c.get(&TRANSPORT_TLS_ROOTS).map(Into::into);
        }
        self
    }
}

/// Where a dialed-out service stands.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DialState {
    /// Not yet dialed, or dialing.
    Connecting,
    /// Mounted at the relay as `path` (`peers.<mount>`). `insecure`
    /// (KEEL-7): over plain `ws://` beyond loopback, as
    /// [`DialOut::insecure_ws`] allowed.
    Mounted {
        mount: String,
        path: String,
        service: String,
        relay: String,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        insecure: bool,
    },
    /// The socket dropped or could not open; dialing again.
    Down { why: String },
    /// The relay refused the offer; not dialing again.
    Refused { why: String },
    /// [`Exposed::stop`]ped.
    Stopped,
}

struct Live {
    conn: Arc<Conn>,
    service: String,
}

/// NEST-25: what a node is shown at first contact with a host it has no key
/// for — the key the host proved at `_info`, its fingerprint, and this
/// connection's pairing code, which the host's operator sees too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FirstContact {
    pub url: String,
    /// `key:<64 hex>`.
    pub key: String,
    /// `SHA256:<base64>`, as ssh shows a host key.
    pub fingerprint: String,
    /// `XXXX-XXXX`, when the host answered the pairing (`host_nonce`).
    pub code: Option<String>,
}

type Ask = Arc<dyn Fn(FirstContact) -> BoxFuture<'static, bool> + Send + Sync>;

#[derive(Clone)]
struct First {
    hosts: KnownHosts,
    ask: Option<Ask>,
}

struct ExposedInner {
    opts: DialOut,
    live: Mutex<Option<Live>>,
    state: watch::Sender<DialState>,
    task: Mutex<Option<tokio::task::AbortHandle>>,
    counters: Arc<Counters>,
    /// NEST-25: the known-hosts file and who says yes at first contact.
    first: Mutex<Option<First>>,
    /// NEST-25: this connection's pairing code, and whether the host holds
    /// the offer pending now.
    code: Mutex<Option<String>>,
    pending: AtomicBool,
    pending_for: Mutex<Duration>,
}

impl Drop for ExposedInner {
    fn drop(&mut self) {
        if let Some(t) = self.task.lock().unwrap().take() {
            t.abort();
        }
    }
}

/// A service's one outbound socket to a relay: what it serves there, and
/// the calls it makes over it. Cheap to clone; [`Self::serve`] holds a weak
/// reference, so the socket goes with the last clone (or [`Self::stop`]).
#[derive(Clone)]
pub struct Exposed {
    inner: Arc<ExposedInner>,
}

impl std::fmt::Debug for Exposed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Exposed").field("url", &self.inner.opts.url).field("state", &self.state()).finish()
    }
}

impl Exposed {
    /// Not dialed until [`Self::serve`]: an activation that calls out through
    /// the relay holds a clone of this before it is served.
    pub fn new(opts: DialOut) -> Self {
        Self {
            inner: Arc::new(ExposedInner {
                opts,
                live: Mutex::new(None),
                state: watch::channel(DialState::Connecting).0,
                task: Mutex::new(None),
                counters: Arc::new(Counters::default()),
                first: Mutex::new(None),
                code: Mutex::new(None),
                pending: AtomicBool::new(false),
                pending_for: Mutex::new(Duration::from_secs(600)),
            }),
        }
    }

    /// NEST-25: first contact, ssh's way. With no [`DialOut::trust`], the
    /// host's key is the one `known_hosts` pins for the URL; when none is,
    /// the host proves a key at `_info` and nothing more is sent or served
    /// until `ask` — shown that key, its fingerprint and the pairing code —
    /// says yes, which pins it there. A host presenting another key than
    /// the one pinned is refused, and `ask` is not asked. `trust` still wins
    /// (the strict mode).
    pub fn with_first_contact<F, Fut>(self, known_hosts: impl Into<PathBuf>, ask: F) -> Self
    where
        F: Fn(FirstContact) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = bool> + Send + 'static,
    {
        let ask: Ask = Arc::new(move |c| Box::pin(ask(c)));
        *self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: Some(ask) });
        self
    }

    /// NEST-25: trust what `known_hosts` pins for the URL, and refuse a host
    /// with no key there (no first contact).
    pub fn with_known_hosts(self, known_hosts: impl Into<PathBuf>) -> Self {
        *self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: None });
        self
    }

    /// NEST-25: how long an offer the host holds pending is waited for, on
    /// the same socket (the pairing code is the connection's). Default 10 min.
    pub fn with_pending_for(self, wait: Duration) -> Self {
        *self.inner.pending_for.lock().unwrap() = wait;
        self
    }

    /// NEST-25: the pairing code while the host holds this side's offer
    /// pending, waiting for its operator.
    pub fn pending(&self) -> Option<String> {
        self.inner.pending.load(Ordering::Acquire).then(|| self.code()).flatten()
    }

    /// NEST-25: the pairing code of the connection now (or the last one).
    pub fn code(&self) -> Option<String> {
        self.inner.code.lock().unwrap().clone()
    }

    /// The options it dials with.
    pub fn options(&self) -> &DialOut {
        &self.inner.opts
    }

    /// The principal this side signs in as (its key's), or why the key does
    /// not read.
    pub fn principal(&self) -> Result<String, String> {
        read_seed(&self.inner.opts.key).map(|k| principal_of(&k))
    }

    /// Where it stands now.
    pub fn state(&self) -> DialState {
        self.inner.state.borrow().clone()
    }

    /// Its state, watched.
    pub fn watch(&self) -> watch::Receiver<DialState> {
        self.inner.state.subscribe()
    }

    /// Wait until mounted (its `path` at the relay), or refused, or `timeout`.
    pub async fn mounted(&self, timeout: Duration) -> Result<String, String> {
        let mut rx = self.watch();
        let settled = tokio::time::timeout(timeout, async {
            rx.wait_for(|s| matches!(s, DialState::Mounted { .. } | DialState::Refused { .. } | DialState::Stopped)).await.map(|s| s.clone())
        })
        .await;
        match settled {
            Ok(Ok(DialState::Mounted { path, .. })) => Ok(path),
            Ok(Ok(other)) => Err(format!("{other:?}")),
            Ok(Err(_)) => Err("stopped".into()),
            Err(_) => Err(format!("not mounted in {timeout:?} ({:?})", self.state())),
        }
    }

    /// Dial, offer `activation`, serve it; dial again whenever the socket
    /// drops. Replaces a previous `serve`.
    pub fn serve<A: Activation + Clone>(&self, activation: A) {
        let weak = Arc::downgrade(&self.inner);
        let task = tokio::spawn(async move {
            let mut failures = 0usize;
            loop {
                let Some(inner) = weak.upgrade() else { return };
                inner.state.send_replace(DialState::Connecting);
                let outcome = session(&inner, activation.clone()).await;
                inner.live.lock().unwrap().take();
                let backoff = inner.opts.backoff;
                match outcome {
                    Outcome::Refused(why) => {
                        tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "the offer was refused: {why}");
                        inner.state.send_replace(DialState::Refused { why });
                        return;
                    }
                    Outcome::Dropped { why, was_mounted } => {
                        tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "{why}; dialing again");
                        inner.state.send_replace(DialState::Down { why });
                        failures = if was_mounted { 0 } else { failures + 1 };
                    }
                }
                drop(inner);
                tokio::time::sleep(backoff.delay(failures)).await;
            }
        });
        if let Some(old) = self.inner.task.lock().unwrap().replace(task.abort_handle()) {
            old.abort();
        }
    }

    /// Close the socket and stop dialing.
    pub fn stop(&self) {
        if let Some(t) = self.inner.task.lock().unwrap().take() {
            t.abort();
        }
        if let Some(live) = self.inner.live.lock().unwrap().take() {
            live.conn.shutdown.notify_one();
        }
        self.inner.state.send_replace(DialState::Stopped);
    }

    /// Call `method` (a path at the relay: `peers.bob.hello`, `peers.list`)
    /// over this side's socket, as this side's key: `{svc}.call`, decided by
    /// the relay's gate. Not connected: one `child_unavailable` item.
    pub async fn call(&self, method: &str, params: Value) -> PlexusStream {
        let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
        let live = self.inner.live.lock().unwrap().as_ref().map(|l| (Arc::clone(&l.conn), l.service.clone()));
        let Some((conn, service)) = live else {
            return one(unavailable("relay", &format!("not connected to {} ({:?})", self.inner.opts.url, self.state())));
        };
        match conn.open(&format!("{service}.call"), json!({ "method": method, "params": params }), self.inner.opts.timeout, None).await {
            Ok((sid, rx)) => Box::pin(Items { rx, sid, conn, over: false }),
            Err(item) => one(item),
        }
    }
}

/// A call's items, until its terminal one; dropped before it, unsubscribed.
struct Items {
    rx: mpsc::Receiver<PlexusStreamItem>,
    sid: SubKey,
    conn: Arc<Conn>,
    over: bool,
}

impl futures::Stream for Items {
    type Item = PlexusStreamItem;

    fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
        if self.over {
            return std::task::Poll::Ready(None);
        }
        match self.rx.poll_recv(cx) {
            std::task::Poll::Ready(Some(item)) => {
                self.over = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
                std::task::Poll::Ready(Some(item))
            }
            std::task::Poll::Ready(None) => {
                self.over = true;
                std::task::Poll::Ready(Some(unavailable("relay", "the connection closed")))
            }
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

impl Drop for Items {
    fn drop(&mut self) {
        if !self.over {
            self.conn.unsubscribe(&self.sid);
        }
    }
}

enum Outcome {
    Refused(String),
    Dropped { why: String, was_mounted: bool },
}

fn nonce() -> [u8; 32] {
    let mut n = [0u8; 32];
    n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
    n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
    n
}

/// The offer's request id: a string, so it can never be one of the client
/// `Conn`'s numbered requests (spec/14 rule 2: ids are per direction).
const OFFER_ID: &str = "offer";

/// One socket, from dial to drop.
async fn session<A: Activation + Clone>(inner: &Arc<ExposedInner>, activation: A) -> Outcome {
    let opts = &inner.opts;
    let dropped = |why: String| Outcome::Dropped { why, was_mounted: false };
    // KEEL-7: the transport decided before any socket opens or the key is
    // read — `ws://` beyond loopback only under `transport.insecure_ws`.
    if let Err(why) = check_ws_url(&opts.url, opts.insecure_ws) {
        return Outcome::Refused(format!("{INSECURE_TRANSPORT}: {why}"));
    }
    // KEEL-8: a relay is named by its key before it is dialed; the socket is
    // never a pipe, so nothing on it is believed without that key's proof.
    // NEST-25: or by the key a known-hosts file pins for it, or — first
    // contact — by the one a person says yes to below.
    let first = inner.first.lock().unwrap().clone();
    let pinned: Option<String> = match (&opts.trust, &first) {
        (Some(_), _) | (None, None) => match trusted_key(opts.trust.as_deref()) {
            Ok(k) => Some(k),
            Err(why) => return Outcome::Refused(why),
        },
        (None, Some(f)) => match f.hosts.get(&opts.url) {
            Ok(Some(k)) => Some(k),
            Ok(None) if f.ask.is_some() => None,
            Ok(None) => return Outcome::Refused(format!("no key is known for {} in {} (and no first contact is asked): a dial-out names its relay by key", opts.url, f.hosts.path().display())),
            Err(why) => return Outcome::Refused(format!("the known hosts: {why}")),
        },
    };
    if opts.url.starts_with("wss://") && !cfg!(feature = "child-wss") {
        return Outcome::Refused("a wss:// relay needs plexus-core's `child-wss` feature (TLS)".into());
    }
    let mut req = match opts.url.as_str().into_client_request() {
        Ok(r) => r,
        Err(e) => return Outcome::Refused(format!("`{}`: {e}", opts.url)),
    };
    let signer = match read_seed(&opts.key) {
        Ok(k) => k,
        Err(e) => return Outcome::Refused(e),
    };
    let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
    // A dial-out signs in to its relay (a service): the sign-in context.
    let proof = key_proof(&signer, super::ws::LOGIN_CONTEXT, opts.url.trim_end_matches('/'), &opts.agent, &nonce(), ts);
    // KEEL-19: who this dial-out proves to be — what the relay's `_info`
    // proof must be made for.
    let me = principal_of(&signer);
    match HeaderValue::from_str(&format!("Bearer {proof}")) {
        Ok(v) => req.headers_mut().insert(AUTHORIZATION, v),
        Err(e) => return Outcome::Refused(e.to_string()),
    };
    // KEEL-8: the TLS a mount's dial is made with (`tls_roots` honoured),
    // and its one timeout on the upgrade (a socket accepted and left).
    #[cfg(feature = "child-wss")]
    let connecting = {
        let tls = match opts.url.starts_with("wss://") {
            true => match super::ws::tls_config(opts.tls_roots.as_deref()) {
                Ok(c) => Some(tokio_tungstenite::Connector::Rustls(c)),
                Err(why) => return Outcome::Refused(why),
            },
            false => None,
        };
        // spec/14: a client that serves must not delay small writes (Nagle).
        tokio_tungstenite::connect_async_tls_with_config(req, None, true, tls)
    };
    #[cfg(not(feature = "child-wss"))]
    let connecting = tokio_tungstenite::connect_async_with_config(req, None, true);
    let socket = match tokio::time::timeout(opts.timeout, connecting).await {
        Err(_) => return dropped(format!("dialing {}: no answer to the upgrade in {:?}", opts.url, opts.timeout)),
        Ok(Ok((s, _))) => s,
        Ok(Err(tokio_tungstenite::tungstenite::Error::Http(resp))) => return dropped(format!("the upgrade to {} was refused: HTTP {}", opts.url, resp.status())),
        Ok(Err(e)) => return dropped(format!("dialing {}: {e}", opts.url)),
    };
    let (mut sink, mut stream) = socket.split();

    // This side's calls out: a client `Conn` on the socket's outbound queue.
    let (out, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
    let conn = Conn::new("relay", None, out.clone(), 64, Arc::clone(&inner.counters));
    // The calls in: RETURNS-47's host, on a pipe of lines this side feeds —
    // started only once the relay has proved the trusted key (KEEL-8).
    let (mut host_in, host_r) = tokio::io::duplex(1 << 16);
    let (host_w, host_out) = tokio::io::duplex(1 << 16);
    let proven = Arc::new(AtomicBool::new(false));
    let mut host: Option<tokio::task::JoinHandle<std::io::Result<()>>> = None;

    // Writer: the client's frames and the host's lines, in the order made.
    let out_host = out.clone();
    let host_lines = tokio::spawn(async move {
        let mut lines = BufReader::new(host_out).lines();
        while let Ok(Some(l)) = lines.next_line().await {
            // NEST-25: a call back is a request of this side's too: its id
            // is put in a space of its own (`h:<n>`), apart from the client's.
            if out_host.send(host_request_out(l.into_bytes())).is_err() {
                break;
            }
        }
    });
    let shutdown = Arc::clone(&conn);
    let writer = tokio::spawn(async move {
        loop {
            tokio::select! {
                first = out_rx.recv() => {
                    let Some(first) = first else { break };
                    let mut ok = sink.feed(Message::text(String::from_utf8_lossy(&first).into_owned())).await.is_ok();
                    while let (true, Ok(more)) = (ok, out_rx.try_recv()) {
                        ok = sink.feed(Message::text(String::from_utf8_lossy(&more).into_owned())).await.is_ok();
                    }
                    if !ok || sink.flush().await.is_err() {
                        break;
                    }
                }
                _ = shutdown.shutdown.notified() => {
                    let _ = sink.close().await;
                    break;
                }
            }
        }
    });

    // Reader: by the frame's shape (spec/14 rule 2) — a call into this side
    // to the host; the offer's answer to its waiter; the rest to the client.
    let (offer_tx, mut offer_rx) = mpsc::unbounded_channel::<Value>();
    let reader_conn = Arc::clone(&conn);
    let (reader_proven, refuse_out) = (Arc::clone(&proven), out.clone());
    let reader = tokio::spawn(async move {
        let why = loop {
            let text = match stream.next().await {
                Some(Ok(Message::Text(t))) => t.as_bytes().to_vec(),
                Some(Ok(Message::Binary(b))) => b.to_vec(),
                Some(Ok(Message::Close(f))) => break format!("the relay closed the socket ({})", f.map(|f| f.code.to_string()).unwrap_or_else(|| "no code".into())),
                Some(Ok(_)) => continue,
                Some(Err(e)) => break format!("the socket: {e}"),
                None => break "the relay closed the socket".to_string(),
            };
            let shape: Value = match serde_json::from_slice(&text) {
                Ok(v) => v,
                Err(_) => continue,
            };
            let (method, id) = (shape.get("method"), shape.get("id"));
            let method_is = |m: &str| method.and_then(Value::as_str) == Some(m);
            // NEST-25: the host's answers and items of this side's calls back.
            let to_host = (method_is(HOST_CALL) && id.is_none()) || (method.is_none() && id.and_then(Value::as_str).is_some_and(|i| i.starts_with("h:")));
            if to_host {
                if !reader_proven.load(Ordering::Acquire) {
                    continue;
                }
                let mut line = host_answer_in(shape);
                line.push(b'\n');
                if host_in.write_all(&line).await.is_err() {
                    break "the host stopped".to_string();
                }
            } else if method_is(super::dial_in::OFFER_PENDING) && id.is_none() {
                let _ = offer_tx.send(shape);
            } else if method.is_some() && id.is_some() {
                // KEEL-8: a call before the relay proved its key is answered
                // refused, never served.
                if !reader_proven.load(Ordering::Acquire) {
                    let refusal = json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "the relay has not proved its key", "data": { "error_kind": "forbidden" } } });
                    let _ = refuse_out.send(serde_json::to_vec(&refusal).unwrap_or_default());
                    continue;
                }
                let mut line = text;
                line.push(b'\n');
                if host_in.write_all(&line).await.is_err() {
                    break "the host stopped".to_string();
                }
            } else if method.is_none() && id.and_then(Value::as_str) == Some(OFFER_ID) {
                let _ = offer_tx.send(shape);
            } else {
                reader_conn.on_message(&text).await;
            }
        };
        reader_conn.on_gone(&why);
        reader_conn.shutdown.notify_one();
        why
    });

    let ended = |host: Option<tokio::task::JoinHandle<std::io::Result<()>>>, why: String, was_mounted: bool| {
        if let Some(h) = host {
            h.abort();
        }
        host_lines.abort();
        writer.abort();
        Outcome::Dropped { why, was_mounted }
    };

    // The relay's namespace and its key, proved: its `_info` over a nonce
    // (DYNAUTH-5's proof, the one a mount asks of its child).
    let asked = crate::plexus::peer_token::random_nonce();
    // NEST-25: a nonce of this side's for the pairing code, committed to
    // now and revealed in the offer, after the host's is known.
    let node_nonce = crate::plexus::peer_token::random_nonce();
    let info = async {
        let (_, mut rx) = conn.open("_info", json!({ "nonce": asked, "commit": commitment(&node_nonce) }), opts.timeout, None).await.map_err(|e| format!("{e:?}"))?;
        while let Some(item) = rx.recv().await {
            if let PlexusStreamItem::Data { content, .. } = item {
                let content = content.into_value();
                if let Some(b) = content.get("backend").and_then(Value::as_str) {
                    let field = |k: &str| content.get(k).and_then(Value::as_str).map(str::to_string);
                    return Ok((b.to_string(), field("key"), field("proof"), field("host_nonce")));
                }
            }
        }
        Err::<_, String>("its `_info` names no backend".into())
    };
    let (service, key, key_proof, host_nonce) = match tokio::time::timeout(opts.timeout, info).await {
        Ok(Ok(s)) => s,
        Ok(Err(why)) => {
            reader.abort();
            return ended(host, format!("asking the relay's `_info`: {why}"), false);
        }
        Err(_) => {
            reader.abort();
            return ended(host, format!("the relay did not answer `_info` in {:?}", opts.timeout), false);
        }
    };
    // NEST-25: a key pinned in the known hosts that the host no longer
    // presents is refused loudly, and nobody is asked.
    let from_file = opts.trust.is_none() && pinned.is_some();
    if let (true, Some(p), Some(k)) = (from_file, &pinned, &key) {
        if p != k {
            reader.abort();
            ended(host, String::new(), false);
            let file = first.as_ref().map(|f| f.hosts.path().display().to_string()).unwrap_or_default();
            let why = format!("host_key_changed: {} presents the key {k} ({}), not the one pinned in {file} ({p}): refused — someone may be in the middle; remove that line by hand only if the host's key really changed", opts.url, key_fingerprint(k).unwrap_or_default());
            tracing::error!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
            return Outcome::Refused(why);
        }
    }
    // First contact: the key it proves is checked as a pinned one would be.
    let trusted = match pinned.clone().or_else(|| key.clone()) {
        Some(t) => t,
        None => {
            reader.abort();
            ended(host, String::new(), false);
            return Outcome::Refused(format!("the relay at {} proved no key at `_info`: nothing to trust", opts.url));
        }
    };
    if let Err(why) = relay_proved(&trusted, &service, &asked, &me, key.as_deref(), key_proof.as_deref()) {
        reader.abort();
        ended(host, String::new(), false);
        tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
        return Outcome::Refused(why);
    }
    let code = host_nonce.as_deref().map(|h| pairing_code(&trusted, &me, &node_nonce, h));
    *inner.code.lock().unwrap() = code.clone();
    // Review M2: this side committed to a nonce; at first contact a host
    // that answers no nonce of its own gives no pairing code — refused, never
    // asked about with a fingerprint alone (a relay stripping it would
    // otherwise pass unseen). A host already trusted or pinned may be older.
    if pinned.is_none() && code.is_none() {
        reader.abort();
        ended(host, String::new(), false);
        let why = format!("no_pairing_code: {} answered `_info` with no `host_nonce`, so first contact has no pairing code to compare: refused (a host trusted by `--trust`, or pinned already, is reached without one)", opts.url);
        tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
        return Outcome::Refused(why);
    }
    if pinned.is_none() {
        // Nothing sent, nothing served, until a person says yes.
        let f = first.as_ref().expect("first contact is asked only with a known-hosts file");
        let shown = FirstContact { url: opts.url.clone(), key: trusted.clone(), fingerprint: key_fingerprint(&trusted).unwrap_or_default(), code: code.clone() };
        let yes = match &f.ask {
            Some(ask) => ask(shown).await,
            None => false,
        };
        if !yes {
            reader.abort();
            ended(host, String::new(), false);
            return Outcome::Refused(format!("first contact refused: the key {trusted} of {} was not accepted", opts.url));
        }
        if let Err(why) = f.hosts.add(&opts.url, &trusted) {
            reader.abort();
            ended(host, String::new(), false);
            return Outcome::Refused(format!("first contact: the known hosts: {why}"));
        }
        tracing::warn!(target: "plexus::audit", url = %opts.url, key = %trusted, "first contact: the host's key pinned in the known hosts");
    }
    let _ = conn.ns.set(service.clone());
    let _ = conn.peer_key.set(trusted.clone());
    // NEST-25: served with this side's key, so a call back under a token
    // the relay minted for it carries this key's proof of possession.
    let own = crate::plexus::peer_token::PeerKey::from_seed(signer.to_bytes());
    let serving = super::host::ServeChild { peer: ChildPeer::connection(trusted.clone(), [trusted.clone()]), key: Some(own), tokens: None };
    host = Some(tokio::spawn(super::host::serve(activation.clone(), host_r, host_w, serving)));
    proven.store(true, Ordering::Release);

    // The offer (spec/14), answered once the relay has mounted this side.
    let ns = activation.namespace().to_string();
    let schema_hash = activation.plugin_schema().hash;
    let mut params = json!({ "namespace": ns, "activations": [ns], "schema_hash": schema_hash, "schema": null });
    if let Some(m) = &opts.mount {
        params["mount"] = json!(m);
    }
    // NEST-25: the nonce committed to, revealed; and this side's key over
    // both nonces — its key, proven on this connection.
    if let Some(h) = &host_nonce {
        let mount = opts.mount.clone().unwrap_or_else(|| ns.clone());
        let input = super::dial_in::possession_input(&trusted, &me, &node_nonce, h, &service, &mount);
        params["pairing_nonce"] = json!(node_nonce);
        params["possession"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, signer.sign(input.as_bytes()).to_bytes()));
    }
    drop(signer);
    let _ = out.send(serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": OFFER_ID, "method": format!("{service}.offer"), "params": params })).unwrap_or_default());
    let mut wait = opts.timeout * 2;
    let answer = loop {
        match tokio::time::timeout(wait, offer_rx.recv()).await {
            Ok(Some(a)) if a.get("method").is_some() => {
                // Held pending: the same socket, the same code, until its operator says.
                inner.pending.store(true, Ordering::Release);
                tracing::warn!(target: "plexus::dial", url = %opts.url, code = ?code, "the host holds the offer pending its operator");
                wait = *inner.pending_for.lock().unwrap();
            }
            Ok(Some(a)) => break a,
            Ok(None) => {
                inner.pending.store(false, Ordering::Release);
                let why = reader.await.unwrap_or_else(|_| "the socket".into());
                return ended(host, format!("before the offer was answered: {why}"), false);
            }
            Err(_) => {
                inner.pending.store(false, Ordering::Release);
                reader.abort();
                return ended(host, format!("the offer was not answered in {wait:?}"), false);
            }
        }
    };
    inner.pending.store(false, Ordering::Release);
    if let Some(e) = answer.get("error") {
        reader.abort();
        ended(host, String::new(), false);
        let kind = e.pointer("/data/error_kind").and_then(Value::as_str).unwrap_or("refused");
        let message = e.get("message").and_then(Value::as_str).unwrap_or("");
        return Outcome::Refused(format!("{kind}: {message}"));
    }
    let result = answer.get("result").cloned().unwrap_or(Value::Null);
    let mount = result.get("mount").and_then(Value::as_str).unwrap_or(&ns).to_string();
    let path = result.get("path").and_then(Value::as_str).unwrap_or(&mount).to_string();
    let relay = result.pointer("/service/principal").and_then(Value::as_str).unwrap_or("").to_string();
    // KEEL-8: the relay acts as the key it proved, or not at all — another
    // principal named here is refused, as a remount proving another key is.
    if relay != trusted {
        reader.abort();
        ended(host, String::new(), false);
        let why = format!("the relay proved {trusted} but names {} as the service acting: refused, as another key is", if relay.is_empty() { "no principal" } else { &relay });
        tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
        return Outcome::Refused(why);
    }
    *inner.live.lock().unwrap() = Some(Live { conn: Arc::clone(&conn), service: service.clone() });
    let insecure = is_insecure_ws(&opts.url);
    if insecure {
        tracing::warn!(target: "plexus::dial", url = %opts.url, "insecure: dialed out over plain ws:// beyond loopback (transport.insecure_ws); the key proof and every hop cross in clear");
    }
    tracing::info!(target: "plexus::dial", url = %opts.url, %path, %relay, insecure, "mounted at the relay");
    inner.state.send_replace(DialState::Mounted { mount, path, service, relay, insecure });

    let why = reader.await.unwrap_or_else(|_| "the socket".into());
    ended(host, why, true)
}

/// NEST-25: a request line of this side's host (a call back) as it goes on
/// the socket: its numbered id put in the `h:<n>` space.
fn host_request_out(line: Vec<u8>) -> Vec<u8> {
    let Ok(mut v) = serde_json::from_slice::<Value>(&line) else { return line };
    let is_host = v.get("method").and_then(Value::as_str).is_some_and(|m| m == HOST_CALL || m == HOST_CALL_UNSUB);
    match (is_host, v.get("id").and_then(Value::as_u64)) {
        (true, Some(n)) => {
            v["id"] = json!(format!("h:{n}"));
            serde_json::to_vec(&v).unwrap_or(line)
        }
        _ => line,
    }
}

/// NEST-25: an answer to a call back as this side's host reads it (`h:<n>`
/// back to `n`); an item as it came.
fn host_answer_in(mut v: Value) -> Vec<u8> {
    if let Some(n) = v.get("id").and_then(Value::as_str).and_then(|i| i.strip_prefix("h:")).and_then(|n| n.parse::<u64>().ok()) {
        v["id"] = json!(n);
    }
    serde_json::to_vec(&v).unwrap_or_default()
}

/// KEEL-8: the relay's key a dial-out trusts — `key:<64 hex>` — or why the
/// dial-out may not dial.
fn trusted_key(trust: Option<&str>) -> Result<String, String> {
    let Some(t) = trust else {
        return Err("no trusted key: a dial-out names its relay by key (`DialOut::trust`, `key:<64 hex>`), which the relay proves at each connect; without one nothing it sends could be believed".into());
    };
    match crate::plexus::peer_token::key_of(t) {
        Some(_) => Ok(t.to_string()),
        None => Err(format!("the trusted relay `{t}` is not a key (`key:<64 hex>`): a relay is named by the key it proves")),
    }
}

/// KEEL-8: whether the relay's `_info` proved `trusted` over `nonce` —
/// KEEL-19: made for `me`, the key this dial-out proved to it.
fn relay_proved(trusted: &str, backend: &str, nonce: &str, me: &str, key: Option<&str>, proof: Option<&str>) -> Result<(), String> {
    let Some(key) = key else {
        return Err(format!("the relay proved no key at `_info` (trusted: {trusted})"));
    };
    if key != trusted {
        return Err(format!("the relay proved another key ({key}) than the one trusted ({trusted})"));
    }
    crate::plexus::peer_token::check_key_proof_for(key, proof.unwrap_or_default(), nonce, backend, me)
        .map(|_| ())
        .map_err(|e| format!("the relay's `_info` names the key {key} without proving it: {e}"))
}

/// The principal a key file's proof proves (`key:<64 hex>`), or why the key
/// does not read — a service naming itself, as a relay does in its hops.
pub fn key_principal(path: &std::path::Path) -> Result<String, String> {
    read_seed(path).map(|k| principal_of(&k))
}