258 lines
7.8 KiB
Bash
Executable File
258 lines
7.8 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Send a Secure Chat test message via backone-webhub (WebSocket).
|
|
# Usage: ./scripts/send-secure-chat-test.sh <network_id> <target_peer_id> [message]
|
|
set -euo pipefail
|
|
|
|
NETWORK_ID="${1:?network id required (16 hex chars)}"
|
|
TARGET_ID="${2:?target peer id required (10 hex chars)}"
|
|
MSG="${3:-ping from send-secure-chat-test.sh}"
|
|
|
|
OS="$(uname -s)"
|
|
if [[ "$OS" == "Darwin" ]]; then
|
|
SERVICE_HOME="/Library/Application Support/BackOne"
|
|
DEFAULT_HUB_PORT=9993
|
|
else
|
|
SERVICE_HOME="/var/lib/backone"
|
|
DEFAULT_HUB_PORT=9994
|
|
fi
|
|
|
|
TOKEN="$(
|
|
cat ~/.backone-local-auth 2>/dev/null \
|
|
|| cat ~/.backOneAuthToken 2>/dev/null \
|
|
|| sudo cat "${SERVICE_HOME}/authtoken.secret"
|
|
)"
|
|
PORT="$(cat "${SERVICE_HOME}/backone.port" 2>/dev/null || echo 9993)"
|
|
|
|
MY_ID="$(
|
|
curl -sf -H "X-ZT1-Auth: $TOKEN" "http://127.0.0.1:${PORT}/status" \
|
|
| jq -r '.address' | tr '[:upper:]' '[:lower:]'
|
|
)"
|
|
|
|
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
|
|
)"
|
|
if [[ -z "$HUB_PORT" ]]; then
|
|
if [[ "$OS" == "Darwin" ]]; then
|
|
if nc -z 127.0.0.1 "$DEFAULT_HUB_PORT" 2>/dev/null; then
|
|
HUB_PORT="$DEFAULT_HUB_PORT"
|
|
fi
|
|
elif ss -tln 2>/dev/null | rg -q "127\\.0\\.0\\.1:${DEFAULT_HUB_PORT}"; then
|
|
HUB_PORT="$DEFAULT_HUB_PORT"
|
|
else
|
|
echo "Could not detect webhub port. Is backone-webhub running?" >&2
|
|
exit 1
|
|
fi
|
|
fi
|
|
|
|
NETWORK_ID="${NETWORK_ID,,}"
|
|
TARGET_ID="${TARGET_ID,,}"
|
|
|
|
echo "My ID: $MY_ID"
|
|
echo "Hub port: $HUB_PORT"
|
|
echo "Network: $NETWORK_ID"
|
|
echo "Target: $TARGET_ID"
|
|
echo "Message: $MSG"
|
|
|
|
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' \
|
|
| head -1
|
|
)"
|
|
if [[ -n "$PEER_OK" ]]; then
|
|
echo "Peer VL1: online ($PEER_OK)"
|
|
else
|
|
echo "Peer VL1: not in /peer list"
|
|
fi
|
|
|
|
if [[ "$OS" != "Darwin" ]] && ! 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 [[ "$OS" != "Darwin" ]] && ! 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
|
|
if [[ "$OS" == "Darwin" ]]; then
|
|
echo " python3 -m pip install websockets" >&2
|
|
else
|
|
echo " sudo apt install python3-websockets" >&2
|
|
fi
|
|
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
|
|
|
|
token = os.environ["TOKEN"]
|
|
my_id = os.environ["MY_ID"]
|
|
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"]
|
|
|
|
|
|
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({
|
|
"type": "register",
|
|
"peerId": my_id,
|
|
"networkId": network_id,
|
|
}))
|
|
await ws.send(json.dumps({
|
|
"type": "chat_message",
|
|
"networkId": network_id,
|
|
"targetId": target_id,
|
|
"senderName": my_id,
|
|
"body": msg,
|
|
}))
|
|
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":
|
|
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())
|
|
PY
|