1.0.0
Wydanie WGTools-Extended / release (push) Failing after 16s

This commit is contained in:
asminme committed 2026-10-30 00:35:08 +01:00
1 parent f5bdd7e21c
commit affe28ad71
110 files changed
+52936 -14

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
echo "Run as root: sudo bash $0" >&2
exit 1
fi
if [[ "${WGTOOLS_FULL_CLEAN_CONFIRMED:-0}" != "1" ]]; then
cat <<'TXT'
WARNING: FULL CLEANUP removes WGTools, all WireGuard interfaces/configs,
local WGTools Relay state and the WGTools Let's Encrypt certificate from THIS host.
Remote Relay Agents on other VPS hosts are not contacted.
TXT
printf '\nType DELETE ALL to continue: '
read -r answer
[[ "$answer" == "DELETE ALL" ]] || { echo "Cancelled."; exit 0; }
fi
echo "[1/7] Stopping WGTools and Relay services..."
for unit in \
wgtools.service wgtools-telegram.service \
wgtools-expiry.timer wgtools-expiry.service \
wgtools-certbot-renew.timer wgtools-certbot-renew.service \
wg-quick@wgnode0.service
do
systemctl disable --now "$unit" >/dev/null 2>&1 || true
done
mapfile -t relay_units < <(
systemctl list-unit-files --type=service --no-legend 2>/dev/null \
| awk '$1 ~ /^wgtools-relay-(agent|transport-|home-)/ {print $1}' \
| sort -u
)
for unit in "${relay_units[@]}"; do
systemctl disable --now "$unit" >/dev/null 2>&1 || true
done
echo "[2/7] Bringing down WireGuard interfaces..."
if [[ -d /etc/wireguard ]]; then
shopt -s nullglob
for conf in /etc/wireguard/*.conf; do
iface="$(basename "$conf" .conf)"
systemctl disable --now "wg-quick@${iface}.service" >/dev/null 2>&1 || true
if command -v wg-quick >/dev/null 2>&1; then
wg-quick down "$iface" >/dev/null 2>&1 || true
fi
done
shopt -u nullglob
fi
# Also stop enabled wg-quick units whose config may already be missing.
while read -r unit _; do
[[ "$unit" == wg-quick@*.service ]] || continue
systemctl disable --now "$unit" >/dev/null 2>&1 || true
done < <(systemctl list-unit-files 'wg-quick@*.service' --no-legend 2>/dev/null || true)
if command -v wg >/dev/null 2>&1; then
for iface in $(wg show interfaces 2>/dev/null || true); do
ip link delete "$iface" >/dev/null 2>&1 || true
done
fi
echo "[3/7] Removing WGTools firewall/NAT leftovers..."
if command -v iptables >/dev/null 2>&1; then
# Known direct Nodes rules.
while iptables -C FORWARD -i wgnode0 -j ACCEPT >/dev/null 2>&1; do iptables -D FORWARD -i wgnode0 -j ACCEPT || true; done
while iptables -C FORWARD -o wgnode0 -j ACCEPT >/dev/null 2>&1; do iptables -D FORWARD -o wgnode0 -j ACCEPT || true; done
# Remove every rule that jumps to a WGTOOLS-* custom chain (including
# source/comment-qualified jumps), then remove the chains themselves.
for table in filter nat mangle; do
mapfile -t chains < <(iptables -t "$table" -S 2>/dev/null | awk '$1=="-N" && $2 ~ /^WGTOOLS-/ {print $2}')
for chain in "${chains[@]}"; do
mapfile -t jump_rules < <(iptables -t "$table" -S 2>/dev/null | grep -E "^-A .* -j ${chain}($| )" || true)
for rule in "${jump_rules[@]}"; do
eval "iptables -t '$table' ${rule/-A /-D }" >/dev/null 2>&1 || true
done
iptables -t "$table" -F "$chain" >/dev/null 2>&1 || true
iptables -t "$table" -X "$chain" >/dev/null 2>&1 || true
done
done
# Protection rules are direct FORWARD entries carrying a WGTools comment.
mapfile -t protect_rules < <(iptables -S FORWARD 2>/dev/null | grep -- '--comment wgtools-' || true)
for rule in "${protect_rules[@]}"; do
# iptables -S output is generated by the local kernel/iptables, not user input.
eval "iptables ${rule/-A FORWARD/-D FORWARD}" >/dev/null 2>&1 || true
done
fi
echo "[4/7] Removing WGTools files and systemd units..."
rm -f \
/etc/systemd/system/wgtools.service \
/etc/systemd/system/wgtools-telegram.service \
/etc/systemd/system/wgtools-expiry.service \
/etc/systemd/system/wgtools-expiry.timer \
/etc/systemd/system/wgtools-certbot-renew.service \
/etc/systemd/system/wgtools-certbot-renew.timer \
/etc/systemd/system/wgtools-relay-agent.service \
/etc/systemd/system/wgtools-relay-transport-*.service \
/etc/systemd/system/wgtools-relay-home-*.service \
/etc/sudoers.d/wgtools \
/usr/local/libexec/wgtools-helper \
/usr/local/libexec/wgtools-certbot-reload \
/usr/local/bin/wgtools \
/etc/sysctl.d/99-wgtools-wireguard.conf \
/var/lib/systemd/timers/stamp-wgtools-*
rm -rf \
/opt/wgtools \
/etc/wgtools \
/var/lib/wgtools \
/opt/wgtools-relay \
/var/lib/wgtools-relay \
/etc/wireguard \
/tmp/wgtools-install \
/tmp/wgtools-update* \
/tmp/wgtools-cli-* \
/tmp/wgtools-*
echo "[5/7] Removing WGTools Let's Encrypt certificate..."
if command -v certbot >/dev/null 2>&1; then
certbot delete --cert-name wgtools --non-interactive >/dev/null 2>&1 || true
fi
rm -rf /etc/letsencrypt/live/wgtools /etc/letsencrypt/archive/wgtools
rm -f /etc/letsencrypt/renewal/wgtools.conf
echo "[6/7] Removing WireGuard packages..."
export DEBIAN_FRONTEND=noninteractive
if command -v apt-get >/dev/null 2>&1; then
apt-get purge -y wireguard wireguard-tools || true
apt-get autoremove -y --purge || true
fi
echo "[7/7] Reloading system state..."
systemctl daemon-reload
systemctl reset-failed >/dev/null 2>&1 || true
sysctl --system >/dev/null 2>&1 || true
echo
echo "Done: WGTools, local Relay state, all WireGuard configs/interfaces and WGTools-specific files were removed from this host."
echo "Remote Relay Agents on other VPS hosts were not changed."
echo "Shared OS tools (Python, iproute2, iptables, certbot, OpenSSH) were intentionally preserved."
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Create a Gitea release from a version tag; the .bin is a gzip tar archive."""
from __future__ import annotations
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
from urllib.parse import quote
from urllib.request import Request, urlopen
import uuid
def main() -> None:
tag = os.environ['GITHUB_REF_NAME']
if not re.fullmatch(r'v\d+\.\d+\.\d+', tag):
raise ValueError('Tag wydania musi mieć postać v1.2.3')
if Path('VERSION').read_text(encoding='utf-8').strip() != tag[1:]:
raise ValueError('VERSION musi odpowiadać tagowi wydania')
server = os.environ['GITHUB_SERVER_URL'].rstrip('/')
repo = os.environ['GITHUB_REPOSITORY']
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo):
raise ValueError('Nieprawidłowa nazwa repozytorium')
token = os.environ['GITEA_RELEASE_TOKEN']
if not token:
raise ValueError('Brakuje sekretu GITEA_RELEASE_TOKEN')
api = f'{server}/api/v1/repos/{repo}/releases'
def request(url: str, method: str, data: bytes, content_type: str) -> dict:
req = Request(url, data=data, method=method, headers={'Authorization': f'token {token}', 'Content-Type': content_type})
with urlopen(req, timeout=120) as response:
return json.load(response)
with tempfile.TemporaryDirectory() as tmp:
package = Path(tmp) / f'WGTools-Extended-{tag[1:]}.bin'
for required in ('VERSION', 'app/main.py', 'scripts/wgtools-helper', 'scripts/install.sh'):
subprocess.run(['git', 'cat-file', '-e', f'HEAD:{required}'], check=True)
subprocess.run(['git', 'archive', '--format=tar.gz', f'--output={package}', 'HEAD'], check=True)
title = f'WGTools-Extended wersja {tag[1:]}'
release = request(api, 'POST', json.dumps({'tag_name': tag, 'name': title, 'body': title, 'draft': True}).encode(), 'application/json')
boundary = 'wgtools' + uuid.uuid4().hex
body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{package.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
+ package.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
request(f'{api}/{int(release["id"])}/assets?name={quote(package.name)}', 'POST', body, f'multipart/form-data; boundary={boundary}')
request(f'{api}/{int(release["id"])}', 'PATCH', b'{"draft":false}', 'application/json')
if __name__ == '__main__':
main()
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env bash
set -euo pipefail
APP_DIR=/opt/wgtools
# Keep custom settings when upgrading an existing native installation.
# Avoid overriding environment explicitly supplied for a fresh install.
if [[ -r /etc/wgtools/wgtools.env ]]; then
# shellcheck disable=SC1091
source /etc/wgtools/wgtools.env
fi
WG_INTERFACE="${WG_INTERFACE:-${WGTOOLS_INTERFACE:-wg0}}"
WEB_PORT="${WGTOOLS_PORT:-8341}"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [[ ${EUID} -ne 0 ]]; then
echo "Run this installer as root." >&2
exit 1
fi
if [[ ! "$WG_INTERFACE" =~ ^[A-Za-z0-9_.-]{1,15}$ ]]; then
echo "Invalid WireGuard interface: $WG_INTERFACE" >&2
exit 1
fi
echo "[1/8] Installing WGTools runtime packages..."
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-venv python3-pip iproute2 iputils-ping traceroute curl openssh-client sshpass openssl
echo "[2/8] Preparing directories..."
install -d -o root -g root -m 0755 /var/lib/wgtools /etc/wgtools /usr/local/libexec /usr/local/bin
if [[ ! -s /var/lib/wgtools/session.key ]]; then
python3 - <<'PYSECRET'
from pathlib import Path
import secrets
p=Path('/var/lib/wgtools/session.key')
p.write_text(secrets.token_hex(32), encoding='utf-8')
p.chmod(0o600)
PYSECRET
fi
touch /var/lib/wgtools/wgtools.db
chmod 0600 /var/lib/wgtools/session.key /var/lib/wgtools/wgtools.db
echo "[3/8] Installing application..."
# Stop only the WGTools web service while replacing its files. WireGuard itself is not touched.
if systemctl is-active --quiet wgtools-telegram.service 2>/dev/null; then
systemctl stop wgtools-telegram.service
fi
if systemctl is-active --quiet wgtools-expiry.timer 2>/dev/null; then
systemctl stop wgtools-expiry.timer
fi
if systemctl is-active --quiet wgtools-certbot-renew.timer 2>/dev/null; then
systemctl stop wgtools-certbot-renew.timer
fi
if systemctl is-active --quiet wgtools.service 2>/dev/null; then
systemctl stop wgtools.service
fi
rm -rf "$APP_DIR"
mkdir -p "$APP_DIR"
cp -a "$SOURCE_DIR"/. "$APP_DIR"/
rm -rf "$APP_DIR/.git" "$APP_DIR/.github" "$APP_DIR/.venv" "$APP_DIR/.test-deps" "$APP_DIR/tests"
find "$APP_DIR" -type d -name __pycache__ -prune -exec rm -rf {} + 2>/dev/null || true
chown -R root:root "$APP_DIR"
# Normalize executable bits after archive extraction or Windows/Git workflows.
chmod 0755 "$APP_DIR/scripts/install.sh" "$APP_DIR/scripts/uninstall.sh" "$APP_DIR/scripts/full-clean.sh" "$APP_DIR/scripts/wgtools-web" "$APP_DIR/scripts/wgtools-cli" "$APP_DIR/scripts/wgtools-certbot-reload" "$APP_DIR/scripts/wgtools-helper"
python3 -m venv "$APP_DIR/.venv"
"$APP_DIR/.venv/bin/pip" install --upgrade pip >/dev/null
"$APP_DIR/.venv/bin/pip" install -r "$APP_DIR/requirements.txt"
echo "[4/8] Installing root helper..."
install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-helper" /usr/local/libexec/wgtools-helper
install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-certbot-reload" /usr/local/libexec/wgtools-certbot-reload
install -o root -g root -m 0755 "$APP_DIR/scripts/wgtools-cli" /usr/local/bin/wgtools
if [[ ! -f /etc/wgtools/wgtools.env ]]; then
cat > /etc/wgtools/wgtools.env <<ENV
WGTOOLS_INTERFACE=$WG_INTERFACE
WGTOOLS_PORT=$WEB_PORT
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
WGTOOLS_REFRESH_SECONDS=5
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
WGTOOLS_SESSION_MAX_AGE_SECONDS=2592000
ENV
chmod 0644 /etc/wgtools/wgtools.env
else
echo "Preserving existing /etc/wgtools/wgtools.env"
fi
rm -f /etc/sudoers.d/wgtools
echo "[5/8] Installing systemd services (run as root)..."
cp "$APP_DIR/systemd/wgtools.service" /etc/systemd/system/wgtools.service
cp "$APP_DIR/systemd/wgtools-telegram.service" /etc/systemd/system/wgtools-telegram.service
cp "$APP_DIR/systemd/wgtools-expiry.service" /etc/systemd/system/wgtools-expiry.service
cp "$APP_DIR/systemd/wgtools-expiry.timer" /etc/systemd/system/wgtools-expiry.timer
cp "$APP_DIR/systemd/wgtools-certbot-renew.service" /etc/systemd/system/wgtools-certbot-renew.service
cp "$APP_DIR/systemd/wgtools-certbot-renew.timer" /etc/systemd/system/wgtools-certbot-renew.timer
systemctl daemon-reload
systemctl enable wgtools.service >/dev/null
systemctl enable wgtools-telegram.service >/dev/null
systemctl enable wgtools-expiry.timer >/dev/null
if [[ -r /etc/wgtools/https.env ]] && grep -q '^WGTOOLS_HTTPS_ENABLED=1$' /etc/wgtools/https.env; then
systemctl enable wgtools-certbot-renew.timer >/dev/null
systemctl restart wgtools-certbot-renew.timer
fi
systemctl restart wgtools.service
systemctl restart wgtools-expiry.timer
echo "[6/8] Waiting for web service..."
READY=0
HTTPS_ENABLED=0
HTTPS_PORT=443
WGTOOLS_ACCESS_PATH=""
if [[ -r /etc/wgtools/https.env ]]; then
# shellcheck disable=SC1091
source /etc/wgtools/https.env
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
WGTOOLS_ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}"
fi
for _ in $(seq 1 25); do
if [[ "$HTTPS_ENABLED" == "1" ]]; then
if curl -kfsS "https://127.0.0.1:${HTTPS_PORT}${WGTOOLS_ACCESS_PATH%/}/healthz" >/dev/null 2>&1; then
READY=1
break
fi
elif curl -fsS "http://127.0.0.1:${WEB_PORT}/healthz" >/dev/null 2>&1; then
READY=1
break
fi
sleep 1
done
if [[ "$READY" -ne 1 ]]; then
echo "WGTools did not become ready. Recent log:" >&2
journalctl -u wgtools.service -n 60 --no-pager >&2 || true
exit 1
fi
echo "[7/8] Starting integrated Telegram bot service..."
systemctl restart wgtools-telegram.service
sleep 1
if ! systemctl is-active --quiet wgtools-telegram.service; then
echo "WGTools Telegram service did not start. Recent log:" >&2
journalctl -u wgtools-telegram.service -n 40 --no-pager >&2 || true
exit 1
fi
echo "Telegram service OK (it stays idle until a BotFather token is enabled in Settings)."
echo "[8/8] Running helper self-test..."
printf '%s\n' '{"view":"server"}' | timeout --foreground 20s /usr/local/libexec/wgtools-helper snapshot "$WG_INTERFACE" >/tmp/wgtools-selftest.json
python3 - <<'PY'
import json
with open('/tmp/wgtools-selftest.json', encoding='utf-8') as f:
data=json.load(f)
assert data.get('ok') is True, data
wg=data.get('wireguard', {})
assert isinstance(data.get('route_items', []), list), data
assert isinstance(data.get('firewall_items', []), list), data
assert isinstance(data.get('client_groups', []), list), data
print(f"Helper OK: state={wg.get('state')} interface={data.get('interface')} routes={len(data.get('route_items', []))} firewall={len(data.get('firewall_items', []))}")
PY
rm -f /tmp/wgtools-selftest.json
# Create and immediately remove a full migration backup as a non-destructive smoke test.
timeout --foreground 60s /usr/local/libexec/wgtools-helper migration_backup_create "$WG_INTERFACE" </dev/null >/tmp/wgtools-migration-selftest.json
python3 - <<'PY'
import json
from pathlib import Path
with open('/tmp/wgtools-migration-selftest.json', encoding='utf-8') as f:
data=json.load(f)
assert data.get('ok') is True, data
p=Path(data.get('path',''))
assert p.is_file() and p.stat().st_size > 0, data
print(f"Migration backup helper OK: {p.name} ({p.stat().st_size} bytes)")
p.unlink()
PY
rm -f /tmp/wgtools-migration-selftest.json
# Smoke-test the raw configuration helper when a WireGuard config already exists.
# The HTTP API is intentionally protected by authentication from v0.6 onward.
if [[ -f "/etc/wireguard/${WG_INTERFACE}.conf" ]]; then
timeout --foreground 20s /usr/local/libexec/wgtools-helper raw_config_get "$WG_INTERFACE" </dev/null >/tmp/wgtools-raw-config-selftest.json
python3 - <<'PY'
import json
with open('/tmp/wgtools-raw-config-selftest.json', encoding='utf-8') as f:
data=json.load(f)
assert data.get('ok') is True, data
assert isinstance(data.get('content'), str) and '[Interface]' in data.get('content', ''), data
print('Raw config helper OK')
PY
rm -f /tmp/wgtools-raw-config-selftest.json
fi
echo
echo "WGTools v$(cat "$APP_DIR/VERSION") is installed."
echo "Service account: root (no additional Linux user is created)."
echo "WireGuard is NOT installed by the WGTools deploy script on a clean VM."
echo "If it is missing, install it later from Server -> Install WireGuard."
if [[ "$HTTPS_ENABLED" == "1" ]]; then
HTTPS_OPEN_HOST=""
if [[ -r /etc/wgtools/https.json ]]; then
HTTPS_OPEN_HOST="$(python3 - <<'PYHTTPSHOST'
import json
from pathlib import Path
try:
data=json.loads(Path('/etc/wgtools/https.json').read_text(encoding='utf-8'))
print(str(data.get('target') or '').strip())
except Exception:
pass
PYHTTPSHOST
)"
fi
if [[ -z "$HTTPS_OPEN_HOST" ]]; then
HTTPS_OPEN_HOST="$(hostname -I | awk '{print $1}')"
fi
if [[ "$HTTPS_OPEN_HOST" == *:* && "$HTTPS_OPEN_HOST" != \[*\] ]]; then
HTTPS_OPEN_HOST="[$HTTPS_OPEN_HOST]"
fi
HTTPS_OPEN_PATH="${WGTOOLS_ACCESS_PATH:-}"
if [[ -n "$HTTPS_OPEN_PATH" && "$HTTPS_OPEN_PATH" != */ ]]; then
HTTPS_OPEN_PATH="${HTTPS_OPEN_PATH}/"
fi
if [[ "$HTTPS_PORT" == "443" ]]; then
echo "Open: https://${HTTPS_OPEN_HOST}${HTTPS_OPEN_PATH}"
else
echo "Open: https://${HTTPS_OPEN_HOST}:${HTTPS_PORT}${HTTPS_OPEN_PATH}"
fi
else
echo "Open: http://$(hostname -I | awk '{print $1}'):${WEB_PORT}"
fi
echo "Web: systemctl status wgtools --no-pager"
echo "Telegram: systemctl status wgtools-telegram --no-pager"
echo "Access: systemctl status wgtools-expiry.timer --no-pager"
echo "Web logs: journalctl -u wgtools -f"
echo "Bot logs: journalctl -u wgtools-telegram -f"
echo "Console: wgtools"
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${EUID} -ne 0 ]]; then echo "Run as root" >&2; exit 1; fi
systemctl disable --now wgtools-certbot-renew.timer 2>/dev/null || true
systemctl disable --now wgtools-certbot-renew.service 2>/dev/null || true
systemctl disable --now wgtools-expiry.timer 2>/dev/null || true
systemctl disable --now wgtools-expiry.service 2>/dev/null || true
systemctl disable --now wgtools-telegram.service 2>/dev/null || true
systemctl disable --now wgtools.service 2>/dev/null || true
# The Nodes tunnel is an internal WGTools transport, not a user WireGuard server.
systemctl disable --now wg-quick@wgnode0.service 2>/dev/null || true
ip link delete wgnode0 2>/dev/null || true
rm -f /etc/wireguard/wgnode0.conf
# Detach local home-side Relay transports, but preserve /var/lib/wgtools so a
# later reinstall/restore can reconnect to the same remote Relay tenants.
for service in /etc/systemd/system/wgtools-relay-home-*.service; do
[[ -e "$service" ]] || continue
unit="$(basename "$service")"
systemctl disable --now "$unit" 2>/dev/null || true
rm -f "$service"
done
rm -f \
/etc/systemd/system/wgtools.service \
/etc/systemd/system/wgtools-telegram.service \
/etc/systemd/system/wgtools-expiry.service \
/etc/systemd/system/wgtools-expiry.timer \
/etc/systemd/system/wgtools-certbot-renew.service \
/etc/systemd/system/wgtools-certbot-renew.timer \
/etc/sudoers.d/wgtools \
/usr/local/libexec/wgtools-helper \
/usr/local/libexec/wgtools-certbot-reload \
/usr/local/bin/wgtools
rm -rf /opt/wgtools /etc/wgtools
systemctl daemon-reload
systemctl reset-failed >/dev/null 2>&1 || true
cat <<'TXT'
WGTools removed.
Preserved intentionally:
/var/lib/wgtools WGTools users, settings, keys/metadata and backups
/etc/wireguard Normal WireGuard configuration (internal wgnode0 removed)
/etc/letsencrypt Let's Encrypt certificates
WireGuard packages and normal wg-quick services
Remote VPS Relay Agent/tenants
Reinstalling WGTools can reuse the preserved state.
For a destructive wipe of this host, use the "FULL CLEANUP" action from the
wgtools menu before uninstalling, or run /opt/wgtools/scripts/full-clean.sh
while WGTools is still installed.
TXT
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
/bin/systemctl try-restart wgtools.service
+783
View File
@@ -0,0 +1,783 @@
#!/usr/bin/env bash
set -u
APP_DIR=/opt/wgtools
WG_ENV=/etc/wgtools/wgtools.env
HTTPS_ENV=/etc/wgtools/https.env
HTTPS_STATE=/etc/wgtools/https.json
VERSION_FILE="$APP_DIR/VERSION"
DATABASE_PATH="${WGTOOLS_DB:-/var/lib/wgtools/wgtools.db}"
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
echo "Run wgtools as root (or with sudo)." >&2
exit 1
fi
# shellcheck disable=SC1090
[[ -r "$WG_ENV" ]] && source "$WG_ENV"
# shellcheck disable=SC1090
[[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"
WG_INTERFACE="${WGTOOLS_INTERFACE:-wg0}"
NODE_INTERFACE="wgnode0"
HTTP_PORT="${WGTOOLS_PORT:-8341}"
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}"
VERSION="$(cat "$VERSION_FILE" 2>/dev/null || echo unknown)"
if [[ -t 1 ]]; then
BOLD='\033[1m'; DIM='\033[2m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; CYAN='\033[36m'; HEADER_RED='\033[38;5;124m'; RESET='\033[0m'
else
BOLD=''; DIM=''; GREEN=''; YELLOW=''; RED=''; CYAN=''; HEADER_RED=''; RESET=''
fi
service_state_raw() {
local unit="$1"
if systemctl is-active --quiet "$unit" 2>/dev/null; then
printf 'Running'
elif systemctl is-failed --quiet "$unit" 2>/dev/null; then
printf 'Failed'
else
printf 'Stopped'
fi
}
timer_state_raw() {
local unit="$1"
if systemctl is-active --quiet "$unit" 2>/dev/null; then
printf 'Active'
else
printf 'Inactive'
fi
}
state_color() {
case "$1" in
Running|Active|Enabled*) printf '%b' "$GREEN" ;;
Failed) printf '%b' "$RED" ;;
Stopped|Inactive|Disabled|"Not configured"|"Not installed") printf '%b' "$YELLOW" ;;
*) printf '%b' "$RESET" ;;
esac
}
https_target() {
python3 - "$HTTPS_STATE" <<'PY' 2>/dev/null || true
import json,sys
from pathlib import Path
p=Path(sys.argv[1])
try:
data=json.loads(p.read_text(encoding='utf-8'))
print(str(data.get('target') or '').strip())
except Exception:
pass
PY
}
primary_ip() {
hostname -I 2>/dev/null | awk '{print $1}'
}
panel_url() {
local host path
if [[ "$HTTPS_ENABLED" == "1" ]]; then
host="$(https_target)"
[[ -z "$host" ]] && host="$(primary_ip)"
[[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]"
path="$ACCESS_PATH"
[[ -n "$path" && "$path" != /* ]] && path="/$path"
[[ -n "$path" && "$path" != */ ]] && path="$path/"
if [[ "$HTTPS_PORT" == "443" ]]; then
printf 'https://%s%s' "$host" "$path"
else
printf 'https://%s:%s%s' "$host" "$HTTPS_PORT" "$path"
fi
else
host="$(primary_ip)"
[[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]"
printf 'http://%s:%s/' "$host" "$HTTP_PORT"
fi
}
wireguard_interfaces() {
{
if [[ -d /etc/wireguard ]]; then
for path in /etc/wireguard/*.conf; do
[[ -e "$path" ]] || continue
basename "$path" .conf
done
fi
wg show interfaces 2>/dev/null | tr ' ' '\n' || true
} | awk 'NF && $0 !~ /^wgrly/ && $0 !~ /^wgnode/ {print}' | sort -u
}
wg_state_for_raw() {
local iface="$1"
if wg show "$iface" >/dev/null 2>&1; then
printf 'Running'
elif [[ -f "/etc/wireguard/${iface}.conf" ]]; then
printf 'Stopped'
else
printf 'Not configured'
fi
}
node_state_raw() {
if wg show "$NODE_INTERFACE" >/dev/null 2>&1; then
printf 'Running'
elif [[ -f "/etc/wireguard/${NODE_INTERFACE}.conf" ]]; then
printf 'Stopped'
else
printf 'Not configured'
fi
}
relay_agent_state_raw() {
if systemctl is-active --quiet wgtools-relay-agent.service 2>/dev/null; then
printf 'Running'
elif [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then
printf 'Stopped'
else
printf 'Not installed'
fi
}
cert_expiry() {
local cert=/etc/letsencrypt/live/wgtools/fullchain.pem
[[ -r "$cert" ]] || { printf '—'; return; }
openssl x509 -in "$cert" -noout -enddate 2>/dev/null | sed 's/^notAfter=//' || printf '—'
}
print_row() {
local label="$1" value="$2" color="${3:-$RESET}"
printf '│ %-22s │ %b%-38s%b │\n' "$label" "$color" "$value" "$RESET"
}
print_status() {
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-$HTTPS_ENABLED}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-$HTTPS_PORT}"
ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-$ACCESS_PATH}"
[[ -t 1 ]] && printf '\033c' 2>/dev/null || true
printf '┌─────────────────────────────────────────────────────────────────┐\n'
printf '│ %bWGTools Management%b - v%-41s │\n' "$BOLD" "$RESET" "$VERSION"
printf '├────────────────────────┬────────────────────────────────────────┤\n'
local value color iface
value="$(service_state_raw wgtools.service)"; color="$(state_color "$value")"; print_row 'Panel service' "$value" "$color"
mapfile -t wg_ifaces < <(wireguard_interfaces)
if [[ ${#wg_ifaces[@]} -eq 0 ]]; then
value='Not configured'; color="$(state_color "$value")"; print_row 'WireGuard' "$value" "$color"
else
for iface in "${wg_ifaces[@]}"; do
value="$(wg_state_for_raw "$iface")"; color="$(state_color "$value")"; print_row "WireGuard $iface" "$value" "$color"
done
fi
value="$(node_state_raw)"; color="$(state_color "$value")"; print_row 'Nodes tunnel' "$value" "$color"
value="$(service_state_raw wgtools-telegram.service)"; color="$(state_color "$value")"; print_row 'Telegram service' "$value" "$color"
value="$(timer_state_raw wgtools-expiry.timer)"; color="$(state_color "$value")"; print_row 'Expiry timer' "$value" "$color"
if [[ "$HTTPS_ENABLED" == "1" ]]; then
value="Enabled - TCP $HTTPS_PORT"; print_row 'HTTPS' "$value" "$GREEN"
value="$(timer_state_raw wgtools-certbot-renew.timer)"; color="$(state_color "$value")"; print_row 'Renewal timer' "$value" "$color"
print_row 'Panel path' "${ACCESS_PATH:-—}" "$CYAN"
print_row 'Certificate until' "$(cert_expiry)" "$RESET"
else
print_row 'HTTPS' 'Disabled' "$YELLOW"
fi
if [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then
value="$(relay_agent_state_raw)"; color="$(state_color "$value")"; print_row 'Relay agent (local)' "$value" "$color"
fi
printf '└────────────────────────┴────────────────────────────────────────┘\n'
printf '%bPanel URL:%b %b%s%b\n' "$BOLD" "$RESET" "$CYAN" "$(panel_url)" "$RESET"
}
format_age() {
local epoch="${1:-0}" now delta
[[ "$epoch" =~ ^[0-9]+$ ]] || { printf 'never'; return; }
(( epoch > 0 )) || { printf 'never'; return; }
now="$(date +%s)"
delta=$(( now - epoch ))
(( delta < 0 )) && delta=0
if (( delta < 60 )); then
printf '%ss ago' "$delta"
elif (( delta < 3600 )); then
printf '%sm ago' "$((delta / 60))"
elif (( delta < 86400 )); then
printf '%sh ago' "$((delta / 3600))"
else
printf '%sd ago' "$((delta / 86400))"
fi
}
online_threshold_seconds() {
python3 - "$DATABASE_PATH" "${WGTOOLS_ONLINE_THRESHOLD_SECONDS:-180}" <<'PYTHRESH' 2>/dev/null || printf '180'
import sqlite3, sys
path, default = sys.argv[1], sys.argv[2]
try:
fallback = max(30, min(int(default), 3600))
except Exception:
fallback = 180
try:
conn = sqlite3.connect(path)
row = conn.execute("SELECT value FROM app_settings WHERE key='online_threshold_seconds'").fetchone()
conn.close()
value = int(row[0]) if row else fallback
print(max(30, min(value, 3600)))
except Exception:
print(fallback)
PYTHRESH
}
show_wireguard_status() {
local requested="${1:-}" iface snapshot threshold
mapfile -t interfaces < <(wireguard_interfaces)
if [[ -n "$requested" ]]; then
interfaces=("$requested")
fi
if [[ ${#interfaces[@]} -eq 0 ]]; then
echo "No WireGuard interfaces are configured."
return 1
fi
threshold="$(online_threshold_seconds)"
[[ "$threshold" =~ ^[0-9]+$ ]] || threshold=180
echo
printf '%bWireGuard status%b\n' "$BOLD" "$RESET"
for iface in "${interfaces[@]}"; do
if [[ ! -f "/etc/wireguard/${iface}.conf" ]] && ! wg show "$iface" >/dev/null 2>&1; then
printf '\n%s: Not found\n' "$iface"
continue
fi
snapshot=''
if [[ -x /usr/local/libexec/wgtools-helper ]]; then
snapshot="$(printf '%s\n' '{"view":"clients"}' | /usr/local/libexec/wgtools-helper snapshot "$iface" 2>/dev/null || true)"
fi
if [[ -n "$snapshot" ]]; then
python3 - "$iface" "$threshold" "$DATABASE_PATH" 3<<<"$snapshot" <<'PYSTATUS'
import json, sqlite3, sys, time
iface = sys.argv[1]
database_path = sys.argv[3]
try:
threshold = max(30, min(int(sys.argv[2]), 3600))
except Exception:
threshold = 180
try:
data = json.loads(open('/dev/fd/3', encoding='utf-8').read())
except Exception:
data = {}
if not isinstance(data, dict) or not data.get('ok'):
raise SystemExit(2)
now = int(time.time())
peers = list(data.get('peers') or [])
running = bool(data.get('running'))
config = data.get('config') or {}
interface = config.get('interface') or {}
address = str(interface.get('address') or '—')
port = data.get('listen_port') or interface.get('listen_port') or '—'
audit = {}
try:
conn = sqlite3.connect(database_path)
rows = conn.execute(
'SELECT public_key,latest_handshake,endpoint FROM audit_wg_connection_state WHERE interface=?',
(iface,),
).fetchall()
conn.close()
audit = {str(row[0]): {'latest_handshake': int(row[1] or 0), 'endpoint': str(row[2] or '')} for row in rows}
except Exception:
audit = {}
def handshake_epoch(peer):
try:
live = int(peer.get('latest_handshake') or 0)
except Exception:
live = 0
saved = audit.get(str(peer.get('public_key') or ''), {})
try:
historical = int(saved.get('latest_handshake') or 0)
except Exception:
historical = 0
return max(live, historical)
def peer_endpoint(peer):
value = str(peer.get('endpoint') or '').strip()
if value:
return value
return str(audit.get(str(peer.get('public_key') or ''), {}).get('endpoint') or '—')
def age(epoch):
try:
epoch = int(epoch or 0)
except Exception:
epoch = 0
if epoch <= 0:
return 'Never'
delta = max(0, now - epoch)
if delta < 60:
return f'{delta}s ago'
if delta < 3600:
return f'{delta // 60}m ago'
if delta < 86400:
return f'{delta // 3600}h ago'
return f'{delta // 86400}d ago'
def online(peer):
hs = handshake_epoch(peer)
return bool(running and hs > 0 and now - hs <= threshold)
def human_bytes(value):
try:
n = float(int(value or 0))
except Exception:
n = 0.0
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']
idx = 0
while n >= 1024 and idx < len(units) - 1:
n /= 1024.0
idx += 1
if idx == 0:
return f'{int(n)} {units[idx]}'
if n >= 100:
return f'{n:.0f} {units[idx]}'
if n >= 10:
return f'{n:.1f} {units[idx]}'
return f'{n:.2f} {units[idx]}'
def short_key(value):
value = str(value or '')
if len(value) <= 16:
return value or 'Unnamed peer'
return value[:8] + '…' + value[-6:]
def compact_bytes(value):
try:
n = float(int(value or 0))
except Exception:
n = 0.0
units = ['B', 'K', 'M', 'G', 'T']
idx = 0
while n >= 1024 and idx < len(units) - 1:
n /= 1024.0
idx += 1
if idx == 0:
return f'{int(n)}B'
if n >= 100:
return f'{n:.0f}{units[idx]}'
if n >= 10:
return f'{n:.1f}{units[idx]}'
return f'{n:.2f}{units[idx]}'
def fit(value, width, middle=False):
value = str(value or '-')
if len(value) <= width:
return value
if width <= 3:
return value[:width]
if middle:
right = min(6, max(2, width // 2))
left = width - right - 1
return value[:left] + '~' + value[-right:]
return value[:width - 1] + '~'
online_count = sum(1 for p in peers if online(p))
state = 'Running' if running else 'Stopped'
print()
print(f'{iface} {state} {address} UDP {port} Peers {len(peers)} ({online_count} online)')
if not peers:
print('Clients / peers: none configured')
raise SystemExit(0)
# Keep one peer per line, but do not shorten Endpoint: the terminal usually has
# more horizontal room than the boxed menu. Column widths adapt to current data.
rows = []
for peer in peers:
name = str(peer.get('name') or '').strip()
if not name or name.lower() == 'unnamed peer':
name = short_key(peer.get('public_key'))
allowed = list(peer.get('allowed_ips') or peer.get('allowed_ips_runtime') or [])
vpn_ip = str(peer.get('vpn_address') or (allowed[0] if allowed else '-'))
peer_state = 'Online' if online(peer) else 'Offline'
handshake = age(handshake_epoch(peer))
endpoint = peer_endpoint(peer)
if endpoint in {'—', '(none)', 'None', ''}:
endpoint = '-'
traffic = f"{compact_bytes(peer.get('rx_bytes'))}/{compact_bytes(peer.get('tx_bytes'))}"
rows.append((name, vpn_ip, peer_state, handshake, endpoint, traffic))
name_width = min(20, max([len('Name')] + [len(r[0]) for r in rows]))
vpn_width = max([len('VPN IP')] + [len(r[1]) for r in rows])
state_width = max([len('State')] + [len(r[2]) for r in rows])
handshake_width = max([len('Handshake')] + [len(r[3]) for r in rows])
endpoint_width = max([len('Endpoint')] + [len(r[4]) for r in rows])
traffic_width = max([len('RX/TX')] + [len(r[5]) for r in rows])
print()
print('Clients / peers')
header = (
f"{'Name':<{name_width}} "
f"{'VPN IP':<{vpn_width}} "
f"{'State':<{state_width}} "
f"{'Handshake':<{handshake_width}} "
f"{'Endpoint':<{endpoint_width}} "
f"{'RX/TX':<{traffic_width}}"
)
print(header)
print('-' * len(header))
for name, vpn_ip, peer_state, handshake, endpoint, traffic in rows:
print(
f"{fit(name, name_width):<{name_width}} "
f"{vpn_ip:<{vpn_width}} "
f"{peer_state:<{state_width}} "
f"{handshake:<{handshake_width}} "
f"{endpoint:<{endpoint_width}} "
f"{traffic:<{traffic_width}}"
)
PYSTATUS
rc=$?
[[ $rc -eq 0 ]] && continue
fi
# Fallback for a damaged/missing helper: still show live WireGuard data.
local state address port peers latest latest_text
state="$(wg_state_for_raw "$iface")"
address="$(ip -o -4 addr show dev "$iface" 2>/dev/null | awk '{print $4}' | paste -sd, -)"
[[ -n "$address" ]] || address='—'
if wg show "$iface" >/dev/null 2>&1; then
port="$(wg show "$iface" listen-port 2>/dev/null || true)"
[[ "$port" =~ ^[0-9]+$ ]] || port='—'
peers="$(wg show "$iface" peers 2>/dev/null | awk 'NF{n++} END{print n+0}')"
latest="$(wg show "$iface" latest-handshakes 2>/dev/null | awk '$2>m{m=$2} END{print m+0}')"
latest_text="$(format_age "$latest")"
else
port='—'; peers='0'; latest_text='—'
fi
printf '\nInterface: %s\n State: %s\n Address: %s\n Port: %s\n Peers: %s\n Latest handshake: %s\n' \
"$iface" "$state" "$address" "$port" "$peers" "$latest_text"
done
}
control_wireguard() {
local action="$1" requested="${2:-}" iface
mapfile -t interfaces < <(wireguard_interfaces)
if [[ -n "$requested" ]]; then
iface="$requested"
if [[ ! -f "/etc/wireguard/${iface}.conf" ]]; then
echo "WireGuard interface $iface is not configured."
return 1
fi
else
if [[ ${#interfaces[@]} -eq 0 ]]; then
echo "No WireGuard interfaces are configured."
return 1
elif [[ ${#interfaces[@]} -eq 1 ]]; then
iface="${interfaces[0]}"
elif [[ -f "/etc/wireguard/${WG_INTERFACE}.conf" ]]; then
iface="$WG_INTERFACE"
else
echo "Multiple WireGuard interfaces are configured: ${interfaces[*]}"
echo "Use: wgtools ${action}-wg <interface>"
return 1
fi
fi
case "$action" in
start|stop|restart) systemctl "$action" "wg-quick@${iface}.service" ;;
*) echo "Unsupported WireGuard action: $action" >&2; return 1 ;;
esac
}
menu_wireguard_action() {
local action="$1" selected
mapfile -t _wg_menu_ifaces < <(wireguard_interfaces)
if [[ ${#_wg_menu_ifaces[@]} -eq 0 ]]; then
echo "No WireGuard interfaces are configured."
return 1
fi
if [[ ${#_wg_menu_ifaces[@]} -eq 1 ]]; then
control_wireguard "$action" "${_wg_menu_ifaces[0]}"
return
fi
printf 'Interface [%s]: ' "${_wg_menu_ifaces[*]}"
read -r selected
[[ -n "$selected" ]] || { echo "Cancelled."; return 0; }
control_wireguard "$action" "$selected"
}
disable_https_rescue() {
if [[ "$HTTPS_ENABLED" != "1" ]]; then
echo "Built-in HTTPS is already disabled."
return 0
fi
printf 'Disable built-in HTTPS and restore HTTP on TCP %s? [y/N] ' "$HTTP_PORT"
read -r answer
[[ "$answer" =~ ^[Yy]$ ]] || return 0
if [[ -x /usr/local/libexec/wgtools-helper ]]; then
/usr/local/libexec/wgtools-helper https_disable "$WG_INTERFACE" >/tmp/wgtools-cli-https.json 2>/tmp/wgtools-cli-https.err || {
cat /tmp/wgtools-cli-https.err >&2 || true
rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err
return 1
}
rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err
sleep 6
# shellcheck disable=SC1090
[[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
echo "HTTP restored: $(panel_url)"
else
echo "WGTools helper is not installed." >&2
return 1
fi
}
mfa_enabled_users() {
python3 - "$DATABASE_PATH" <<'PYMFAUSERS' 2>/dev/null || true
import sqlite3, sys
path=sys.argv[1]
try:
conn=sqlite3.connect(path)
cols={row[1] for row in conn.execute("PRAGMA table_info(users)")}
if "mfa_enabled" not in cols:
raise SystemExit(0)
for row in conn.execute("SELECT username FROM users WHERE mfa_enabled=1 ORDER BY username COLLATE NOCASE"):
print(str(row[0]))
except Exception:
pass
PYMFAUSERS
}
disable_mfa_cli() {
local requested="${1:-}" selected answer i
mapfile -t _mfa_users < <(mfa_enabled_users)
if [[ ${#_mfa_users[@]} -eq 0 ]]; then
echo "MFA is not enabled for any WGTools user."
return 0
fi
if [[ -n "$requested" ]]; then
selected=''
for i in "${_mfa_users[@]}"; do
if [[ "${i,,}" == "${requested,,}" ]]; then selected="$i"; break; fi
done
if [[ -z "$selected" ]]; then
echo "MFA-enabled user not found: $requested" >&2
return 1
fi
elif [[ ${#_mfa_users[@]} -eq 1 ]]; then
selected="${_mfa_users[0]}"
else
echo "MFA-enabled users:"
for i in "${!_mfa_users[@]}"; do printf ' %d. %s\n' "$((i+1))" "${_mfa_users[$i]}"; done
printf 'Select user [1-%d]: ' "${#_mfa_users[@]}"
read -r answer
[[ "$answer" =~ ^[0-9]+$ ]] || { echo "Cancelled."; return 0; }
(( answer >= 1 && answer <= ${#_mfa_users[@]} )) || { echo "Cancelled."; return 0; }
selected="${_mfa_users[$((answer-1))]}"
fi
printf 'Disable MFA for %b%s%b? This invalidates existing sessions. [y/N] ' "$BOLD" "$selected" "$RESET"
read -r answer
[[ "$answer" =~ ^[Yy]$ ]] || { echo "Cancelled."; return 0; }
python3 - "$DATABASE_PATH" "$selected" <<'PYMFADISABLE'
import json, sqlite3, sys, time
path, username = sys.argv[1], sys.argv[2]
conn=sqlite3.connect(path)
try:
cols={row[1] for row in conn.execute("PRAGMA table_info(users)")}
required={"mfa_enabled","mfa_secret","mfa_recovery_codes","mfa_confirmed_at","session_version"}
if not required.issubset(cols):
raise SystemExit("This WGTools database does not support MFA.")
row=conn.execute("SELECT id,mfa_enabled FROM users WHERE username=? COLLATE NOCASE",(username,)).fetchone()
if not row:
raise SystemExit("User not found.")
if not int(row[1] or 0):
print("MFA is already disabled.")
raise SystemExit(0)
conn.execute(
"UPDATE users SET mfa_enabled=0,mfa_secret='',mfa_recovery_codes='[]',mfa_confirmed_at=0,session_version=session_version+1 WHERE id=?",
(int(row[0]),),
)
audit_exists=conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='audit_log'").fetchone()
if audit_exists:
conn.execute(
"INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)",
(int(time.time()),"root-cli","user.mfa_disabled_cli",username,"disabled",json.dumps({"reason":"root CLI rescue"},separators=(",",":"))),
)
conn.commit()
print(f"MFA disabled for {username}. Existing web sessions were invalidated.")
finally:
conn.close()
PYMFADISABLE
}
show_logs() {
echo "Press Ctrl+C to return."
journalctl -u wgtools.service -f --no-pager
}
show_bot_logs() {
echo "Press Ctrl+C to return."
journalctl -u wgtools-telegram.service -f --no-pager
}
uninstall_wgtools() {
echo
printf '%bUninstall WGTools from this host?%b\n' "$YELLOW" "$RESET"
cat <<'TXT'
This removes the WGTools application, web/Telegram/timer services, CLI,
internal Nodes tunnel and local Relay-home transport services.
Preserved intentionally:
• normal WireGuard interfaces/configs and packages
• /var/lib/wgtools (database, backups and reusable state)
• Let's Encrypt certificates
• Relay Agents/tenants on other VPS hosts
TXT
printf '\nType %bUNINSTALL%b to continue: ' "$BOLD" "$RESET"
read -r answer
[[ "$answer" == "UNINSTALL" ]] || { echo "Cancelled."; return 0; }
if [[ -x "$APP_DIR/scripts/uninstall.sh" ]]; then
bash "$APP_DIR/scripts/uninstall.sh"
else
echo "Uninstall script was not found: $APP_DIR/scripts/uninstall.sh" >&2
return 1
fi
exit 0
}
full_cleanup() {
echo
printf '%bFULL CLEANUP — destructive operation%b\n' "$RED$BOLD" "$RESET"
cat <<'TXT'
This wipes this host's WGTools installation completely:
• WGTools application, services, database, backups and CLI
• Nodes and local Relay Agent/tenant state on THIS host
• all WireGuard interfaces and /etc/wireguard configs on THIS host
• WGTools Let's Encrypt certificate
• Debian wireguard / wireguard-tools packages
Remote Relay Agents on OTHER VPS hosts are not contacted or deleted.
Generic shared OS tools such as iproute2, iptables, Python and certbot are kept.
TXT
printf '\nType %bDELETE ALL%b to continue: ' "$RED$BOLD" "$RESET"
read -r answer
[[ "$answer" == "DELETE ALL" ]] || { echo "Cancelled."; return 0; }
if [[ -x "$APP_DIR/scripts/full-clean.sh" ]]; then
WGTOOLS_FULL_CLEAN_CONFIRMED=1 bash "$APP_DIR/scripts/full-clean.sh"
else
echo "Full cleanup script was not found: $APP_DIR/scripts/full-clean.sh" >&2
return 1
fi
exit 0
}
run_action() {
case "${1:-}" in
status) print_status ;;
start) systemctl start wgtools.service ;;
stop) systemctl stop wgtools.service ;;
restart) systemctl restart wgtools.service ;;
status-wg) show_wireguard_status "${2:-}" ;;
start-wg) control_wireguard start "${2:-}" ;;
stop-wg) control_wireguard stop "${2:-}" ;;
restart-wg) control_wireguard restart "${2:-}" ;;
logs) journalctl -u wgtools.service -n 80 --no-pager ;;
bot-logs) journalctl -u wgtools-telegram.service -n 80 --no-pager ;;
http-rescue) disable_https_rescue ;;
disable-mfa) disable_mfa_cli "${2:-}" ;;
uninstall) uninstall_wgtools ;;
full-clean) full_cleanup ;;
*) return 2 ;;
esac
}
if [[ $# -gt 0 ]]; then
run_action "$@" || {
rc=$?
if [[ $rc -eq 2 ]]; then
echo "Usage: wgtools [status|start|stop|restart|status-wg [interface]|start-wg [interface]|stop-wg [interface]|restart-wg [interface]|logs|bot-logs|http-rescue|disable-mfa [username]|uninstall|full-clean]" >&2
fi
exit "$rc"
}
exit 0
fi
while true; do
# Reload mutable HTTPS settings on each pass.
unset WGTOOLS_HTTPS_ENABLED WGTOOLS_HTTPS_PORT WGTOOLS_ACCESS_PATH 2>/dev/null || true
# shellcheck disable=SC1090
[[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}"
print_status
printf '\n┌─────────────────────────────────────────────────────────────────┐\n'
printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Panel' "$RESET"
printf '│ %-63s │\n' ' 1. Refresh status'
printf '│ %-63s │\n' ' 2. Start'
printf '│ %-63s │\n' ' 3. Stop'
printf '│ %-63s │\n' ' 4. Restart'
printf '├─────────────────────────────────────────────────────────────────┤\n'
printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'WireGuard' "$RESET"
printf '│ %-63s │\n' ' 5. Status'
printf '│ %-63s │\n' ' 6. Start'
printf '│ %-63s │\n' ' 7. Stop'
printf '│ %-63s │\n' ' 8. Restart'
printf '├─────────────────────────────────────────────────────────────────┤\n'
printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Logs & recovery' "$RESET"
printf '│ %-63s │\n' ' 9. WGTools logs'
printf '│ %-63s │\n' '10. Telegram logs'
printf '│ %-63s │\n' '11. Restore HTTP access (disable built-in HTTPS)'
printf '├─────────────────────────────────────────────────────────────────┤\n'
printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Security' "$RESET"
printf '│ %-63s │\n' '12. Disable user MFA (emergency rescue)'
printf '├─────────────────────────────────────────────────────────────────┤\n'
printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Removal' "$RESET"
printf '│ %-63s │\n' '13. Uninstall WGTools (keep WireGuard + reusable data)'
printf '│ %-63s │\n' '14. FULL CLEANUP (WGTools + WireGuard + Relay + all data)'
printf '├─────────────────────────────────────────────────────────────────┤\n'
printf '│ %-63s │\n' ' 0. Exit'
printf '└─────────────────────────────────────────────────────────────────┘\n'
printf '\nSelect [0-14]: '
read -r choice || exit 0
case "$choice" in
1) ;;
2) systemctl start wgtools.service; sleep 1 ;;
3) systemctl stop wgtools.service; sleep 1 ;;
4) systemctl restart wgtools.service; sleep 1 ;;
5) show_wireguard_status || true; printf '\nPress Enter to continue...'; read -r _ ;;
6) menu_wireguard_action start || true; sleep 1 ;;
7) menu_wireguard_action stop || true; sleep 1 ;;
8) menu_wireguard_action restart || true; sleep 1 ;;
9) show_logs || true ;;
10) show_bot_logs || true ;;
11) disable_https_rescue || true; printf '\nPress Enter to continue...'; read -r _ ;;
12) disable_mfa_cli || true; printf '\nPress Enter to continue...'; read -r _ ;;
13) uninstall_wgtools || true; printf '\nPress Enter to continue...'; read -r _ ;;
14) full_cleanup || true; printf '\nPress Enter to continue...'; read -r _ ;;
0) exit 0 ;;
*) printf 'Unknown selection.\n'; sleep 1 ;;
esac
done
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
APP_DIR=/opt/wgtools
UVICORN="$APP_DIR/.venv/bin/uvicorn"
HTTP_PORT="${WGTOOLS_PORT:-8341}"
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
CERT_FILE="${WGTOOLS_SSL_CERTFILE:-/etc/letsencrypt/live/wgtools/fullchain.pem}"
KEY_FILE="${WGTOOLS_SSL_KEYFILE:-/etc/letsencrypt/live/wgtools/privkey.pem}"
args=(app.main:application --host 0.0.0.0 --workers 1)
if [[ "$HTTPS_ENABLED" == "1" ]]; then
if [[ ! -r "$CERT_FILE" || ! -r "$KEY_FILE" ]]; then
echo "WGTools HTTPS is enabled but certificate files are not readable:" >&2
echo " cert: $CERT_FILE" >&2
echo " key: $KEY_FILE" >&2
exit 1
fi
args+=(--port "$HTTPS_PORT" --ssl-certfile "$CERT_FILE" --ssl-keyfile "$KEY_FILE")
else
args+=(--port "$HTTP_PORT")
fi
exec "$UVICORN" "${args[@]}"