douyinWEB/backend/app/singbox_manager.py
eric f7dc2b6b4e Add VPS static residential IP via isolated douyinweb-singbox.
US VPS can use egress_mode=residential (127.0.0.1:17891) without touching host sing-box.service / v2ray-agent; default remains datacenter direct.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 21:03:34 -05:00

286 lines
8.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""DouyinWEB-only sing-box: local mixed → residential SOCKS5.
HARD ISOLATION from v2ray-agent:
- Never systemctl start/stop/restart the host unit ``sing-box.service``
- Never read/write ``/etc/v2ray-agent/``
- Only manage ``douyinweb-singbox`` (systemd) or a subprocess with
``${APP}/config/sing-box.json`` listening on 127.0.0.1:17891
"""
from __future__ import annotations
import json
import os
import shutil
import signal
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import BACKEND
from .global_socks import (
CONFIG_DIR,
LOCAL_MIXED_HOST,
LOCAL_MIXED_PORT,
SINGBOX_CONFIG_PATH,
active_profile,
is_global_socks_enabled,
)
# App-owned unit only — NEVER bare "sing-box" (v2ray-agent).
UNIT_NAME = "douyinweb-singbox"
FORBIDDEN_UNITS = frozenset({"sing-box", "sing-box.service", "xray", "xray.service", "v2ray", "v2ray.service"})
V2RAY_AGENT_DIR = Path("/etc/v2ray-agent")
_PID_FILE = CONFIG_DIR / "sing-box.pid"
_LOG_PATH = CONFIG_DIR / "sing-box.log"
def _assert_safe_unit(name: str) -> str:
raw = str(name or "").strip()
base = raw.removesuffix(".service")
if raw in FORBIDDEN_UNITS or base in FORBIDDEN_UNITS or base == "sing-box":
raise RuntimeError(f"refusing to touch host unit {raw!r} (v2ray-agent / edge)")
if base != UNIT_NAME and raw != UNIT_NAME:
raise RuntimeError(f"only {UNIT_NAME} is allowed, got {raw!r}")
return UNIT_NAME
def _find_binary() -> str:
for name in ("sing-box", "/usr/bin/sing-box", "/usr/local/bin/sing-box"):
p = shutil.which(name) if not name.startswith("/") else (name if Path(name).is_file() else None)
if p and Path(p).is_file():
return str(p)
return ""
def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
if not profile:
raise ValueError("SOCKS 配置无效")
server = str(profile.get("server") or "").strip()
port = int(profile.get("port") or 0)
if not server or port <= 0:
raise ValueError("SOCKS 服务器或端口无效")
outbound: dict[str, Any] = {
"type": "socks",
"tag": "upstream",
"server": server,
"server_port": port,
"version": "5",
}
user = str(profile.get("username") or "").strip()
pwd = str(profile.get("password") or "")
if user:
outbound["username"] = user
if pwd:
outbound["password"] = pwd
return {
"log": {"level": "warn", "timestamp": True},
"inbounds": [
{
"type": "mixed",
"tag": "mixed-in",
"listen": LOCAL_MIXED_HOST,
"listen_port": LOCAL_MIXED_PORT,
"sniff": True,
}
],
"outbounds": [
outbound,
{"type": "direct", "tag": "direct"},
],
"route": {
"rules": [],
"final": "upstream",
},
}
def write_config(cfg_dict: dict[str, Any]) -> Path:
if V2RAY_AGENT_DIR in SINGBOX_CONFIG_PATH.parents or str(SINGBOX_CONFIG_PATH).startswith(
str(V2RAY_AGENT_DIR)
):
raise RuntimeError("refusing to write config under /etc/v2ray-agent")
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
SINGBOX_CONFIG_PATH.write_text(json.dumps(cfg_dict, ensure_ascii=False, indent=2), encoding="utf-8")
try:
os.chmod(SINGBOX_CONFIG_PATH, 0o600)
except Exception:
pass
return SINGBOX_CONFIG_PATH
def _read_pid() -> int:
try:
return int(_PID_FILE.read_text(encoding="utf-8").strip())
except Exception:
return 0
def _pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def is_running() -> bool:
pid = _read_pid()
if _pid_alive(pid):
return True
try:
r = subprocess.run(
["systemctl", "is-active", UNIT_NAME],
capture_output=True,
text=True,
timeout=5,
)
return r.returncode == 0 and "active" in (r.stdout or "")
except Exception:
return False
def stop() -> dict[str, Any]:
"""Stop DouyinWEB residential forwarder only — never host sing-box.service."""
pid = _read_pid()
if _pid_alive(pid):
try:
os.kill(pid, signal.SIGTERM)
time.sleep(0.8)
if _pid_alive(pid):
os.kill(pid, signal.SIGKILL)
except Exception:
pass
try:
_assert_safe_unit(UNIT_NAME)
subprocess.run(["systemctl", "stop", UNIT_NAME], capture_output=True, timeout=15)
except Exception:
pass
_PID_FILE.unlink(missing_ok=True)
return {"ok": True, "running": False, "unit": UNIT_NAME}
def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
binary = _find_binary()
if not binary:
return {
"ok": False,
"running": False,
"error": "未找到 sing-box 二进制(可与 v2ray-agent 共用 /usr/bin/sing-box,但使用独立配置)",
}
write_config(cfg_dict)
stop()
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
log_f = open(_LOG_PATH, "a", encoding="utf-8") # noqa: SIM115
try:
proc = subprocess.Popen(
[binary, "run", "-c", str(SINGBOX_CONFIG_PATH)],
stdin=subprocess.DEVNULL,
stdout=log_f,
stderr=subprocess.STDOUT,
cwd=str(BACKEND),
start_new_session=True,
)
except Exception as exc:
log_f.close()
return {"ok": False, "running": False, "error": str(exc)}
_PID_FILE.write_text(str(proc.pid), encoding="utf-8")
time.sleep(0.6)
if proc.poll() is not None:
tail = ""
try:
tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:]
except Exception:
pass
return {"ok": False, "running": False, "error": f"douyinweb-singbox 启动失败: {tail}"}
return {
"ok": True,
"running": True,
"pid": proc.pid,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
}
def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from .global_socks import _settings_dict
settings = _settings_dict(cfg)
if not is_global_socks_enabled(settings):
stop()
return {"ok": True, "running": False, "enabled": False, "unit": UNIT_NAME}
prof = active_profile(settings)
if not prof:
stop()
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置", "unit": UNIT_NAME}
try:
cfg_dict = build_config(prof)
except ValueError as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
write_config(cfg_dict)
try:
_assert_safe_unit(UNIT_NAME)
r = subprocess.run(
["systemctl", "restart", UNIT_NAME],
capture_output=True,
text=True,
timeout=20,
)
if r.returncode == 0:
time.sleep(0.5)
if is_running():
return {
"ok": True,
"running": True,
"enabled": True,
"via": "systemd",
"unit": UNIT_NAME,
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
}
except Exception:
pass
return {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
def host_v2ray_agent_status() -> dict[str, Any]:
"""Read-only peek at v2ray-agent edge (never mutate)."""
active = ""
try:
r = subprocess.run(
["systemctl", "is-active", "sing-box"],
capture_output=True,
text=True,
timeout=5,
)
active = (r.stdout or "").strip()
except Exception as exc:
active = f"error:{exc}"
return {
"unit": "sing-box.service",
"active": active,
"config_dir_exists": V2RAY_AGENT_DIR.is_dir(),
"note": "read-only; DouyinWEB never restarts this unit",
}
def status() -> dict[str, Any]:
binary = _find_binary()
pid = _read_pid()
return {
"running": is_running(),
"pid": pid if _pid_alive(pid) else 0,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
"v2ray_agent": host_v2ray_agent_status(),
"error": "",
}