From 6777bdf0565e973197b024a3dc40251009fc3728 Mon Sep 17 00:00:00 2001 From: eric Date: Tue, 22 Sep 2026 10:52:53 -0500 Subject: [PATCH] Use DouyinWEB-owned sing-box binary under /opt/douyinWEB/bin; never v2ray-agent. Co-authored-by: Cursor --- backend/app/singbox_manager.py | 125 ++++++++++++++++++++-- scripts/_fix_singbox_isolated_both.py | 134 ++++++++++++++++++++++++ scripts/linux/douyinweb-singbox.service | 6 +- 3 files changed, 255 insertions(+), 10 deletions(-) create mode 100644 scripts/_fix_singbox_isolated_both.py diff --git a/backend/app/singbox_manager.py b/backend/app/singbox_manager.py index e90d0ef..aca930f 100644 --- a/backend/app/singbox_manager.py +++ b/backend/app/singbox_manager.py @@ -32,6 +32,13 @@ from .global_socks import ( 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") +# Dedicated binary — NEVER use /etc/v2ray-agent/sing-box/sing-box +APP_BIN_DIR = BACKEND.parent / "bin" +APP_SINGBOX = APP_BIN_DIR / "sing-box" +# Pin a known-good release; install only into APP_BIN_DIR. +SINGBOX_VERSION = "1.11.15" +SINGBOX_ASSET = f"sing-box-{SINGBOX_VERSION}-linux-amd64.tar.gz" +SINGBOX_URL = f"https://github.com/SagerNet/sing-box/releases/download/v{SINGBOX_VERSION}/{SINGBOX_ASSET}" _PID_FILE = CONFIG_DIR / "sing-box.pid" _LOG_PATH = CONFIG_DIR / "sing-box.log" @@ -47,14 +54,69 @@ def _assert_safe_unit(name: str) -> str: return UNIT_NAME +def _assert_safe_binary(path: str) -> str: + """Refuse any binary under v2ray-agent tree.""" + p = Path(path).resolve() + try: + p.relative_to(V2RAY_AGENT_DIR.resolve()) + raise RuntimeError(f"refusing v2ray-agent binary: {p}") + except ValueError: + pass + if "v2ray-agent" in str(p): + raise RuntimeError(f"refusing v2ray-agent binary: {p}") + return str(p) + + 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) + """Only DouyinWEB-owned paths — never PATH /usr/bin or v2ray-agent.""" + candidates = [ + APP_SINGBOX, + Path("/opt/douyinWEB/bin/sing-box"), + ] + for cand in candidates: + if cand.is_file() and os.access(cand, os.X_OK): + try: + return _assert_safe_binary(str(cand)) + except RuntimeError: + continue return "" +def ensure_binary() -> str: + """Install dedicated sing-box into /opt/douyinWEB/bin if missing.""" + found = _find_binary() + if found: + return found + APP_BIN_DIR.mkdir(parents=True, exist_ok=True) + import tempfile + import urllib.request + + tmp_dir = Path(tempfile.mkdtemp(prefix="dy-singbox-")) + try: + tgz = tmp_dir / SINGBOX_ASSET + urllib.request.urlretrieve(SINGBOX_URL, tgz) # noqa: S310 + subprocess.run( + ["tar", "-xzf", str(tgz), "-C", str(tmp_dir)], + check=True, + capture_output=True, + timeout=120, + ) + # tarball contains sing-box--linux-amd64/sing-box + extracted = next(tmp_dir.rglob("sing-box"), None) + if extracted is None or not extracted.is_file() or extracted.name != "sing-box": + # rglob may hit the dir; prefer the file + files = [p for p in tmp_dir.rglob("sing-box") if p.is_file()] + extracted = files[0] if files else None + if not extracted or not extracted.is_file(): + raise RuntimeError("sing-box binary missing from release tarball") + dest = APP_SINGBOX + shutil.copy2(extracted, dest) + os.chmod(dest, 0o755) + return _assert_safe_binary(str(dest)) + finally: + shutil.rmtree(tmp_dir, ignore_errors=True) + + def build_config(profile: dict[str, Any] | None) -> dict[str, Any]: if not profile: raise ValueError("SOCKS 配置无效") @@ -165,12 +227,19 @@ def stop() -> dict[str, Any]: def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]: - binary = _find_binary() + try: + binary = ensure_binary() + except Exception as exc: + return { + "ok": False, + "running": False, + "error": f"无法安装 DouyinWEB 专用 sing-box: {exc}", + } if not binary: return { "ok": False, "running": False, - "error": "未找到 sing-box 二进制(可与 v2ray-agent 共用 /usr/bin/sing-box,但使用独立配置)", + "error": "未找到 DouyinWEB 专用 sing-box(应位于 /opt/douyinWEB/bin/sing-box,不使用 v2ray-agent)", } write_config(cfg_dict) stop() @@ -225,6 +294,16 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]: stop() return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME} write_config(cfg_dict) + try: + ensure_binary() + except Exception as exc: + stop() + return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME} + # Rewrite unit ExecStart to app-owned binary (never /usr/bin or v2ray-agent). + try: + _install_unit_file() + except Exception: + pass try: _assert_safe_unit(UNIT_NAME) r = subprocess.run( @@ -270,6 +349,35 @@ def host_v2ray_agent_status() -> dict[str, Any]: } +def _install_unit_file() -> None: + binary = ensure_binary() + unit = f"""[Unit] +Description=DouyinWEB residential SOCKS forwarder (isolated from v2ray-agent) +Documentation=file:/opt/douyinWEB/README.md +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +WorkingDirectory=/opt/douyinWEB/backend +ExecStart={binary} run -c /opt/douyinWEB/config/sing-box.json +Restart=on-failure +RestartSec=3 +Nice=5 +NoNewPrivileges=true +ProtectSystem=full +ProtectHome=true +PrivateTmp=true +ReadOnlyPaths=/etc/v2ray-agent + +[Install] +WantedBy=multi-user.target +""" + path = Path(f"/etc/systemd/system/{UNIT_NAME}.service") + path.write_text(unit, encoding="utf-8") + subprocess.run(["systemctl", "daemon-reload"], capture_output=True, timeout=15) + + def status() -> dict[str, Any]: binary = _find_binary() pid = _read_pid() @@ -281,5 +389,10 @@ def status() -> dict[str, Any]: "mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}", "unit": UNIT_NAME, "v2ray_agent": host_v2ray_agent_status(), + "isolation": { + "app_bin": str(APP_SINGBOX), + "never_uses": str(V2RAY_AGENT_DIR), + "never_restarts": "sing-box.service", + }, "error": "", } diff --git a/scripts/_fix_singbox_isolated_both.py b/scripts/_fix_singbox_isolated_both.py new file mode 100644 index 0000000..b7e7ba3 --- /dev/null +++ b/scripts/_fix_singbox_isolated_both.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +"""Install DouyinWEB-owned sing-box binary + fix residential apply on both VPS. + +NEVER uses /etc/v2ray-agent/sing-box/sing-box. +NEVER restarts host sing-box.service. +""" +from __future__ import annotations + +import io +import sys +import tarfile +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +JUMP = "107.173.30.245" +HOSTS = [("dylive", "107.173.30.245", False), ("dy", "108.174.50.68", True)] + +FILES = [ + "backend/app/singbox_manager.py", + "scripts/linux/douyinweb-singbox.service", +] + +REMOTE = r''' +set -e +REPO=/opt/douyinWEB +# stop crash-loop first +systemctl stop douyinweb-singbox 2>/dev/null || true +systemctl reset-failed douyinweb-singbox 2>/dev/null || true + +tar -xzf /tmp/sb_fix.tgz -C "$REPO" +install -d -m 755 /opt/douyinWEB/bin /opt/douyinWEB/config + +# Download dedicated binary into APP dir (NOT v2ray-agent) +VER=1.11.15 +ASSET="sing-box-${VER}-linux-amd64.tar.gz" +URL="https://github.com/SagerNet/sing-box/releases/download/v${VER}/${ASSET}" +cd /tmp +rm -rf _sb_dl && mkdir _sb_dl && cd _sb_dl +if ! curl -fsSL -o "$ASSET" "$URL"; then + wget -q -O "$ASSET" "$URL" +fi +tar -xzf "$ASSET" +BIN=$(find . -type f -name sing-box | head -1) +test -n "$BIN" +install -m 755 "$BIN" /opt/douyinWEB/bin/sing-box +# prove isolation +realpath /opt/douyinWEB/bin/sing-box +test "$(realpath /opt/douyinWEB/bin/sing-box)" != "$(realpath /etc/v2ray-agent/sing-box/sing-box 2>/dev/null || echo x)" +/opt/douyinWEB/bin/sing-box version | head -3 + +install -m 644 "$REPO/scripts/linux/douyinweb-singbox.service" /etc/systemd/system/douyinweb-singbox.service +systemctl daemon-reload + +cd "$REPO/backend" +.venv/bin/python -m py_compile app/singbox_manager.py +systemctl restart douyinweb-api +sleep 3 +.venv/bin/python - <<'PY' +from app import db, egress_hub, singbox_manager +m = db.get_settings_map() +print("host_sing-box before=", singbox_manager.host_v2ray_agent_status().get("active")) +# apply residential if profile exists +if m.get("global_socks_enabled") or str(m.get("egress_mode") or "") == "residential": + r = egress_hub.apply_mode("residential", chain=False, refresh_neko=False, cfg=m) + print("apply=", r.get("ok"), r.get("residential", {}).get("ok"), r.get("residential", {}).get("error") or r.get("residential", {}).get("via")) +else: + # just ensure binary + unit; leave mode off + print("bin=", singbox_manager.ensure_binary()) + print("skip apply (residential not enabled in settings)") +print("app_running=", singbox_manager.is_running()) +print("app_bin=", singbox_manager._find_binary()) +print("host_sing-box after=", singbox_manager.host_v2ray_agent_status().get("active")) +st = egress_hub.status() +print("mode=", st.get("mode"), "matrix_uploads=", st.get("matrix")) +print("FIX_OK") +PY + +systemctl is-active sing-box +systemctl is-active douyinweb-singbox || true +ss -lntp | grep 17891 || true +curl -sS -m 5 -o /dev/null -w "api=%{http_code}\n" http://127.0.0.1:8014/api/health +# quick probe via mixed if running +if ss -lntp | grep -q 17891; then + curl -sS -m 12 -x http://127.0.0.1:17891 https://api.ipify.org && echo +fi +echo DONE +''' + + +def main() -> int: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for rel in FILES: + tar.add(ROOT / rel, arcname=rel) + blob = buf.getvalue() + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(JUMP, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False) + with c.open_sftp() as sf: + with sf.file("/tmp/sb_fix.tgz", "wb") as f: + f.write(blob) + with sf.file("/tmp/_fix_sb_iso.sh", "w") as f: + f.write(REMOTE.replace("\r\n", "\n")) + for label, host, via in HOSTS: + print(f"\n===== {label} =====", flush=True) + if via: + c.exec_command( + f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no " + f"/tmp/sb_fix.tgz /tmp/_fix_sb_iso.sh root@{host}:/tmp/", + timeout=60, + )[1].channel.recv_exit_status() + _, o, e = c.exec_command( + f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{host} " + f"bash /tmp/_fix_sb_iso.sh", + timeout=300, + ) + else: + _, o, e = c.exec_command("bash /tmp/_fix_sb_iso.sh", timeout=300) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-10000:] if len(out) > 10000 else out, flush=True) + if "FIX_OK" not in out: + raise SystemExit(f"{label} failed") + c.close() + print("\nBOTH_FIXED_ISOLATED", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/linux/douyinweb-singbox.service b/scripts/linux/douyinweb-singbox.service index b65dfa0..3a47ae4 100644 --- a/scripts/linux/douyinweb-singbox.service +++ b/scripts/linux/douyinweb-singbox.service @@ -6,18 +6,16 @@ Wants=network-online.target [Service] Type=simple -# MUST NOT be named sing-box.service — that unit belongs to v2ray-agent. +# Binary is DouyinWEB-owned ONLY — never /etc/v2ray-agent/sing-box/sing-box WorkingDirectory=/opt/douyinWEB/backend -ExecStart=/usr/bin/sing-box run -c /opt/douyinWEB/config/sing-box.json +ExecStart=/opt/douyinWEB/bin/sing-box run -c /opt/douyinWEB/config/sing-box.json Restart=on-failure RestartSec=3 Nice=5 -# Bind only via config listen 127.0.0.1:17891 — never TUN / never rewrite host routes. NoNewPrivileges=true ProtectSystem=full ProtectHome=true PrivateTmp=true -# Hard deny writing v2ray-agent tree ReadOnlyPaths=/etc/v2ray-agent [Install]