#!/bin/bash # ============================================================================= # WaouW Relay Tunnel — Host-side setup script # ============================================================================= # Called by systemd path unit when /etc/waouw/relay_request.json appears. # Generates WG keys, uses the backend container to call waouw-admin (which has # the Ed25519 signing logic), then starts WireGuard on the host. # ============================================================================= set -euo pipefail REQUEST_FILE="/etc/waouw/relay_request.json" STATE_FILE="/etc/waouw/relay_tunnel.json" WG_CONF="/etc/wireguard/wg0.conf" LOG_TAG="waouw-relay-tunnel" log() { logger -t "$LOG_TAG" "$*"; echo "[relay-tunnel] $*"; } err() { logger -t "$LOG_TAG" -p err "$*"; echo "[relay-tunnel] ERROR: $*" >&2; } if [[ ! -f "$REQUEST_FILE" ]]; then log "No relay request file found, exiting" exit 0 fi ACTION=$(python3 -c "import json; print(json.load(open('$REQUEST_FILE')).get('action',''))" 2>/dev/null || echo "") if [[ "$ACTION" != "setup" ]]; then log "Unknown action: $ACTION" exit 0 fi HOSTNAME_VAL=$(python3 -c "import json; print(json.load(open('$REQUEST_FILE')).get('hostname','waouw'))" 2>/dev/null) log "Starting relay tunnel setup (hostname: $HOSTNAME_VAL)" # 1. Generate WireGuard keypair on the host log "Generating WireGuard keypair..." WG_PRIVKEY=$(wg genkey) WG_PUBKEY=$(echo "$WG_PRIVKEY" | wg pubkey) log "WG public key: $WG_PUBKEY" # 2. Call waouw-admin via the backend container (it has Ed25519 signing) log "Requesting tunnel via backend container..." # Write pubkey for the backend to read echo "$WG_PUBKEY" > /etc/waouw/wg_pubkey # Wait for backend container to be ready for i in $(seq 1 30); do if docker exec waouw_backend curl -sf http://localhost:8000/health > /dev/null 2>&1; then break fi sleep 2 done RESULT=$(docker exec waouw_backend python3 -c " import asyncio, json, sys, warnings, logging warnings.filterwarnings('ignore') logging.disable(logging.CRITICAL) sys.path.insert(0, '/app') from app.services.waouw_auth import waouw_auth async def main(): wg_pubkey = open('/etc/waouw/wg_pubkey').read().strip() result = await waouw_auth.request_relay_tunnel(wg_pubkey, []) print(json.dumps(result)) # Close session to avoid warnings if waouw_auth.session: await waouw_auth.session.close() asyncio.run(main()) " 2>/dev/null) log "waouw-admin response: $RESULT" OK=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print('yes' if d.get('ok') else 'no')" 2>/dev/null || echo "no") if [[ "$OK" != "yes" ]]; then err "Tunnel provisioning failed: $RESULT" # Keep the request file for retry exit 1 fi # 3. Extract relay config WG_IP=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('relay',{}).get('wg_ip',''))" 2>/dev/null) RELAY_ENDPOINT=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('relay',{}).get('relay_endpoint',''))" 2>/dev/null) RELAY_PUBKEY=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('relay',{}).get('relay_public_key',''))" 2>/dev/null) if [[ -z "$WG_IP" || -z "$RELAY_ENDPOINT" || -z "$RELAY_PUBKEY" ]]; then err "Incomplete relay config: WG_IP=$WG_IP ENDPOINT=$RELAY_ENDPOINT PUBKEY=$RELAY_PUBKEY" exit 1 fi # 4. Write WireGuard config log "Writing WireGuard config: $WG_IP → $RELAY_ENDPOINT" mkdir -p /etc/wireguard cat > "$WG_CONF" << EOF [Interface] Address = ${WG_IP}/32 PrivateKey = ${WG_PRIVKEY} [Peer] PublicKey = ${RELAY_PUBKEY} Endpoint = ${RELAY_ENDPOINT} AllowedIPs = 10.100.0.1/32 PersistentKeepalive = 25 EOF chmod 600 "$WG_CONF" # 5. Start WireGuard log "Starting WireGuard tunnel..." wg-quick down wg0 2>/dev/null || true wg-quick up wg0 # 6. Enable on boot systemctl enable wg-quick@wg0 2>/dev/null || true # 7. Save state cat > "$STATE_FILE" << EOF { "status": "active", "wg_ip": "${WG_IP}", "relay_endpoint": "${RELAY_ENDPOINT}", "relay_public_key": "${RELAY_PUBKEY}", "public_key": "${WG_PUBKEY}" } EOF # 8. Scan existing sites and add their subdomains to the tunnel log "Scanning existing sites for subdomains..." SITE_DOMAINS=$(docker exec waouw_postgres psql -U waouw -d waouw -t -A -c "SELECT domain FROM sites WHERE status = 'RUNNING' AND domain LIKE '%.waouw.tech'" 2>/dev/null || echo "") ALL_SUBS="" if [[ -n "$SITE_DOMAINS" ]]; then while IFS= read -r dom; do dom=$(echo "$dom" | tr -d '[:space:]') if [[ -n "$dom" ]]; then if [[ -n "$ALL_SUBS" ]]; then ALL_SUBS="$ALL_SUBS,$dom" else ALL_SUBS="$dom" fi fi done <<< "$SITE_DOMAINS" fi # Build JSON array of subdomains SUB_JSON=$(echo "$ALL_SUBS" | tr ',' '\n' | sort -u | awk 'NF{printf "%s\"%s\"", (NR>1?",":""), $0}') SUB_JSON="[$SUB_JSON]" if [[ -n "$ALL_SUBS" ]]; then log "Updating tunnel subdomains: $SUB_JSON" docker exec waouw_backend python3 -c " import asyncio, json, sys, logging logging.disable(logging.CRITICAL) sys.path.insert(0, '/app') from app.services.waouw_auth import waouw_auth async def main(): payload = {'action': 'update_subdomains', 'subdomains': $SUB_JSON} body = json.dumps(payload, separators=(',',':'), sort_keys=True).encode() import hashlib, time ts = str(int(time.time())) body_hash = hashlib.sha256(body).hexdigest() path = '/api/relay_provision.php' headers = waouw_auth._sign_headers('POST', path, body=body) headers['Content-Type'] = 'application/json' session = await waouw_auth.get_session() async with session.post(f'{waouw_auth.admin_url}{path}', data=body, headers=headers) as resp: data = await resp.json(content_type=None) print(json.dumps(data)) if waouw_auth.session: await waouw_auth.session.close() asyncio.run(main()) " 2>/dev/null || log "Warning: subdomain update failed" fi # 9. Clean up rm -f "$REQUEST_FILE" /etc/waouw/wg_pubkey log "Relay tunnel UP: $WG_IP → $RELAY_ENDPOINT" log "Done."