Skip to main content

qualia_cli/
mesh.rs

1//! `qualia-cli mesh-probe` — a two-machine SocialWebNet reachability probe.
2//!
3//! Cross-host counterpart to the in-process loopback tests: userspace WireGuard over
4//! real UDP. This is the labelled **internet transition** path, not Native Independent
5//! Ethernet. Barriers, NAT class, and the grok-bot listen job are in
6//! `docs/manuals/standards/qualia-decentralized-network-fabric/qdnf-imp/internet-two-host.md`.
7//!
8//! ## Zero key-copying: keys derive from a shared passphrase + role
9//!
10//! ```text
11//!   secret(role) = SHA-256("qualia-mesh-probe:v1:" || role || ":" || passphrase)
12//! ```
13//!
14//! Listen is role `a`; connect is role `b`.
15//!
16//! ## Internet procedure (one side must be a reachable UDP listener)
17//!
18//! Listener (public IP or port-forward — typically grok-bot / desktop / VPS):
19//! ```text
20//!   qualia-cli mesh-probe observe --port 51820
21//!   qualia-cli mesh-probe listen --pass PHRASE --port 51820 --seconds 300
22//! ```
23//! Connector (Cursor cloud agent on address-dependent SNAT — connect-only):
24//! ```text
25//!   qualia-cli mesh-probe connect --pass PHRASE --peer LISTENER_IP:51820 --qdnf
26//! ```
27//!
28//! STUN-learned addresses from an address-dependent NAT must not be given to the peer
29//! as a listen locator. Cursor cloud `ports` forwards TCP to the operator desktop; it
30//! is not a public WireGuard UDP endpoint.
31
32use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
33use std::time::{Duration, Instant};
34
35use clap::Subcommand;
36use sha2::{Digest, Sha256};
37
38use qualia_core_db::net::qdnf::frame::{encode_frame, FrameHeader, MAGIC};
39use qualia_core_db::net::qdnf::registries::{FrameType, NextProtocol};
40use qualia_core_db::p2p::mesh_datagram::{self, ports};
41use qualia_core_db::p2p::stun_observe::{observe_mapping, recommend_role, MappingClass, ProbeRole};
42use qualia_core_db::p2p::wireguard_runtime::{TunnelEvent, WgTunnel};
43use qualia_core_db::p2p::wireguard_userspace::WgKeypair;
44
45const STUN_A: (&str, u16) = ("stun.l.google.com", 3478);
46const STUN_B: (&str, u16) = ("stun.cloudflare.com", 3478);
47
48#[derive(Subcommand, Debug)]
49pub enum MeshAction {
50    /// Print a fresh random WireGuard keypair (secret + public), for explicit-key setups.
51    Keygen,
52    /// Classify NAT mapping with two STUN servers on one UDP socket. Does not handshake.
53    Observe {
54        /// UDP port to bind (0 = OS-chosen).
55        #[arg(long, default_value_t = 51820)]
56        port: u16,
57    },
58    /// Listen for a probe connection (role A). Prints decrypted inner packets until Ctrl-C.
59    Listen {
60        /// Shared passphrase both sides agree on (derives both keypairs).
61        #[arg(long)]
62        pass: String,
63        /// UDP port to bind (default 51820, WireGuard's conventional port).
64        #[arg(long, default_value_t = 51820)]
65        port: u16,
66        /// Seconds to run before exiting (0 = run until Ctrl-C).
67        #[arg(long, default_value_t = 0)]
68        seconds: u64,
69    },
70    /// Connect to a listening probe (role B), complete the handshake, and send a message.
71    Connect {
72        /// Shared passphrase both sides agree on (must match the listener's).
73        #[arg(long)]
74        pass: String,
75        /// The listener's address, `host:port` (e.g. `203.0.113.5:51820`).
76        #[arg(long)]
77        peer: String,
78        /// Message to send once the tunnel is up (chat port; ignored when `--qdnf`).
79        #[arg(long, default_value = "hello from the SocialWebNet probe")]
80        message: String,
81        /// How many times to send the message (1s apart).
82        #[arg(long, default_value_t = 1)]
83        count: u32,
84        /// Seconds to wait for the handshake before giving up.
85        #[arg(long, default_value_t = 15)]
86        timeout: u64,
87        /// Send a QDNF QFrame on overlay port 6423 instead of a chat datagram.
88        #[arg(long, default_value_t = false)]
89        qdnf: bool,
90    },
91}
92
93/// Derive a deterministic 32-byte WireGuard secret from `(role, passphrase)`.
94fn derive_secret(role: &str, pass: &str) -> [u8; 32] {
95    let mut hasher = Sha256::new();
96    hasher.update(b"qualia-mesh-probe:v1:");
97    hasher.update(role.as_bytes());
98    hasher.update(b":");
99    hasher.update(pass.as_bytes());
100    let digest = hasher.finalize();
101    let mut out = [0u8; 32];
102    out.copy_from_slice(&digest);
103    out
104}
105
106/// Runs the command.
107pub fn run(action: &MeshAction) -> Result<(), Box<dyn std::error::Error>> {
108    match action {
109        MeshAction::Keygen => {
110            let kp = qualia_core_db::p2p::wireguard_userspace::generate_keypair();
111            println!("WireGuard keypair (random):");
112            println!("  secret : {}", hex_lower(&kp.private_bytes()));
113            println!("  public : {}", kp.public_hex());
114            Ok(())
115        }
116        MeshAction::Observe { port } => run_observe(*port),
117        MeshAction::Listen {
118            pass,
119            port,
120            seconds,
121        } => run_listen(pass, *port, *seconds),
122        MeshAction::Connect {
123            pass,
124            peer,
125            message,
126            count,
127            timeout,
128            qdnf,
129        } => run_connect(pass, peer, message, *count, *timeout, *qdnf),
130    }
131}
132
133fn hex_lower(bytes: &[u8]) -> String {
134    let mut s = String::with_capacity(bytes.len() * 2);
135    for b in bytes {
136        s.push_str(&format!("{b:02x}"));
137    }
138    s
139}
140
141fn run_listen(pass: &str, port: u16, seconds: u64) -> Result<(), Box<dyn std::error::Error>> {
142    // Role A: my key = derive("a"); peer (the connector) = derive("b").
143    let my_keys = WgKeypair::from_secret_bytes(derive_secret("a", pass));
144    let peer_keys = WgKeypair::from_secret_bytes(derive_secret("b", pass));
145
146    let bind: SocketAddr = format!("0.0.0.0:{port}").parse()?;
147    let mut tunnel = WgTunnel::bind(&my_keys, peer_keys.public_bytes().into(), bind, 1)?;
148    tunnel.set_read_timeout(Some(Duration::from_millis(500)))?;
149
150    println!("SocialWebNet probe — LISTEN (role A)");
151    println!("  my WG public : {}", my_keys.public_hex());
152    println!("  bound        : {}", tunnel.local_addr()?);
153    println!("  expecting peer WG public : {}", peer_keys.public_hex());
154    print_stun_on_socket(tunnel.udp_socket());
155    tunnel.set_read_timeout(Some(Duration::from_millis(500)))?;
156    if seconds == 0 {
157        println!("  waiting for a connection… (Ctrl-C to stop)");
158    } else {
159        println!("  waiting up to {seconds}s for a connection…");
160    }
161
162    let deadline = if seconds == 0 {
163        None
164    } else {
165        Some(Instant::now() + Duration::from_secs(seconds))
166    };
167    let mut announced_session = false;
168
169    loop {
170        if let Some(d) = deadline {
171            if Instant::now() >= d {
172                println!("  (timeout reached; exiting)");
173                return Ok(());
174            }
175        }
176        match tunnel.pump()? {
177            TunnelEvent::InnerPacket(inner) => match mesh_datagram::decode_datagram(&inner) {
178                Some(d) if d.dst_port == ports::QDNF => {
179                    let magic_ok = d.payload.starts_with(&MAGIC);
180                    println!(
181                        "  ← QDNF overlay {} bytes magic_ok={magic_ok}",
182                        d.payload.len()
183                    );
184                }
185                Some(d) => println!(
186                    "  ← received {} bytes on port {}: \"{}\"",
187                    d.payload.len(),
188                    d.dst_port,
189                    String::from_utf8_lossy(&d.payload)
190                ),
191                None => println!(
192                    "  ← received a {}-byte inner packet (not a UDP datagram)",
193                    inner.len()
194                ),
195            },
196            TunnelEvent::Progressed => {
197                if !announced_session && tunnel.has_session() {
198                    announced_session = true;
199                    println!(
200                        "  ✓ handshake complete with {:?} — tunnel is up",
201                        tunnel
202                            .peer_endpoint()
203                            .map(|e| e.to_string())
204                            .unwrap_or_default()
205                    );
206                }
207            }
208            TunnelEvent::Idle => {
209                // Periodically drive timers (keepalives/rekey) while idle.
210                let _ = tunnel.tick();
211            }
212        }
213    }
214}
215
216fn run_connect(
217    pass: &str,
218    peer: &str,
219    message: &str,
220    count: u32,
221    timeout: u64,
222    qdnf: bool,
223) -> Result<(), Box<dyn std::error::Error>> {
224    // Role B: my key = derive("b"); peer (the listener) = derive("a").
225    let my_keys = WgKeypair::from_secret_bytes(derive_secret("b", pass));
226    let peer_keys = WgKeypair::from_secret_bytes(derive_secret("a", pass));
227
228    let endpoint = peer
229        .to_socket_addrs()?
230        .next()
231        .ok_or_else(|| format!("could not resolve peer address '{peer}'"))?;
232
233    let bind: SocketAddr = "0.0.0.0:0".parse()?;
234    let mut tunnel = WgTunnel::bind(&my_keys, peer_keys.public_bytes().into(), bind, 2)?;
235    tunnel.set_read_timeout(Some(Duration::from_millis(500)))?;
236    tunnel.set_peer_endpoint(endpoint);
237
238    println!("SocialWebNet probe — CONNECT (role B)");
239    println!("  my WG public : {}", my_keys.public_hex());
240    println!(
241        "  peer         : {endpoint} (WG public {})",
242        peer_keys.public_hex()
243    );
244    println!("  initiating handshake…");
245    tunnel.initiate_handshake()?;
246
247    // Drive the handshake to completion. `pump` processes the peer's response; `tick` drives
248    // WireGuard's timers so a *lost* initiation is retransmitted (e.g. the listener wasn't ready
249    // when our first init went out) — without it a single dropped init would hang until timeout.
250    let deadline = Instant::now() + Duration::from_secs(timeout);
251    while !tunnel.has_session() {
252        if Instant::now() >= deadline {
253            return Err(format!(
254                "handshake did not complete within {timeout}s — check the peer address, that the \
255                 listener is running with the same --pass, and that UDP is reachable (NAT/firewall)"
256            )
257            .into());
258        }
259        let _ = tunnel.pump()?;
260        let _ = tunnel.tick()?;
261    }
262    println!("  ✓ handshake complete — tunnel is up");
263
264    // Send the message `count` times. `send_packet` returns whether ciphertext actually went on the
265    // wire (vs. being held pending a (re)handshake), so report honestly rather than assuming.
266    for i in 1..=count {
267        let packet = if qdnf {
268            let header = FrameHeader::new(FrameType::DiscoveryBeacon, NextProtocol::QLink);
269            let mut wire = [0u8; 128];
270            let n = encode_frame(&header, &[], &mut wire)?;
271            mesh_datagram::encode_datagram(ports::QDNF, ports::QDNF, &wire[..n])
272        } else {
273            mesh_datagram::encode_datagram(ports::CHAT, ports::CHAT, message.as_bytes())
274        };
275        let transmitted = tunnel.send_packet(&packet)?;
276        if transmitted {
277            if qdnf {
278                println!(
279                    "  → sent [{i}/{count}] QDNF DiscoveryBeacon on overlay {}",
280                    ports::QDNF
281                );
282            } else {
283                println!("  → sent [{i}/{count}]: \"{message}\"");
284            }
285        } else {
286            println!("  → queued [{i}/{count}] (awaiting session)");
287        }
288        // Pump briefly so any keepalive/response is processed before the next send.
289        let until = Instant::now() + Duration::from_millis(900);
290        while Instant::now() < until {
291            let _ = tunnel.pump()?;
292        }
293    }
294    println!("  done. Delivery is best-effort UDP; the listener prints each datagram it decrypts.");
295    Ok(())
296}
297
298fn resolve_ipv4(host: &str, port: u16) -> Result<SocketAddr, Box<dyn std::error::Error>> {
299    let addr = (host, port)
300        .to_socket_addrs()?
301        .find(|a| a.is_ipv4())
302        .ok_or_else(|| format!("no IPv4 for {host}:{port}"))?;
303    Ok(addr)
304}
305
306fn print_report(report: &qualia_core_db::p2p::stun_observe::ObserveReport) {
307    let role = recommend_role(report.class);
308    println!("SOCIALWEBNET-INTERNET-OFFER v1");
309    println!("  local_bind     : {}", report.local);
310    println!("  srflx_stun_a   : {}", report.sample_a);
311    println!("  srflx_stun_b   : {}", report.sample_b);
312    println!(
313        "  mapping        : {}",
314        match report.class {
315            MappingClass::EndpointIndependent => "endpoint-independent",
316            MappingClass::AddressDependent => "address-dependent",
317        }
318    );
319    println!(
320        "  role           : {}",
321        match role {
322            ProbeRole::ConnectOnly => "connect-only (do not publish STUN as a listen locator)",
323        }
324    );
325    println!(
326        "  listener_viable: not proven — only claim listen if you have a public IP or UDP port-forward"
327    );
328    println!(
329        "  handshake      : internet_two_host_handshake_executed=false until a remote peer answers"
330    );
331}
332
333fn print_stun_on_socket(sock: &UdpSocket) {
334    match (
335        resolve_ipv4(STUN_A.0, STUN_A.1),
336        resolve_ipv4(STUN_B.0, STUN_B.1),
337    ) {
338        (Ok(a), Ok(b)) => match observe_mapping(sock, a, b, Duration::from_secs(3)) {
339            Ok(report) => print_report(&report),
340            Err(e) => println!("  stun observe failed: {e}"),
341        },
342        (a, b) => println!("  stun resolve failed: {a:?} {b:?}"),
343    }
344}
345
346fn run_observe(port: u16) -> Result<(), Box<dyn std::error::Error>> {
347    let bind = SocketAddr::from(([0, 0, 0, 0], port));
348    let sock = UdpSocket::bind(bind)?;
349    println!("SocialWebNet probe — OBSERVE");
350    println!("  bound : {}", sock.local_addr()?);
351    print_stun_on_socket(&sock);
352    Ok(())
353}