This commit is contained in:
eric 2026-06-07 00:34:55 -05:00
parent 4bf39e3314
commit e091e20ec8
14 changed files with 283 additions and 10 deletions

View File

@ -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

View File

@ -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@<iface>.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
```

View File

@ -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

View File

@ -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

View File

@ -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 <<UNIT
[Unit]
Description=Live WireGuard keepalive watcher
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=$ROOT_DIR
Environment=LIVE_STACK_ROOT=$ROOT_DIR
ExecStart=/bin/bash $ROOT_DIR/scripts/linux/wireguard_watch.sh
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now 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 <<SUDOERS

View File

@ -17,6 +17,8 @@ install_live_console_service
ensure_runtime_dirs_owned_by_live
log "Rewriting /etc/systemd/system/live-neko-ip-watch.service from repo"
install_neko_ip_watch_service
log "Rewriting /etc/systemd/system/live-wireguard-watch.service from repo"
install_wireguard_watch_service
log "Rewriting /etc/systemd/system/live-frigate-usb-watch.service from repo"
install_frigate_usb_watch_service
log "Done. Check: systemctl status live-console.service --no-pager"

View File

@ -9,7 +9,7 @@ ensure_root "$@"
load_env
log "Stopping systemd services"
for svc in live-edge-watch.service live-edge.service live-console.service live-neko-ip-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service live-kmscube.service live-redroid-host.service netdata cockpit.socket shellcrash.service avahi-daemon; do
for svc in live-edge-watch.service live-edge.service live-console.service live-neko-ip-watch.service live-wireguard-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service live-kmscube.service live-redroid-host.service netdata cockpit.socket shellcrash.service avahi-daemon; do
systemctl stop "$svc" >/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

View File

@ -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

View File

@ -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 "$@"

View File

@ -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)

View File

@ -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))

View File

@ -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;

View File

@ -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({
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
disabled={lock}
disabled={laneSaving}
title={urlSaveBlockedReason || undefined}
onClick={() => void saveProUrlAndServer()}
className="rounded-xl bg-cyan-500/20 px-4 py-2 text-sm text-cyan-100 ring-1 ring-cyan-500/30"
>
@ -3244,7 +3268,8 @@ export function LiveYoutubeUnmannedView({
/>
<button
type="button"
disabled={lock}
disabled={laneSaving}
title={urlSaveBlockedReason || undefined}
onClick={() => void saveSingleUrlAndClearDirty()}
className="mt-3 rounded-xl bg-cyan-500/20 px-4 py-2 text-sm text-cyan-100 ring-1 ring-cyan-500/30"
>

View File

@ -1674,7 +1674,7 @@ async def save_url_config(request: Request, process: str = Query(..., descriptio
rel = managed_url_config_relpath(process)
governed_save_managed_file("app-config", rel, content)
_persist_youtube_pro_channel_edits(process, url_content=content)
return JSONResponse({"message": "配置保存成功"}, headers=_NO_STORE_HEADERS)
return JSONResponse({"message": "配置保存成功", "path": rel, "process": process}, headers=_NO_STORE_HEADERS)
except sqlite3.Error as e:
return JSONResponse({"error": _youtube_pro_store_error(e)}, status_code=500)
except OSError as e: