From e091e20ec89f4f63ae3a9f3bad325a954ac9c6dc Mon Sep 17 00:00:00 2001 From: eric Date: Sun, 7 Jun 2026 00:34:55 -0500 Subject: [PATCH] 's' --- d2ypp2/config/system-stack.env.example | 6 + d2ypp2/docs/wg-easy-operations.md | 18 +++ d2ypp2/scripts/linux/install_all.sh | 1 + d2ypp2/scripts/linux/install_hub.sh | 1 + d2ypp2/scripts/linux/lib/common.sh | 31 +++++ .../linux/refresh_live_console_unit.sh | 2 + d2ypp2/scripts/linux/uninstall_stack.sh | 3 +- d2ypp2/scripts/linux/upgrade_live_console.sh | 2 + d2ypp2/scripts/linux/wireguard_watch.sh | 107 ++++++++++++++++++ d2ypp2/src/wireguard_config.py | 58 +++++++++- d2ypp2/tests/test_wireguard_config.py | 22 ++++ .../live-product/LiveControlApp.tsx | 9 +- .../live-product/LiveYoutubeUnmannedView.tsx | 31 ++++- d2ypp2/web.py | 2 +- 14 files changed, 283 insertions(+), 10 deletions(-) create mode 100644 d2ypp2/scripts/linux/wireguard_watch.sh diff --git a/d2ypp2/config/system-stack.env.example b/d2ypp2/config/system-stack.env.example index bd714db..26e72f9 100644 --- a/d2ypp2/config/system-stack.env.example +++ b/d2ypp2/config/system-stack.env.example @@ -42,6 +42,12 @@ NETWORK_PROBE_GOOGLE_URL=https://www.google.com/generate_204 NETWORK_PROBE_YOUTUBE_URL=https://www.youtube.com/generate_204 NETWORK_PROBE_DOUYIN_URL=https://live.douyin.com/ +# WireGuard client watchdog: PersistentKeepalive should keep NAT bindings fresh, but some kernels/NICs can wedge. +ENABLE_WIREGUARD_WATCH=1 +WIREGUARD_WATCH_INTERVAL=30 +WIREGUARD_STALE_SECONDS=300 +WIREGUARD_RESTART_COOLDOWN=300 + # Browser / Android lab BROWSER_PROFILE_DIR=/var/lib/live-browser/profile BROWSER_START_URL=https://www.tiktok.com/live diff --git a/d2ypp2/docs/wg-easy-operations.md b/d2ypp2/docs/wg-easy-operations.md index 927b9b2..adee55c 100644 --- a/d2ypp2/docs/wg-easy-operations.md +++ b/d2ypp2/docs/wg-easy-operations.md @@ -80,3 +80,21 @@ NEKO_WEBRTC_UDPMUX=52301 - 页面会生成 Windows Endpoint 旁路路由模板。 导入功能只做解析和保存,不直接执行系统级 `wg-quick` 或 Windows 隧道安装命令,避免从 Web 表单执行未审计的网络配置。 +## WireGuard Client Watchdog + +NAT-side clients must keep: + +```ini +PersistentKeepalive = 25 +``` + +The console now normalizes imported WireGuard configs and adds that value for endpoint peers when it is missing. Deployed hubs also install `live-wireguard-watch.service`; it checks keepalive-enabled `wg-quick` interfaces every `WIREGUARD_WATCH_INTERVAL=30` seconds and restarts `wg-quick@.service` when the latest handshake is older than `WIREGUARD_STALE_SECONDS=300`. + +This handles the failure mode where `wg-quick@...` is still active but the runtime tunnel stops refreshing handshakes. Configure it in `config/system-stack.env`: + +```env +ENABLE_WIREGUARD_WATCH=1 +WIREGUARD_WATCH_INTERVAL=30 +WIREGUARD_STALE_SECONDS=300 +WIREGUARD_RESTART_COOLDOWN=300 +``` diff --git a/d2ypp2/scripts/linux/install_all.sh b/d2ypp2/scripts/linux/install_all.sh index 7baa8f8..758ab03 100644 --- a/d2ypp2/scripts/linux/install_all.sh +++ b/d2ypp2/scripts/linux/install_all.sh @@ -27,6 +27,7 @@ install_shellcrash install_browser_stack install_neko_browser install_neko_ip_watch_service +install_wireguard_watch_service install_redroid prepare_mitmproxy prepare_vscode_server diff --git a/d2ypp2/scripts/linux/install_hub.sh b/d2ypp2/scripts/linux/install_hub.sh index d38709a..e5ab6c8 100644 --- a/d2ypp2/scripts/linux/install_hub.sh +++ b/d2ypp2/scripts/linux/install_hub.sh @@ -30,6 +30,7 @@ install_shellcrash install_browser_stack install_neko_browser install_neko_ip_watch_service +install_wireguard_watch_service install_redroid prepare_mitmproxy prepare_vscode_server diff --git a/d2ypp2/scripts/linux/lib/common.sh b/d2ypp2/scripts/linux/lib/common.sh index aeb8d2d..248ad69 100644 --- a/d2ypp2/scripts/linux/lib/common.sh +++ b/d2ypp2/scripts/linux/lib/common.sh @@ -1332,6 +1332,37 @@ UNIT systemctl enable --now live-neko-ip-watch.service } +install_wireguard_watch_service() { + if [ "${ENABLE_WIREGUARD_WATCH:-1}" != "1" ]; then + systemctl disable --now live-wireguard-watch.service >/dev/null 2>&1 || true + rm -f /etc/systemd/system/live-wireguard-watch.service + systemctl daemon-reload + return 0 + fi + [ -f "$ROOT_DIR/scripts/linux/wireguard_watch.sh" ] || return 0 + log "Installing WireGuard keepalive watcher" + chmod +x "$ROOT_DIR/scripts/linux/wireguard_watch.sh" + cat >/etc/systemd/system/live-wireguard-watch.service </dev/null 2>&1 || true +} + configure_sudoers() { log "Configuring sudoers for live control plane" cat >/etc/sudoers.d/live-control-plane </dev/null 2>&1 || true systemctl disable "$svc" >/dev/null 2>&1 || true done @@ -44,6 +44,7 @@ rm -f /etc/systemd/system/live-edge.service rm -f /etc/systemd/system/live-edge-watch.service rm -f /etc/systemd/system/live-console.service rm -f /etc/systemd/system/live-neko-ip-watch.service +rm -f /etc/systemd/system/live-wireguard-watch.service rm -f /etc/systemd/system/live-webtty.service rm -f /etc/systemd/system/live-android-panel.service rm -f /etc/systemd/system/live-pulseaudio.service diff --git a/d2ypp2/scripts/linux/upgrade_live_console.sh b/d2ypp2/scripts/linux/upgrade_live_console.sh index e2c80be..9eca214 100644 --- a/d2ypp2/scripts/linux/upgrade_live_console.sh +++ b/d2ypp2/scripts/linux/upgrade_live_console.sh @@ -22,6 +22,8 @@ prepare_web_console log "Refreshing Neko LAN IP watcher unit" install_neko_ip_watch_service +log "Refreshing WireGuard keepalive watcher unit" +install_wireguard_watch_service log "Restarting live-console.service" systemctl daemon-reload diff --git a/d2ypp2/scripts/linux/wireguard_watch.sh b/d2ypp2/scripts/linux/wireguard_watch.sh new file mode 100644 index 0000000..8125071 --- /dev/null +++ b/d2ypp2/scripts/linux/wireguard_watch.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Restart stale WireGuard client interfaces so NAT keepalive does not silently die. +set -euo pipefail + +ROOT_DIR="${LIVE_STACK_ROOT:-/opt/live/d2ypp}" +STACK_ENV="${LIVE_STACK_ENV:-$ROOT_DIR/config/system-stack.env}" + +log() { + printf '[wireguard-watch] %s\n' "$*" +} + +positive_int() { + case "${1:-}" in + ''|*[!0-9]*) return 1 ;; + *) [ "$1" -gt 0 ] ;; + esac +} + +reload_env() { + if [ -f "$STACK_ENV" ]; then + set -a + # shellcheck source=/dev/null + . "$STACK_ENV" || true + set +a + fi + WIREGUARD_WATCH_INTERVAL="${WIREGUARD_WATCH_INTERVAL:-30}" + WIREGUARD_STALE_SECONDS="${WIREGUARD_STALE_SECONDS:-300}" + WIREGUARD_RESTART_COOLDOWN="${WIREGUARD_RESTART_COOLDOWN:-300}" + positive_int "$WIREGUARD_WATCH_INTERVAL" || WIREGUARD_WATCH_INTERVAL=30 + positive_int "$WIREGUARD_STALE_SECONDS" || WIREGUARD_STALE_SECONDS=300 + positive_int "$WIREGUARD_RESTART_COOLDOWN" || WIREGUARD_RESTART_COOLDOWN=300 + [ "$WIREGUARD_WATCH_INTERVAL" -lt 10 ] && WIREGUARD_WATCH_INTERVAL=10 + [ "$WIREGUARD_STALE_SECONDS" -lt 60 ] && WIREGUARD_STALE_SECONDS=60 + [ "$WIREGUARD_RESTART_COOLDOWN" -lt "$WIREGUARD_STALE_SECONDS" ] && WIREGUARD_RESTART_COOLDOWN="$WIREGUARD_STALE_SECONDS" + return 0 +} + +interface_has_keepalive_peer() { + local iface="$1" + wg show "$iface" dump 2>/dev/null | awk ' + NR > 1 { + ka = $9 + if (ka != "" && ka != "off" && ka != "0") found = 1 + } + END { exit found ? 0 : 1 } + ' +} + +interface_is_stale() { + local iface="$1" now="$2" stale="$3" + wg show "$iface" dump 2>/dev/null | awk -v now="$now" -v stale="$stale" ' + NR > 1 { + latest = $6 + ka = $9 + if (ka != "" && ka != "off" && ka != "0" && (latest == 0 || now - latest > stale)) bad = 1 + } + END { exit bad ? 0 : 1 } + ' +} + +restart_interface() { + local iface="$1" + if systemctl list-unit-files "wg-quick@${iface}.service" --no-legend 2>/dev/null | grep -q .; then + systemctl restart "wg-quick@${iface}.service" + elif systemctl list-units "wg-quick@${iface}.service" --no-legend 2>/dev/null | grep -q .; then + systemctl restart "wg-quick@${iface}.service" + else + log "WARN: $iface is stale but wg-quick@${iface}.service is not installed" + return 1 + fi +} + +watch_once() { + local now iface last last_restart_var last_restart + command -v wg >/dev/null 2>&1 || return 0 + command -v systemctl >/dev/null 2>&1 || return 0 + now="$(date +%s)" + for iface in $(wg show interfaces 2>/dev/null || true); do + [ -n "$iface" ] || continue + interface_has_keepalive_peer "$iface" || continue + interface_is_stale "$iface" "$now" "$WIREGUARD_STALE_SECONDS" || continue + last_restart_var="/run/live-wireguard-watch-${iface}.last" + last_restart="$(cat "$last_restart_var" 2>/dev/null || echo 0)" + positive_int "$last_restart" || last_restart=0 + if [ $((now - last_restart)) -lt "$WIREGUARD_RESTART_COOLDOWN" ]; then + continue + fi + last="$(wg show "$iface" latest-handshakes 2>/dev/null | awk 'NR == 1 {print $2}')" + log "Restarting stale $iface; latest_handshake=${last:-0}; stale_seconds=$WIREGUARD_STALE_SECONDS" + if restart_interface "$iface"; then + date +%s >"$last_restart_var" + fi + done +} + +main() { + log "Watching WireGuard keepalive health" + while true; do + reload_env + if [ "${ENABLE_WIREGUARD_WATCH:-1}" = "1" ]; then + watch_once || true + fi + sleep "$WIREGUARD_WATCH_INTERVAL" + done +} + +main "$@" diff --git a/d2ypp2/src/wireguard_config.py b/d2ypp2/src/wireguard_config.py index 34e4b71..54dff10 100644 --- a/d2ypp2/src/wireguard_config.py +++ b/d2ypp2/src/wireguard_config.py @@ -293,7 +293,14 @@ def normalize_wireguard_overlay_config(content: str, *, name: str | None = None) warnings: list[str] = [] if not overlay_allowed: warnings.append("No private Interface Address was found; kept AllowedIPs unchanged") - return _normalized_config_text(content), {"changed": False, "allowed_ips": [], "warnings": warnings} + normalized, keepalive = normalize_wireguard_keepalive_config(content) + warnings.extend(keepalive.get("warnings") or []) + return normalized, { + "changed": bool(keepalive.get("changed")), + "allowed_ips": [], + "warnings": warnings, + "keepalive": keepalive, + } lines = _normalized_config_text(content).splitlines() next_lines: list[str] = [] @@ -367,6 +374,48 @@ def normalize_wireguard_overlay_config(content: str, *, name: str | None = None) return "\n".join(next_lines).strip() + "\n", {"changed": changed, "allowed_ips": overlay_allowed, "warnings": warnings} +def normalize_wireguard_keepalive_config(content: str) -> tuple[str, dict[str, Any]]: + lines = _normalized_config_text(content).splitlines() + next_lines: list[str] = [] + section = "" + peer_has_keepalive = False + peer_seen_endpoint = False + changed = False + added_keepalive = 0 + + def maybe_add_keepalive() -> None: + nonlocal added_keepalive, changed, peer_has_keepalive, peer_seen_endpoint + if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive: + next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}") + added_keepalive += 1 + changed = True + peer_has_keepalive = False + peer_seen_endpoint = False + + for raw in lines: + stripped = _strip_inline_comment(raw).strip() + if stripped.startswith("[") and stripped.endswith("]"): + maybe_add_keepalive() + section = stripped[1:-1].strip() + next_lines.append(raw) + continue + if "=" in stripped: + key, _, _value = stripped.partition("=") + key_l = key.strip().lower() + if section == "Peer": + if key_l == "endpoint": + peer_seen_endpoint = True + elif key_l == "persistentkeepalive": + peer_has_keepalive = True + next_lines.append(raw) + + maybe_add_keepalive() + warnings = [] + if added_keepalive: + warnings.append(f"Added PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS} to {added_keepalive} WireGuard peer(s)") + return "\n".join(next_lines).strip() + "\n", {"changed": changed, "added_keepalive": added_keepalive, "warnings": warnings} + + def _save_wireguard_summary(summary: dict[str, Any], target: Path) -> Path: summary_path = target.with_suffix(".summary.json") summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") @@ -385,7 +434,11 @@ def save_imported_wireguard_config( if route_mode == "overlay": normalized, overlay = normalize_wireguard_overlay_config(content, name=name) elif route_mode == "preserve": - normalized = _normalized_config_text(content) + normalized, keepalive = normalize_wireguard_keepalive_config(content) + if keepalive.get("warnings"): + overlay["warnings"] = [*overlay.get("warnings", []), *keepalive["warnings"]] + overlay["changed"] = bool(overlay.get("changed") or keepalive.get("changed")) + overlay["keepalive"] = keepalive else: raise WireGuardConfigError(f"Unsupported WireGuard route mode: {route_mode}") @@ -394,6 +447,7 @@ def save_imported_wireguard_config( summary["warnings"] = [*summary.get("warnings", []), *overlay["warnings"]] summary["route_mode"] = route_mode summary["overlay"] = overlay + summary["health"] = _wireguard_config_health(summary) safe_name = str(summary["name"]) target_dir = repo_root / "config" / "wireguard" / "imports" target_dir.mkdir(parents=True, exist_ok=True) diff --git a/d2ypp2/tests/test_wireguard_config.py b/d2ypp2/tests/test_wireguard_config.py index 14d58d5..bce339a 100644 --- a/d2ypp2/tests/test_wireguard_config.py +++ b/d2ypp2/tests/test_wireguard_config.py @@ -6,6 +6,7 @@ from unittest.mock import patch from src.wireguard_config import ( WireGuardConfigError, configure_neko_wireguard_access, + normalize_wireguard_keepalive_config, normalize_wireguard_overlay_config, parse_wireguard_config, save_imported_wireguard_config, @@ -53,6 +54,24 @@ class WireGuardConfigTests(unittest.TestCase): self.assertIn("route -p add 129.204.21.129", result["windows_route_template"]["powershell"]) self.assertTrue(Path(result["summary_path"]).is_file()) + def test_preserve_mode_adds_missing_keepalive(self) -> None: + no_keepalive = SAMPLE_WG.replace("PersistentKeepalive = 25\n", "") + with tempfile.TemporaryDirectory() as tmp: + result = save_imported_wireguard_config(no_keepalive, name="wg-vps", repo_root=Path(tmp)) + + saved = Path(result["path"]).read_text(encoding="utf-8") + self.assertIn("PersistentKeepalive = 25", saved) + self.assertEqual(result["health"]["missing_keepalive_peer_count"], 0) + self.assertTrue(result["overlay"]["keepalive"]["changed"]) + + def test_keepalive_normalizer_adds_only_endpoint_peers(self) -> None: + content = SAMPLE_WG.replace("PersistentKeepalive = 25\n", "") + "\n[Peer]\nPublicKey = DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD=\nAllowedIPs = 10.88.0.9/32\n" + + normalized, meta = normalize_wireguard_keepalive_config(content) + + self.assertEqual(normalized.count("PersistentKeepalive = 25"), 1) + self.assertTrue(meta["changed"]) + def test_invalid_endpoint_is_rejected(self) -> None: bad = SAMPLE_WG.replace("Endpoint = 129.204.21.129:51820", "Endpoint = 129.204.21.129:notaport") with self.assertRaises(WireGuardConfigError): @@ -111,6 +130,9 @@ class WireGuardConfigTests(unittest.TestCase): with patch("src.wireguard_config.shutil.which", return_value="/usr/bin/tool"), patch( "src.wireguard_config._run_command", side_effect=fake_run, + ), patch( + "src.wireguard_config._system_wireguard_configs", + return_value=[], ): status = wireguard_runtime_status(repo_root=Path(tmp)) diff --git a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx index 8981630..bb7e445 100644 --- a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx +++ b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx @@ -1176,13 +1176,16 @@ export default function LiveControlApp() { const saveUrlConfig = async (overrideContent?: string, processOverride?: string) => { const proc = (processOverride ?? currentProc).trim(); - if (!proc) return; + if (!proc) { + notify(t("请选择要保存地址的进程", "Pick a process before saving URLs")); + throw new Error(t("请选择要保存地址的进程", "Pick a process before saving URLs")); + } const content = overrideContent ?? urlConfig; const requestId = ++urlConfigRequestSeqRef.current; setBusy("save:url"); try { const params = new URLSearchParams({ process: proc }); - await fetchJson(`/save_url_config?${params}`, { + const data = await fetchJson<{ message?: string; path?: string }>(`/save_url_config?${params}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content }), @@ -1190,7 +1193,7 @@ export default function LiveControlApp() { if (requestId === urlConfigRequestSeqRef.current && proc === currentProcRef.current.trim()) { setUrlConfig(content); } - notify(t("URL 配置已保存", "URL config saved")); + notify(data.path ? t(`URL 配置已保存: ${data.path}`, `URL config saved: ${data.path}`) : t("URL 配置已保存", "URL config saved")); } catch (e) { notify((e as Error).message); throw e; diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx index 942ef9c..7139e5a 100644 --- a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx @@ -1530,7 +1530,17 @@ export function LiveYoutubeUnmannedView({ const keySuffixDisplay = keySuffixUi ? `…${keySuffixUi}` : "—"; const saveProUrlAndServer = async () => { - if (!active) return; + if (!active) { + const message = t("请选择线路后再保存地址", "Pick a lane before saving URLs"); + setLaneStatus(message); + notify(message); + return; + } + if (urlSaveBlockedReason) { + setLaneStatus(urlSaveBlockedReason); + notify(urlSaveBlockedReason); + return; + } try { setLaneSaving(true); setLaneStatus(null); @@ -1552,6 +1562,10 @@ export function LiveYoutubeUnmannedView({ }; const saveSingleUrlAndClearDirty = async () => { + if (urlSaveBlockedReason) { + notify(urlSaveBlockedReason); + return; + } const targetPm2 = currentProcRef.current.trim(); if (!targetPm2) { notify(t("请选择进程", "Pick a process")); @@ -1794,6 +1808,15 @@ export function LiveYoutubeUnmannedView({ const lock = !!busy || ytIniLoading || urlReloading || urlOptimizing || laneSaving; const proLaneActionLock = !!busy || laneSaving; + const urlSaveBlockedReason = ytIniLoading + ? t("正在读取 youtube.ini,稍后再保存地址", "youtube.ini is loading; save URLs after it finishes") + : urlReloading + ? t("正在重新读取地址列表,稍后再保存", "URL list is reloading; save after it finishes") + : urlOptimizing + ? t("正在整理地址列表,稍后再保存", "URL list is being optimized; save after it finishes") + : busy + ? t("正在执行其他操作,稍后再保存地址", "Another operation is running; save URLs after it finishes") + : ""; const singleRow = mode === "single" ? runtimeLogRow : currentProcRow; const singleOnline = pm2StatusOnline(statusForPm2(singleRuntimeProc)); @@ -3203,7 +3226,8 @@ export function LiveYoutubeUnmannedView({