From e6f0e58ed32b10d02dcfe99eeff9c16b49c52b03 Mon Sep 17 00:00:00 2001 From: ariskadatabisnis Date: Mon, 6 Jul 2026 15:11:44 +0700 Subject: [PATCH] secure chat addon and stun --- scripts/install-secure-chat-deps.sh | 28 ++++- scripts/send-secure-chat-test.sh | 168 +++++++++++++++++++++++++--- src/secure_chat/mod.rs | 48 ++++++-- src/secure_chat/relay.rs | 99 ++++++++++++++++ src/secure_chat/state.rs | 3 + src/serviceclient.rs | 4 + 6 files changed, 320 insertions(+), 30 deletions(-) create mode 100644 src/secure_chat/relay.rs diff --git a/scripts/install-secure-chat-deps.sh b/scripts/install-secure-chat-deps.sh index a9ef51c..0744aa6 100755 --- a/scripts/install-secure-chat-deps.sh +++ b/scripts/install-secure-chat-deps.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Install BackOne + WebHub builds required for Secure Chat send/receive. +# Install patched backone + webhub and verify secure-chat prerequisites. # Run: sudo ./scripts/install-secure-chat-deps.sh set -euo pipefail @@ -29,6 +29,19 @@ sleep 2 TOKEN="$(cat /var/lib/backone/authtoken.secret)" PORT="$(cat /var/lib/backone/backone.port 2>/dev/null || echo 9993)" +echo "" +echo "Verifying installed binaries match git build..." +if cmp -s "${BACKONE_REPO}/backone" /usr/sbin/backone; then + echo " backone: OK" +else + echo " backone: MISMATCH" >&2 +fi +if cmp -s "${BACKONE_REPO}/addons/webhub/backone-webhub" /usr/lib/backone/addons/webhub/backone-webhub; then + echo " webhub: OK" +else + echo " webhub: MISMATCH" >&2 +fi + echo "" echo "Verifying comms API..." for path in "/app/api/webrtc-config" "/controller/comms/ping?host=127.0.0.1"; do @@ -36,6 +49,17 @@ for path in "/app/api/webrtc-config" "/controller/comms/ping?host=127.0.0.1"; do echo " ${path} -> HTTP ${code}" done +echo "" +echo "Verifying relay accepts private-IP POST without auth..." +code="$(curl -s -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \ + -d '{"networkId":"0000000000000000","senderId":"0000000000","senderName":"t","targetId":"0000000000","body":"t","at":1}' \ + "http://127.0.0.1:${PORT}/controller/comms/chat/relay")" +echo " POST /controller/comms/chat/relay (no auth) -> HTTP ${code}" +if [[ "$code" != "200" ]]; then + echo " WARN: relay no-auth check failed — cross-peer delivery may not work" >&2 +fi + systemctl --no-pager status backone backone-webhub | sed -n '1,12p' echo "" -echo "Done. Restart BackOneUI and open Secure Chat from the tray menu." +echo "Done. Run the SAME script on every peer machine (e.g. c52b90363c)." +echo "Then restart BackOneUI and open Secure Chat on the recipient." diff --git a/scripts/send-secure-chat-test.sh b/scripts/send-secure-chat-test.sh index 3d2aa86..52d1012 100755 --- a/scripts/send-secure-chat-test.sh +++ b/scripts/send-secure-chat-test.sh @@ -19,7 +19,6 @@ MY_ID="$( | jq -r '.address' | tr '[:upper:]' '[:lower:]' )" -# /app/api/webrtc-config is 404 without app-shell; jq // 9994 does not help on empty body. HUB_PORT="$( curl -sf -H "X-ZT1-Auth: $TOKEN" "http://127.0.0.1:${PORT}/app/api/webrtc-config" 2>/dev/null \ | jq -r '.webhubPort // empty' 2>/dev/null || true @@ -28,7 +27,7 @@ if [[ -z "$HUB_PORT" ]]; then if ss -tln 2>/dev/null | grep -q '127.0.0.1:9994'; then HUB_PORT=9994 else - echo "Could not detect webhub port (default 9994 not listening). Is backone-webhub running?" >&2 + echo "Could not detect webhub port. Is backone-webhub running?" >&2 exit 1 fi fi @@ -42,10 +41,6 @@ echo "Network: $NETWORK_ID" echo "Target: $TARGET_ID" echo "Message: $MSG" -if ! systemctl is-active --quiet backone-webhub 2>/dev/null; then - echo "WARN: backone-webhub service does not appear active" >&2 -fi - PEER_OK="$( curl -sf -H "X-ZT1-Auth: $TOKEN" "http://127.0.0.1:${PORT}/peer" \ | jq -r --arg t "$TARGET_ID" '.[] | select(.address | ascii_downcase == $t) | .address' \ @@ -54,15 +49,42 @@ PEER_OK="$( if [[ -n "$PEER_OK" ]]; then echo "Peer VL1: online ($PEER_OK)" else - echo "Peer VL1: not found in /peer (may still deliver if recipient has webhub open)" + echo "Peer VL1: not in /peer list" fi -export TOKEN MY_ID NETWORK_ID TARGET_ID MSG HUB_PORT -python3 <<'PY' +if ! cmp -s /usr/sbin/backone "${BACKONE_REPO:-$HOME/git/BackOne}/backone" 2>/dev/null; then + echo "" + echo "WARN: system backone is not the patched build — run:" >&2 + echo " sudo ./scripts/install-secure-chat-deps.sh" >&2 +fi +if ! cmp -s /usr/lib/backone/addons/webhub/backone-webhub \ + "${BACKONE_REPO:-$HOME/git/BackOne}/addons/webhub/backone-webhub" 2>/dev/null; then + echo "WARN: system webhub is outdated — run install script above" >&2 +fi + +export TOKEN MY_ID NETWORK_ID TARGET_ID MSG HUB_PORT PORT BACKONE_REPO="${BACKONE_REPO:-$HOME/git/BackOne}" + +# Prefer system python3 — project venv often lacks python3-websockets. +PYTHON="" +for candidate in /usr/bin/python3 python3; do + if [[ -x "$candidate" ]] && "$candidate" -c "import websockets" 2>/dev/null; then + PYTHON="$candidate" + break + fi +done +if [[ -z "$PYTHON" ]]; then + echo "python3-websockets is required. Install with:" >&2 + echo " sudo apt install python3-websockets" >&2 + echo " # or: pip install websockets (outside the BackOneUI venv)" >&2 + exit 1 +fi + +"$PYTHON" <<'PY' import asyncio import json import os import urllib.parse +import urllib.request import websockets @@ -72,10 +94,106 @@ network_id = os.environ["NETWORK_ID"] target_id = os.environ["TARGET_ID"] msg = os.environ["MSG"] hub_port = os.environ["HUB_PORT"] +port = os.environ["PORT"] -url = f"ws://127.0.0.1:{hub_port}/?auth={urllib.parse.quote(token, safe='')}" -async def main() -> None: +def peer_path_hosts(): + req = urllib.request.Request( + f"http://127.0.0.1:{port}/peer", + headers={"X-ZT1-Auth": token}, + ) + with urllib.request.urlopen(req, timeout=3) as resp: + peers = json.loads(resp.read().decode("utf-8")) + hosts = [] + seen = set() + for peer in peers: + if (peer.get("address") or "").lower() != target_id: + continue + for path in peer.get("paths") or []: + addr = path.get("address") or "" + host = addr.split("/", 1)[0].strip() + if host and host not in seen: + seen.add(host) + hosts.append(host) + break + return hosts + + +def overlay_neigh_hosts(): + """Overlay IPs on the joined network interface (fallback when members API is 404).""" + import subprocess + + req = urllib.request.Request( + f"http://127.0.0.1:{port}/network", + headers={"X-ZT1-Auth": token}, + ) + with urllib.request.urlopen(req, timeout=3) as resp: + networks = json.loads(resp.read().decode("utf-8")) + dev = None + for net in networks: + if (net.get("id") or "").lower() == network_id: + dev = net.get("portDeviceName") + break + if not dev: + return [] + try: + out = subprocess.check_output( + ["ip", "neigh", "show", "dev", dev], + text=True, + timeout=3, + ) + except (subprocess.SubprocessError, FileNotFoundError): + return [] + hosts = [] + for line in out.splitlines(): + parts = line.split() + if not parts: + continue + ip = parts[0] + if ip.startswith("192.168.") or ip.startswith("10."): + hosts.append(ip) + return hosts + + +def relay_hosts(): + seen = set() + out = [] + for host in peer_path_hosts() + overlay_neigh_hosts(): + if host and host not in seen: + seen.add(host) + out.append(host) + return out + + +def try_relay(host, use_auth): + payload = { + "networkId": network_id, + "senderId": my_id, + "senderName": my_id, + "targetId": target_id, + "body": msg, + "at": int(__import__("time").time() * 1000), + } + headers = {"Content-Type": "application/json"} + if use_auth: + headers["X-ZT1-Auth"] = token + req = urllib.request.Request( + f"http://{host}:{port}/controller/comms/chat/relay", + data=json.dumps(payload).encode("utf-8"), + headers=headers, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=4) as resp: + body = json.loads(resp.read().decode("utf-8")) + return resp.status, body + except Exception as exc: + return None, str(exc) + + +async def webhub_send(): + url = f"ws://127.0.0.1:{hub_port}/?auth={urllib.parse.quote(token, safe='')}" + delivered = False async with websockets.connect(url) as ws: await ws.send(json.dumps({"type": "auth", "token": token})) await ws.send(json.dumps({ @@ -87,22 +205,36 @@ async def main() -> None: "type": "chat_message", "networkId": network_id, "targetId": target_id, - "senderName": f"test-{my_id[:6]}", + "senderName": my_id, "body": msg, })) - for _ in range(5): + for _ in range(6): try: reply = await asyncio.wait_for(ws.recv(), timeout=2.0) print("recv:", reply) data = json.loads(reply) if data.get("type") == "chat_delivery": - if data.get("delivered"): - print("DELIVERED") - else: - print("NOT DELIVERED — open Secure Chat on recipient, or run install-secure-chat-deps.sh on both sides") + delivered = bool(data.get("delivered")) except asyncio.TimeoutError: break + return delivered + + +async def main(): + delivered = await webhub_send() + if delivered: + print("DELIVERED via WebHub") + return + print("WebHub delivery failed — trying VL1/overlay relay...") + for host in relay_hosts(): + for use_auth in (True, False): + label = "auth" if use_auth else "no-auth" + status, body = try_relay(host, use_auth) + print(f" relay {host}:{port} ({label}) -> {status} {body}") + if status == 200 and isinstance(body, dict) and body.get("queued"): + print("QUEUED via overlay relay (recipient needs Secure Chat open + updated backone)") + return + print("NOT DELIVERED — run: sudo ./scripts/install-secure-chat-deps.sh on BOTH machines") asyncio.run(main()) -print("done") PY diff --git a/src/secure_chat/mod.rs b/src/secure_chat/mod.rs index 56dc43c..37e98b3 100644 --- a/src/secure_chat/mod.rs +++ b/src/secure_chat/mod.rs @@ -1,3 +1,4 @@ +mod relay; mod state; mod webhub; @@ -507,6 +508,10 @@ unsafe extern "C" fn on_timer(_: *mut c_void) -> c_int { network_id: nwid.to_lowercase(), }); } + let self_id = c.client.self_address(); + for msg in poll_incoming_chat(&c.client, &self_id) { + ingest_chat_message(msg); + } update_send_enabled(); } HubEvent::Disconnected => { @@ -521,16 +526,39 @@ unsafe extern "C" fn on_timer(_: *mut c_void) -> c_int { if !delivered { if let Some(peer) = selected_peer() { if peer.peer_id.eq_ignore_ascii_case(&target_id) { - let now = crate::serviceclient::ms_since_epoch(); - c.session.thread_for(&peer.peer_id).push(ChatLine { - sender: String::from("system"), - sender_name: String::from("system"), - body: String::from( - "Message not delivered — peer may be offline or Secure Chat is not open", - ), - at: now, - }); - render_thread(); + if let Some(network_id) = selected_network_id() { + let name = self_display_name(&c.client); + let body = c + .session + .thread_for(&peer.peer_id) + .last() + .filter(|line| line.sender == "me") + .map(|line| line.body.clone()) + .unwrap_or_default(); + if !body.is_empty() { + let relayed = relay::relay_chat_to_peer_paths( + &c.client, + &network_id, + &c.client.self_address(), + &name, + &peer.peer_id, + &body, + ); + let now = crate::serviceclient::ms_since_epoch(); + let msg = if relayed { + "Message relayed over VL1 — recipient needs Secure Chat open" + } else { + "Message not delivered — run install-secure-chat-deps.sh on both machines and open Secure Chat on recipient" + }; + c.session.thread_for(&peer.peer_id).push(ChatLine { + sender: String::from("system"), + sender_name: String::from("system"), + body: String::from(msg), + at: now, + }); + render_thread(); + } + } } } } diff --git a/src/secure_chat/relay.rs b/src/secure_chat/relay.rs new file mode 100644 index 0000000..a1cb9dd --- /dev/null +++ b/src/secure_chat/relay.rs @@ -0,0 +1,99 @@ +use serde_json::json; + +use crate::serviceclient::ServiceClient; + +fn peer_path_hosts(client: &ServiceClient, target_id: &str) -> Vec { + let target = target_id.to_lowercase(); + let Some(peers) = client.http_get_json("/peer").and_then(|v| v.as_array().cloned()) else { + return Vec::new(); + }; + let mut hosts = Vec::new(); + for peer in peers { + let peer_id = peer + .get("address") + .and_then(|a| a.as_str()) + .unwrap_or("") + .to_lowercase(); + if peer_id != target { + continue; + } + let Some(paths) = peer.get("paths").and_then(|p| p.as_array()) else { + break; + }; + for path in paths { + let Some(addr) = path.get("address").and_then(|a| a.as_str()) else { + continue; + }; + let host = addr.split('/').next().unwrap_or(addr).trim(); + if host.is_empty() || hosts.iter().any(|h| h == host) { + continue; + } + hosts.push(host.to_string()); + } + break; + } + hosts +} + +fn post_relay_url( + host: &str, + port: u16, + auth_token: Option<&str>, + payload: &str, +) -> (u16, String) { + let url = format!("http://{}:{}/controller/comms/chat/relay", host, port); + let mut req = ureq::post(&url).timeout(std::time::Duration::from_millis(4000)); + if let Some(token) = auth_token.filter(|t| !t.is_empty()) { + req = req.set("X-ZT1-Auth", token); + } + req.send_string(payload).map_or_else( + |e| match e { + ureq::Error::Status(status, resp) => { + let body = resp.into_string().unwrap_or_default(); + (status, body) + } + _ => (0, String::new()), + }, + |resp| { + let status = resp.status(); + let body = resp.into_string().unwrap_or_default(); + (status, body) + }, + ) +} + +/// Queue a chat message on a remote peer's backone via VL1 path hosts. +pub fn relay_chat_to_peer_paths( + client: &ServiceClient, + network_id: &str, + sender_id: &str, + sender_name: &str, + target_id: &str, + body: &str, +) -> bool { + let port = client.http_port(); + if port == 0 { + return false; + } + let payload = json!({ + "networkId": network_id.to_lowercase(), + "senderId": sender_id.to_lowercase(), + "senderName": sender_name, + "targetId": target_id.to_lowercase(), + "body": body, + "at": crate::serviceclient::ms_since_epoch(), + }); + let payload_str = payload.to_string(); + let token = client.auth_token(); + + for host in peer_path_hosts(client, target_id) { + for use_auth in [true, false] { + let auth = if use_auth { Some(token) } else { None }; + let (status, resp_body) = post_relay_url(&host, port, auth, &payload_str); + if status == 200 && resp_body.contains("\"queued\":true") { + return true; + } + } + } + false +} diff --git a/src/secure_chat/state.rs b/src/secure_chat/state.rs index da0c147..485242f 100644 --- a/src/secure_chat/state.rs +++ b/src/secure_chat/state.rs @@ -404,6 +404,9 @@ pub fn network_choices(client: &ServiceClient) -> Vec<(String, String)> { } pub fn network_ids_match(selected: Option<&str>, incoming: &str) -> bool { + if incoming.is_empty() { + return selected.is_some(); + } let Some(sel) = selected else { return false; }; diff --git a/src/serviceclient.rs b/src/serviceclient.rs index 4c409e3..59ebeea 100644 --- a/src/serviceclient.rs +++ b/src/serviceclient.rs @@ -460,6 +460,10 @@ impl ServiceClient { &self.auth_token } + pub fn http_port(&self) -> u16 { + self.port + } + fn http_get(&self, path: &str) -> (u16, String) { if self.auth_token.is_empty() || self.base_url.is_empty() { (0, String::new())