1
0

waouw-relay-tunnel.sh 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/bin/bash
  2. # =============================================================================
  3. # WaouW Relay Tunnel — Host-side setup script
  4. # =============================================================================
  5. # Called by systemd path unit when /etc/waouw/relay_request.json appears.
  6. # Generates WG keys, uses the backend container to call waouw-admin (which has
  7. # the Ed25519 signing logic), then starts WireGuard on the host.
  8. # =============================================================================
  9. set -euo pipefail
  10. REQUEST_FILE="/etc/waouw/relay_request.json"
  11. STATE_FILE="/etc/waouw/relay_tunnel.json"
  12. WG_CONF="/etc/wireguard/wg0.conf"
  13. LOG_TAG="waouw-relay-tunnel"
  14. log() { logger -t "$LOG_TAG" "$*"; echo "[relay-tunnel] $*"; }
  15. err() { logger -t "$LOG_TAG" -p err "$*"; echo "[relay-tunnel] ERROR: $*" >&2; }
  16. if [[ ! -f "$REQUEST_FILE" ]]; then
  17. log "No relay request file found, exiting"
  18. exit 0
  19. fi
  20. ACTION=$(python3 -c "import json; print(json.load(open('$REQUEST_FILE')).get('action',''))" 2>/dev/null || echo "")
  21. if [[ "$ACTION" != "setup" ]]; then
  22. log "Unknown action: $ACTION"
  23. exit 0
  24. fi
  25. HOSTNAME_VAL=$(python3 -c "import json; print(json.load(open('$REQUEST_FILE')).get('hostname','waouw'))" 2>/dev/null)
  26. log "Starting relay tunnel setup (hostname: $HOSTNAME_VAL)"
  27. # 1. Generate WireGuard keypair on the host
  28. log "Generating WireGuard keypair..."
  29. WG_PRIVKEY=$(wg genkey)
  30. WG_PUBKEY=$(echo "$WG_PRIVKEY" | wg pubkey)
  31. log "WG public key: $WG_PUBKEY"
  32. # 2. Call waouw-admin via the backend container (it has Ed25519 signing)
  33. log "Requesting tunnel via backend container..."
  34. # Write pubkey for the backend to read
  35. echo "$WG_PUBKEY" > /etc/waouw/wg_pubkey
  36. # Wait for backend container to be ready
  37. for i in $(seq 1 30); do
  38. if docker exec waouw_backend curl -sf http://localhost:8000/health > /dev/null 2>&1; then
  39. break
  40. fi
  41. sleep 2
  42. done
  43. RESULT=$(docker exec waouw_backend python3 -c "
  44. import asyncio, json, sys, warnings, logging
  45. warnings.filterwarnings('ignore')
  46. logging.disable(logging.CRITICAL)
  47. sys.path.insert(0, '/app')
  48. from app.services.waouw_auth import waouw_auth
  49. async def main():
  50. wg_pubkey = open('/etc/waouw/wg_pubkey').read().strip()
  51. result = await waouw_auth.request_relay_tunnel(wg_pubkey, [])
  52. print(json.dumps(result))
  53. # Close session to avoid warnings
  54. if waouw_auth.session:
  55. await waouw_auth.session.close()
  56. asyncio.run(main())
  57. " 2>/dev/null)
  58. log "waouw-admin response: $RESULT"
  59. 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")
  60. if [[ "$OK" != "yes" ]]; then
  61. err "Tunnel provisioning failed: $RESULT"
  62. # Keep the request file for retry
  63. exit 1
  64. fi
  65. # 3. Extract relay config
  66. WG_IP=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('relay',{}).get('wg_ip',''))" 2>/dev/null)
  67. RELAY_ENDPOINT=$(echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('relay',{}).get('relay_endpoint',''))" 2>/dev/null)
  68. 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)
  69. if [[ -z "$WG_IP" || -z "$RELAY_ENDPOINT" || -z "$RELAY_PUBKEY" ]]; then
  70. err "Incomplete relay config: WG_IP=$WG_IP ENDPOINT=$RELAY_ENDPOINT PUBKEY=$RELAY_PUBKEY"
  71. exit 1
  72. fi
  73. # 4. Write WireGuard config
  74. log "Writing WireGuard config: $WG_IP → $RELAY_ENDPOINT"
  75. mkdir -p /etc/wireguard
  76. cat > "$WG_CONF" << EOF
  77. [Interface]
  78. Address = ${WG_IP}/32
  79. PrivateKey = ${WG_PRIVKEY}
  80. [Peer]
  81. PublicKey = ${RELAY_PUBKEY}
  82. Endpoint = ${RELAY_ENDPOINT}
  83. AllowedIPs = 10.100.0.1/32
  84. PersistentKeepalive = 25
  85. EOF
  86. chmod 600 "$WG_CONF"
  87. # 5. Start WireGuard
  88. log "Starting WireGuard tunnel..."
  89. wg-quick down wg0 2>/dev/null || true
  90. wg-quick up wg0
  91. # 6. Enable on boot
  92. systemctl enable wg-quick@wg0 2>/dev/null || true
  93. # 7. Save state
  94. cat > "$STATE_FILE" << EOF
  95. {
  96. "status": "active",
  97. "wg_ip": "${WG_IP}",
  98. "relay_endpoint": "${RELAY_ENDPOINT}",
  99. "relay_public_key": "${RELAY_PUBKEY}",
  100. "public_key": "${WG_PUBKEY}"
  101. }
  102. EOF
  103. # 8. Scan existing sites and add their subdomains to the tunnel
  104. log "Scanning existing sites for subdomains..."
  105. 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 "")
  106. ALL_SUBS=""
  107. if [[ -n "$SITE_DOMAINS" ]]; then
  108. while IFS= read -r dom; do
  109. dom=$(echo "$dom" | tr -d '[:space:]')
  110. if [[ -n "$dom" ]]; then
  111. if [[ -n "$ALL_SUBS" ]]; then
  112. ALL_SUBS="$ALL_SUBS,$dom"
  113. else
  114. ALL_SUBS="$dom"
  115. fi
  116. fi
  117. done <<< "$SITE_DOMAINS"
  118. fi
  119. # Build JSON array of subdomains
  120. SUB_JSON=$(echo "$ALL_SUBS" | tr ',' '\n' | sort -u | awk 'NF{printf "%s\"%s\"", (NR>1?",":""), $0}')
  121. SUB_JSON="[$SUB_JSON]"
  122. if [[ -n "$ALL_SUBS" ]]; then
  123. log "Updating tunnel subdomains: $SUB_JSON"
  124. docker exec waouw_backend python3 -c "
  125. import asyncio, json, sys, logging
  126. logging.disable(logging.CRITICAL)
  127. sys.path.insert(0, '/app')
  128. from app.services.waouw_auth import waouw_auth
  129. async def main():
  130. payload = {'action': 'update_subdomains', 'subdomains': $SUB_JSON}
  131. body = json.dumps(payload, separators=(',',':'), sort_keys=True).encode()
  132. import hashlib, time
  133. ts = str(int(time.time()))
  134. body_hash = hashlib.sha256(body).hexdigest()
  135. path = '/api/relay_provision.php'
  136. headers = waouw_auth._sign_headers('POST', path, body=body)
  137. headers['Content-Type'] = 'application/json'
  138. session = await waouw_auth.get_session()
  139. async with session.post(f'{waouw_auth.admin_url}{path}', data=body, headers=headers) as resp:
  140. data = await resp.json(content_type=None)
  141. print(json.dumps(data))
  142. if waouw_auth.session: await waouw_auth.session.close()
  143. asyncio.run(main())
  144. " 2>/dev/null || log "Warning: subdomain update failed"
  145. fi
  146. # 9. Clean up
  147. rm -f "$REQUEST_FILE" /etc/waouw/wg_pubkey
  148. log "Relay tunnel UP: $WG_IP → $RELAY_ENDPOINT"
  149. log "Done."