From f7dc2b6b4e0bd3a425f6895f3ac5e0f631b572de Mon Sep 17 00:00:00 2001 From: eric Date: Mon, 21 Sep 2026 21:03:34 -0500 Subject: [PATCH] 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 --- README.md | 4 +- backend/app/egress_hub.py | 327 ++++++++++++++++-------- backend/app/host_profile.py | 7 +- backend/app/main.py | 60 ++++- backend/app/network_hub.py | 4 +- backend/app/singbox_manager.py | 103 +++++++- backend/app/tiktok_socks.py | 32 ++- backend/app/youtube_live.py | 15 +- frontend/src/app/network/page.tsx | 94 ++++--- scripts/_deploy_git_pull_both.py | 6 +- scripts/_deploy_residential_test3.py | 137 ++++++++++ scripts/linux/build_orphan_watch.sh | 44 +++- scripts/linux/douyinweb-singbox.service | 24 ++ 13 files changed, 662 insertions(+), 195 deletions(-) create mode 100644 scripts/_deploy_residential_test3.py create mode 100644 scripts/linux/douyinweb-singbox.service diff --git a/README.md b/README.md index 223b0f2..d6f071a 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ cd desktop && npm install && npm run electron:dev | 脚本 | `scripts/bootstrap_vps.sh` | | TLS | 本机 Nginx / 宝塔 / Caddy → `127.0.0.1:4015/8014` | | 进程绑定 | 通常 `127.0.0.1` | -| 业务出海(可选) | 文档后文「全局 SOCKS5 / DouyinWEB 专用 sing-box」规划;**勿动** VPS 上已有 v2ray-agent `sing-box` | +| 业务出海(可选) | **静态住宅 IP**:`egress_mode=residential` → 本机 `douyinweb-singbox` `:17891` → 供应商 SOCKS;**默认 off(机房 IP)**;**勿动** v2ray-agent `sing-box.service` | | ShellCrash | **不是**默认栈;不要在纯 VPS 上假设有 `:7890` ShellCrash | | Neko WebRTC | `NEKO_WEBRTC_NAT1TO1` / `DY_NEKO_NAT1TO1` = **本机公网 IP**;UDP/TCP mux 在本机安全组放行(无第二跳 DNAT) | | 边缘 Caddy | 不需要 `bootstrap_physical_edge.sh` | @@ -451,7 +451,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,** | API 内存 | systemd drop-in(对齐 dylive 紧预算,按机内存微调) | 例:dylive ≈ High **700M** / Max **900M**;dy.live ≈ High **1100M** / Max **1500M**(ffmpeg 已外置) | | ffmpeg CPU | `douyinweb-ffmpeg.slice` `CPUQuota` | dy.live 现网 **200%**(4 核机留给 API/Neko 余量) | | Web 加固 | `douyinweb-web.service.d/harden.conf` | `KillMode=control-group` + `CPUQuota=150%`,部署后孤儿随 unit 杀掉 | -| 孤儿守护 | `scripts/linux/build_orphan_watch.sh` + timer(每分钟) | 清 Next SWC `usr` / 无参 `node` / `.r*` 临时目录 | +| 孤儿守护 | `scripts/linux/build_orphan_watch.sh` + timer(每分钟) | 清 Next SWC `usr` / 假 `pm2` / 无参 `node` / `.d*` `.r*` 临时目录 | | 看门狗 | `scripts/linux/api_health_watch.sh` → `douyinweb-api-watch.service` | health 连续失败或 `:8014` Recv-Q 过高 → SIGKILL 重启 API | 对齐部署:`python scripts/_stabilize_dy_permanent.py`(孤儿 timer + web/api CPU);配额/代码对齐另用 `scripts/_align_dy_to_dylive_harden.py`。 diff --git a/backend/app/egress_hub.py b/backend/app/egress_hub.py index 67537c8..d41d8c8 100644 --- a/backend/app/egress_hub.py +++ b/backend/app/egress_hub.py @@ -1,14 +1,15 @@ # -*- coding: utf-8 -*- -"""Business egress — always via ShellCrash on China physical hosts. +"""Business egress for DouyinWEB. -Correct model (虚空终端 dialer-proxy): - App → 127.0.0.1:7890 (ShellCrash mixed) - ├─ 默认:选机场节点直接出海 - └─ 勾选「住宅落地」:选 dy-residential(socks5 + dialer-proxy) - → 先经 ShellCrash 前置节点拨号,再连住宅 SOCKS 落地 - (家宽无法直连海外住宅 SOCKS) +US VPS (primary): + off → datacenter IP direct + residential → 127.0.0.1:17891 (douyinweb-singbox) → static residential SOCKS + NEVER touches host sing-box.service / v2ray-agent -Docs: https://wiki.metacubex.one/config/proxies/dialer-proxy/ +Physical China (legacy, optional): + shellcrash → 127.0.0.1:7890 (+ optional dialer-proxy residential chain) + +Douyin scrape/CDN stays DIRECT in all modes (callers must not inject proxy). """ from __future__ import annotations @@ -19,9 +20,9 @@ from pathlib import Path from typing import Any from .config import BACKEND, ROOT -from .global_socks import CONFIG_DIR +from .global_socks import CONFIG_DIR, LOCAL_MIXED_HOST, LOCAL_MIXED_PORT, local_mixed_url -MODES = ("off", "shellcrash") +MODES = ("off", "shellcrash", "residential") PROXYCHAINS_CONF = CONFIG_DIR / "proxychains.conf" RESIDENTIAL_PROXY_NAME = "dy-residential" DEFAULT_DIALER = "dialer" @@ -41,38 +42,53 @@ def _settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]: return dict(db.get_settings_map()) +def _is_vps_host(cfg: dict[str, Any] | None = None) -> bool: + try: + from . import host_profile + + return host_profile.infer_profile(cfg) == "vps" + except Exception: + return True + + def get_mode(cfg: dict[str, Any] | None = None) -> str: s = _settings(cfg) raw = str(s.get(_MODE_KEY) or "").strip().lower() - # Legacy: "residential" meant chain-on ShellCrash, never direct SOCKS. - if raw == "residential": - return "shellcrash" if raw in MODES: return raw + # Legacy toggles → residential on VPS, shellcrash elsewhere if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"): - return "shellcrash" - # Default ON for China physical: all non-Douyin business via ShellCrash. - # Explicit "off" in settings still wins (handled above via MODES). + return "residential" if _is_vps_host(s) else "shellcrash" + if _is_vps_host(s): + return "off" return "shellcrash" +def local_residential_http_proxy() -> str: + return local_mixed_url() + + +def local_residential_socks() -> str: + return f"socks5://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}" + + def google_http_proxy(cfg: dict[str, Any] | None = None) -> str: - """Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT via Clash rules. - - - shellcrash mode → mixed :7890 - - mode off but ShellCrash still running → still use it (physical soft path) - - mode off + no ShellCrash → empty string (pure VPS direct) - """ - if get_mode(cfg) == "shellcrash": + """Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT.""" + mode = get_mode(cfg) + if mode == "residential": + return local_residential_http_proxy() + if mode == "shellcrash": return _host_http_proxy(cfg) - try: - from . import shellcrash_hub + # Soft path: ShellCrash still running on physical while mode off + if not _is_vps_host(cfg): + try: + from . import shellcrash_hub - st = shellcrash_hub.status() or {} - if st.get("running"): - return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}" - except Exception: - pass + st = shellcrash_hub.status() or {} + if st.get("running"): + return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}" + except Exception: + pass return "" @@ -84,20 +100,18 @@ def google_httpx_kwargs(*, timeout: float = 45.0, cfg: dict[str, Any] | None = N return kw -# Alias — overseas APIs (TikTok Open API, etc.) share the same egress. overseas_httpx_kwargs = google_httpx_kwargs overseas_http_proxy = google_http_proxy def chain_residential(cfg: dict[str, Any] | None = None) -> bool: + """ShellCrash dialer-proxy chain (physical only). VPS residential does not use this.""" s = _settings(cfg) + if get_mode(s) == "residential": + return False if _CHAIN_KEY in s: - return bool(s.get(_CHAIN_KEY)) - # Legacy residential mode / socks toggle → chain on - raw = str(s.get(_MODE_KEY) or "").strip().lower() - if raw == "residential": - return True - return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled")) + return bool(s.get(_CHAIN_KEY)) and get_mode(s) == "shellcrash" + return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled")) and get_mode(s) == "shellcrash" def cover_neko(cfg: dict[str, Any] | None = None) -> bool: @@ -111,7 +125,7 @@ def cover_relay(cfg: dict[str, Any] | None = None) -> bool: s = _settings(cfg) if _RELAY_KEY in s: return bool(s.get(_RELAY_KEY)) - return get_mode(s) == "shellcrash" + return get_mode(s) in {"shellcrash", "residential"} def cover_uploads(cfg: dict[str, Any] | None = None) -> bool: @@ -139,42 +153,48 @@ def _host_http_proxy(cfg: dict[str, Any] | None = None) -> str: def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str: - if get_mode(cfg) == "off": - return "" - return _host_http_proxy(cfg) + return google_http_proxy(cfg) def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str: if get_mode(cfg) == "off" or not cover_uploads(cfg): return "" - return _host_http_proxy(cfg) + return google_http_proxy(cfg) + + +def resolve_business_proxy(cfg: dict[str, Any] | None = None) -> str: + """Unified overseas business proxy (uploads / OAuth / TikTok fallback).""" + return resolve_upload_proxy(cfg) or google_http_proxy(cfg) def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str: - """Chromium inside Neko → host ShellCrash. - - Physical (DY_NEKO_EDGE_UPSTREAM set): always inject proxy unless egress mode is explicit off. - """ + """Chromium inside Neko → host local mixed (no upstream credentials in URL).""" import os physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip()) - if get_mode(cfg) == "off": + mode = get_mode(cfg) + if mode == "off": return "" if not cover_neko(cfg) and not physical: return "" + if mode == "residential": + return f"http://host.docker.internal:{LOCAL_MIXED_PORT}" return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}" def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path: - """Always point proxychains at ShellCrash mixed SOCKS — never raw residential.""" CONFIG_DIR.mkdir(parents=True, exist_ok=True) - if get_mode(cfg) != "shellcrash": + mode = get_mode(cfg) + if mode == "off": PROXYCHAINS_CONF.write_text( "# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n", encoding="utf-8", ) return PROXYCHAINS_CONF - port = shellcrash_mixed_port(cfg) + if mode == "residential": + port = LOCAL_MIXED_PORT + else: + port = shellcrash_mixed_port(cfg) text = ( "strict_chain\n" "proxy_dns\n" @@ -187,6 +207,12 @@ def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path: f"socks5 127.0.0.1 {port}\n" ) PROXYCHAINS_CONF.write_text(text, encoding="utf-8") + try: + import os + + os.chmod(PROXYCHAINS_CONF, 0o600) + except Exception: + pass return PROXYCHAINS_CONF @@ -220,20 +246,15 @@ def apply_mode( cfg: dict[str, Any] | None = None, ) -> dict[str, Any]: from . import db - from . import shellcrash_hub from . import singbox_manager raw = str(mode or "off").strip().lower() - if raw == "residential": - mode = "shellcrash" - if chain is None: - chain = True - elif raw not in MODES: + if raw not in MODES: raise ValueError(f"unsupported egress mode: {raw}") - else: - mode = raw + mode = raw s = _settings(cfg) + # dialer-proxy chain only meaningful with ShellCrash if chain is None: chain = chain_residential(s) if mode == "shellcrash" else False chain = bool(chain) and mode == "shellcrash" @@ -241,31 +262,46 @@ def apply_mode( if cover_neko_flag is None: cover_neko_flag = mode != "off" if cover_relay_flag is None: - cover_relay_flag = mode == "shellcrash" + cover_relay_flag = mode in {"shellcrash", "residential"} if cover_uploads_flag is None: cover_uploads_flag = mode != "off" + socks_on = mode == "residential" or (mode == "shellcrash" and chain) updates: dict[str, Any] = { _MODE_KEY: mode, _CHAIN_KEY: chain, _NEKO_KEY: bool(cover_neko_flag), _RELAY_KEY: bool(cover_relay_flag), _UPLOADS_KEY: bool(cover_uploads_flag), - # Keep legacy flags aligned with «住宅链式» checkbox only (not a separate engine). - "global_socks_enabled": chain, - "shorts_upload_socks_enabled": chain, + "global_socks_enabled": socks_on, + "shorts_upload_socks_enabled": socks_on, } db.update_settings_map(updates) s = db.get_settings_map() - # Never run douyinweb-singbox as China residential path — stop if leftover. - try: - singbox_manager.stop() - except Exception: - pass - chain_result: dict[str, Any] = {"skipped": True} + residential_result: dict[str, Any] = {"skipped": True} + + if mode == "residential": + from . import global_socks + + prof = global_socks.active_profile(s) + if not prof: + raise ValueError("已启用静态住宅 IP,但未配置 SOCKS5 账号(网络页「业务 SOCKS」填写)") + # Start DouyinWEB forwarder only — never host sing-box.service + residential_result = singbox_manager.apply_from_settings(s) + if not residential_result.get("ok") and not residential_result.get("running"): + raise ValueError(str(residential_result.get("error") or "douyinweb-singbox 启动失败")) + else: + # Leaving residential: stop app forwarder only + try: + residential_result = {**singbox_manager.stop(), "note": "stopped douyinweb-singbox"} + except Exception as exc: + residential_result = {"ok": False, "error": str(exc)} + if mode == "shellcrash": + from . import shellcrash_hub + if chain: from . import global_socks @@ -277,7 +313,6 @@ def apply_mode( dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER, ) else: - # Normal ShellCrash node (not residential landing). try: chain_result = shellcrash_hub.apply_profile( shellcrash_hub.DEFAULT_PROFILE, @@ -287,7 +322,7 @@ def apply_mode( chain_result = {"ok": False, "error": str(exc)} pc_path = "" - if mode == "shellcrash" and (cover_relay_flag or cover_uploads_flag): + if mode != "off" and (cover_relay_flag or cover_uploads_flag): pc_path = str(write_proxychains_conf(s)) neko_result: dict[str, Any] = {"skipped": True} @@ -303,26 +338,32 @@ def apply_mode( "ok": True, "egress": status(s), "chain": chain_result, + "residential": residential_result, "proxychains_conf": pc_path, "neko": neko_result, + "v2ray_agent": singbox_manager.host_v2ray_agent_status(), } def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]: mode = get_mode(cfg) - proxy = _host_http_proxy(cfg) if mode != "off" else "" + proxy = google_http_proxy(cfg) if mode != "off" else "" targets = [ ("google", "https://www.google.com/generate_204"), ("youtube", "https://www.youtube.com/"), + ("ip", "https://api.ipify.org"), ("douyin", "https://www.douyin.com/"), ] rows = [] for name, url in targets: - # Douyin: always probe DIRECT; also via proxy to show rule should still work for pull via ShellCrash if name == "douyin": rows.append(_curl_probe("douyin_direct", url, proxy="")) if proxy: - rows.append(_curl_probe("douyin_via_sc", url, proxy=proxy)) + rows.append(_curl_probe("douyin_via_proxy", url, proxy=proxy)) + continue + if name == "ip": + rows.append(_curl_probe_body("exit_ip", url, proxy=proxy)) + rows.append(_curl_probe_body("exit_ip_direct", url, proxy="")) continue rows.append(_curl_probe(name, url, proxy=proxy)) rows.append(_curl_probe(f"{name}_direct", url, proxy="")) @@ -366,29 +407,84 @@ def _curl_probe(name: str, url: str, *, proxy: str) -> dict[str, Any]: } +def _curl_probe_body(name: str, url: str, *, proxy: str) -> dict[str, Any]: + cmd = ["curl", "-sS", "-m", "10"] + if proxy: + cmd.extend(["-x", proxy]) + cmd.append(url) + t0 = time.time() + try: + p = subprocess.run(cmd, capture_output=True, text=True, timeout=14, check=False) + body = (p.stdout or "").strip()[:64] + ok = p.returncode == 0 and bool(body) + return { + "target": name, + "ok": ok, + "http_code": "200" if ok else "000", + "elapsed_ms": int((time.time() - t0) * 1000), + "via": proxy or "direct", + "body": body, + "error": (p.stderr or "").strip()[:160] if not ok else "", + } + except Exception as exc: + return { + "target": name, + "ok": False, + "http_code": "000", + "elapsed_ms": int((time.time() - t0) * 1000), + "via": proxy or "direct", + "body": "", + "error": str(exc)[:160], + } + + def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]: - from . import shellcrash_hub + from . import singbox_manager s = _settings(cfg) mode = get_mode(s) - chain = chain_residential(s) if mode == "shellcrash" else False - sc = shellcrash_hub.status() - host_proxy = _host_http_proxy(s) + chain = chain_residential(s) + vps = _is_vps_host(s) + sc: dict[str, Any] = {} + try: + from . import shellcrash_hub + + sc = shellcrash_hub.status() or {} + except Exception: + sc = {} + host_proxy = google_http_proxy(s) neko_proxy = neko_browser_proxy(s) pc = proxychains_bin() - exit_label = RESIDENTIAL_PROXY_NAME if chain else (sc.get("selected_node") or shellcrash_hub.DEFAULT_NODE) - return { - "mode": mode, - "chain_residential": chain, - "modes": [ - {"id": "off", "label": "直连", "description": "不经 ShellCrash"}, + sb = singbox_manager.status() + if mode == "residential": + exit_label = "static-residential" + elif chain: + exit_label = RESIDENTIAL_PROXY_NAME + else: + exit_label = sc.get("selected_node") or "direct" + modes_ui = [ + {"id": "off", "label": "机房直连", "description": "美国 VPS 默认:业务用机房 IP"}, + { + "id": "residential", + "label": "静态住宅 IP", + "description": f"本机 :{LOCAL_MIXED_PORT} → 住宅 SOCKS(不动 v2ray-agent)", + "ready": True, + }, + ] + if not vps: + modes_ui.append( { "id": "shellcrash", "label": "ShellCrash", - "description": "业务统一走本机 :7890;可选住宅链式落地", + "description": "物理机出海 :7890;可选住宅链式", "ready": bool(sc.get("running") or sc.get("installed")), - }, - ], + } + ) + return { + "mode": mode, + "chain_residential": chain, + "host_profile": "vps" if vps else "physical", + "modes": modes_ui, "cover": { "neko": cover_neko(s), "relay": cover_relay(s), @@ -399,13 +495,25 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]: "exit_node": exit_label, "dialer": DEFAULT_DIALER, "residential_proxy_name": RESIDENTIAL_PROXY_NAME, - "socks_url": f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "", + "socks_url": ( + local_residential_socks() + if mode == "residential" + else (f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "") + ), + "local_mixed": local_residential_http_proxy() if mode == "residential" else "", "proxychains": { "installed": bool(pc), "bin": pc, "conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "", "relay_active": ffmpeg_uses_proxy(s), }, + "douyinweb_singbox": { + "running": bool(sb.get("running")), + "unit": sb.get("unit"), + "mixed": sb.get("mixed"), + "config": sb.get("config"), + }, + "v2ray_agent": sb.get("v2ray_agent") or singbox_manager.host_v2ray_agent_status(), "shellcrash": { "running": bool(sc.get("running")), "mixed_port": sc.get("mixed_port") or "7890", @@ -414,48 +522,55 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]: "matrix": [ { "id": "neko", - "label": "Neko Chrome", + "label": "Neko Chrome / X", "active": bool(neko_proxy), - "detail": (neko_proxy + (f" → {exit_label}" if chain else "")) if neko_proxy else "直连", + "detail": neko_proxy or "直连(机房 IP)", }, { "id": "relay", "label": "直播推流 FFmpeg", "active": ffmpeg_uses_proxy(s), "detail": ( - f"proxychains → ShellCrash → {exit_label}" + f"proxychains → {exit_label}" if ffmpeg_uses_proxy(s) - else ("缺 proxychains" if cover_relay(s) and not pc else "直连") + else ("缺 proxychains" if cover_relay(s) and not pc else "直连(机房 IP)") ), }, { "id": "uploads", - "label": "Shorts / 长视频 / 上传", + "label": "Shorts / 长视频 / TikTok", "active": bool(resolve_upload_proxy(s)), - "detail": (host_proxy + (f" → {exit_label}" if chain else "")) if resolve_upload_proxy(s) else "直连", + "detail": (host_proxy + f" → {exit_label}") if resolve_upload_proxy(s) else "直连(机房 IP)", }, ], - "hints": _hints(mode, chain, sc, pc), + "hints": _hints(mode, chain, sc, pc, sb, vps), "app_root": str(ROOT), "backend": str(BACKEND), } -def _hints(mode: str, chain: bool, sc: dict[str, Any], pc: str) -> list[str]: +def _hints( + mode: str, + chain: bool, + sc: dict[str, Any], + pc: str, + sb: dict[str, Any], + vps: bool, +) -> list[str]: out: list[str] = [] - if mode == "shellcrash": - out.append("硬规则:*.douyin.com / 抖音 CDN 必须 DIRECT(拉流与监控不可走机场)") + out.append("硬规则:*.douyin.com / 抖音 CDN 始终直连,不进住宅代理") + out.append("绝不操作宿主机 sing-box.service(v2ray-agent);仅 douyinweb-singbox") + if mode == "residential": + if not sb.get("running"): + out.append("douyinweb-singbox 未运行 — 检查 SOCKS 账号后重新「应用」") + else: + out.append(f"业务入口 {local_residential_http_proxy()} → 静态住宅;默认关=机房 IP") + if mode == "off" and vps: + out.append("当前机房 IP 直出(美国 VPS 默认可访问 Google/YouTube)") if mode == "shellcrash" and not sc.get("running"): - out.append("ShellCrash 未运行 — 先启动,再应用出海") + out.append("ShellCrash 未运行 — 先启动再应用") if mode == "shellcrash" and chain: - out.append( - "住宅落地 = ShellCrash 链式(dialer-proxy):家宽 → 前置节点 → 住宅 SOCKS。" - "详见虚空终端 docs:dialer-proxy" - ) - if mode == "shellcrash" and not chain: - out.append("当前用 ShellCrash 机场线路出海;勾选「住宅落地」才会链式到 SOCKS5") + out.append("住宅落地 = ShellCrash dialer-proxy 链式(物理机)") if mode != "off" and not pc: out.append("未安装 proxychains4 — 直播推流无法走代理") - if mode == "off": - out.append("直连:国内物理机上 YouTube Studio / 推流通常不可用") return out diff --git a/backend/app/host_profile.py b/backend/app/host_profile.py index cb6b373..96c8bf4 100644 --- a/backend/app/host_profile.py +++ b/backend/app/host_profile.py @@ -43,9 +43,10 @@ def status() -> dict[str, Any]: "profiles": list(PROFILES), "effects": { "vps": [ - "egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)", - "本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)", - "单路独占默认开启(省内存;可配对物理机 ops-neko)", + "默认机房 IP 直出;可选「静态住宅 IP」经 douyinweb-singbox :17891", + "绝不操作宿主机 sing-box.service(v2ray-agent)", + "本机分配 Neko 仍可按频道启停", + "单路独占默认开启(省内存)", ], "physical": [ "业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)", diff --git a/backend/app/main.py b/backend/app/main.py index 91f4157..5cb2061 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -4521,22 +4521,39 @@ async def network_socks_get() -> dict[str, Any]: @app.patch("/api/network/socks") async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]: - """Update global SOCKS profiles — empty list allowed (fresh install).""" + """Update global SOCKS profiles — empty list allowed (fresh install). + + On VPS: enabled → egress_mode=residential + douyinweb-singbox only. + Never touches host sing-box.service (v2ray-agent). + """ from . import db + from . import egress_hub from . import global_socks + from . import host_profile from . import singbox_manager cfg = await asyncio.to_thread(db.get_settings_map) updates: dict[str, Any] = {} + want_on: bool | None = None if "enabled" in body: - updates["global_socks_enabled"] = bool(body.get("enabled")) - updates["shorts_upload_socks_enabled"] = bool(body.get("enabled")) - # 住宅 SOCKS 勾选 = ShellCrash 链式落地,不是独立引擎 - updates["egress_chain_residential"] = bool(body.get("enabled")) - if bool(body.get("enabled")): - updates["egress_mode"] = "shellcrash" - elif str(cfg.get("egress_mode") or "") == "residential": - updates["egress_mode"] = "shellcrash" + want_on = bool(body.get("enabled")) + updates["global_socks_enabled"] = want_on + updates["shorts_upload_socks_enabled"] = want_on + is_vps = host_profile.infer_profile(cfg) == "vps" + if want_on: + if is_vps: + updates["egress_mode"] = "residential" + updates["egress_chain_residential"] = False + else: + # Physical: keep ShellCrash dialer-proxy chain semantics + updates["egress_mode"] = "shellcrash" + updates["egress_chain_residential"] = True + else: + updates["egress_chain_residential"] = False + if str(cfg.get("egress_mode") or "") in {"residential", "shellcrash"}: + updates["egress_mode"] = "off" if is_vps else str(cfg.get("egress_mode") or "shellcrash") + if is_vps: + updates["egress_mode"] = "off" if "active_profile_id" in body: updates["global_socks_profile_id"] = str(body.get("active_profile_id") or "").strip() updates["shorts_upload_socks_profile_id"] = updates["global_socks_profile_id"] @@ -4547,7 +4564,6 @@ async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]: for item in raw: p = global_socks._norm_profile(item) if p and p["server"] and p["port"] > 0: - # Keep existing password if client sent masked *** old = global_socks.get_socks_profile(str(p["id"]), cfg) pwd = str(p.get("password") or "") if old and (not pwd or pwd.startswith("***")): @@ -4558,10 +4574,26 @@ async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]: if updates: await asyncio.to_thread(db.update_settings_map, updates) cfg = await asyncio.to_thread(db.get_settings_map) - try: - await asyncio.to_thread(singbox_manager.apply_from_settings, cfg) - except Exception: - pass + mode = str(cfg.get("egress_mode") or "off") + if mode == "residential" and cfg.get("global_socks_enabled"): + try: + await asyncio.to_thread( + egress_hub.apply_mode, + "residential", + chain=False, + refresh_neko=True, + cfg=cfg, + ) + except Exception: + try: + await asyncio.to_thread(singbox_manager.apply_from_settings, cfg) + except Exception: + pass + elif want_on is False or mode == "off": + try: + await asyncio.to_thread(singbox_manager.stop) + except Exception: + pass from . import network_hub return await asyncio.to_thread(network_hub.socks_status) diff --git a/backend/app/network_hub.py b/backend/app/network_hub.py index cfa6006..033cad0 100644 --- a/backend/app/network_hub.py +++ b/backend/app/network_hub.py @@ -99,7 +99,9 @@ def socks_status() -> dict[str, Any]: "profiles": profiles, "local_mixed": global_socks.local_mixed_url() if enabled else "", "singbox_running": bool(singbox_manager.is_running()) if enabled else False, - "hint": "新装默认无住宅节点;自行添加 SOCKS5", + "unit": "douyinweb-singbox", + "v2ray_agent": singbox_manager.host_v2ray_agent_status(), + "hint": "美国 VPS:填 SOCKS 后开「静态住宅 IP」;永不重启宿主机 sing-box.service", } diff --git a/backend/app/singbox_manager.py b/backend/app/singbox_manager.py index c8d9d3d..e90d0ef 100644 --- a/backend/app/singbox_manager.py +++ b/backend/app/singbox_manager.py @@ -1,5 +1,12 @@ # -*- coding: utf-8 -*- -"""sing-box local mixed inbound → remote SOCKS5 upstream.""" +"""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 @@ -21,10 +28,25 @@ from .global_socks import ( 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) @@ -76,8 +98,16 @@ def build_config(profile: dict[str, Any] | None) -> dict[str, Any]: 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 @@ -102,10 +132,9 @@ def is_running() -> bool: pid = _read_pid() if _pid_alive(pid): return True - # systemd fallback try: r = subprocess.run( - ["systemctl", "is-active", "douyinweb-singbox"], + ["systemctl", "is-active", UNIT_NAME], capture_output=True, text=True, timeout=5, @@ -116,25 +145,33 @@ def is_running() -> bool: 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: - subprocess.run(["systemctl", "stop", "douyinweb-singbox"], capture_output=True, timeout=15) + _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} + 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(apt install sing-box 或官方脚本)"} + 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) @@ -159,8 +196,16 @@ def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]: tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:] except Exception: pass - return {"ok": False, "running": False, "error": f"sing-box 启动失败: {tail}"} - return {"ok": True, "running": True, "pid": proc.pid, "binary": binary} + 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]: @@ -169,21 +214,21 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]: settings = _settings_dict(cfg) if not is_global_socks_enabled(settings): stop() - return {"ok": True, "running": False, "enabled": False} + 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 配置"} + 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)} - # Prefer systemd unit when present. + 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", "douyinweb-singbox"], + ["systemctl", "restart", UNIT_NAME], capture_output=True, text=True, timeout=20, @@ -191,12 +236,40 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]: if r.returncode == 0: time.sleep(0.5) if is_running(): - return {"ok": True, "running": True, "enabled": True, "via": "systemd"} + 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() @@ -206,5 +279,7 @@ def status() -> dict[str, Any]: "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": "", } diff --git a/backend/app/tiktok_socks.py b/backend/app/tiktok_socks.py index 1c39d0b..5bb08e4 100644 --- a/backend/app/tiktok_socks.py +++ b/backend/app/tiktok_socks.py @@ -85,20 +85,26 @@ def socks_proxy_url(profile: dict[str, Any] | None) -> str: def resolve_channel_socks_proxy(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> str: - """Return proxy URL only when this TikTok account opted into SOCKS; else empty (direct).""" - if not channel: + """Per-account SOCKS if opted in; else fall back to global residential / egress uploads proxy.""" + if channel: + enabled = channel.get("socks_enabled") + if isinstance(enabled, str): + enabled = enabled.strip().lower() in {"1", "true", "yes", "on"} + if enabled: + pid = str(channel.get("socks_profile_id") or "").strip() + prof = get_socks_profile(pid, cfg) + if not prof: + rows = list_socks_profiles(cfg, public=False) + prof = rows[0] if rows else None + url = socks_proxy_url(prof) + if url: + return url + try: + from . import egress_hub + + return egress_hub.resolve_upload_proxy(cfg) or "" + except Exception: return "" - enabled = channel.get("socks_enabled") - if isinstance(enabled, str): - enabled = enabled.strip().lower() in {"1", "true", "yes", "on"} - if not enabled: - return "" - pid = str(channel.get("socks_profile_id") or "").strip() - prof = get_socks_profile(pid, cfg) - if not prof: - rows = list_socks_profiles(cfg, public=False) - prof = rows[0] if rows else None - return socks_proxy_url(prof) def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]: diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py index 1e1de28..9a2a3b1 100644 --- a/backend/app/youtube_live.py +++ b/backend/app/youtube_live.py @@ -111,6 +111,14 @@ def _http_channel_live_probe(channel_id: str) -> dict[str, Any]: html = "" last_err = "" proxies_try: list[str] = [] + try: + from . import egress_hub + + hub_proxy = str(egress_hub.google_http_proxy() or "").strip() + if hub_proxy: + proxies_try.append(hub_proxy) + except Exception: + pass env_proxy = ( str(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "").strip() or str(os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") or "").strip() @@ -118,9 +126,10 @@ def _http_channel_live_probe(channel_id: str) -> dict[str, Any]: if env_proxy: proxies_try.append(env_proxy) proxies_try.append("") # direct - # Physical China guest: ShellCrash (same as douyinweb-yt) if env unset / direct fails - if "127.0.0.1:7890" not in env_proxy: - proxies_try.append("http://127.0.0.1:7890") + # Soft fallbacks (physical ShellCrash / legacy) — only if not already listed + for soft in ("http://127.0.0.1:17891", "http://127.0.0.1:7890"): + if soft not in proxies_try: + proxies_try.append(soft) seen_p: set[str] = set() for proxy in proxies_try: if proxy in seen_p: diff --git a/frontend/src/app/network/page.tsx b/frontend/src/app/network/page.tsx index 83e7cf5..e020cd2 100644 --- a/frontend/src/app/network/page.tsx +++ b/frontend/src/app/network/page.tsx @@ -23,6 +23,7 @@ type ScRoot = { root_id: string; label: string; file_count: number; files?: ScFi type EgressPayload = { mode?: string; chain_residential?: boolean; + host_profile?: string; modes?: Array<{ id: string; label: string; description?: string; ready?: boolean }>; cover?: { neko?: boolean; relay?: boolean; uploads?: boolean }; host_proxy?: string; @@ -32,6 +33,8 @@ type EgressPayload = { matrix?: Array<{ id: string; label: string; active?: boolean; detail?: string }>; proxychains?: { installed?: boolean; relay_active?: boolean; bin?: string }; shellcrash?: { running?: boolean; mixed_port?: string; selected_node?: string | null }; + douyinweb_singbox?: { running?: boolean; unit?: string; mixed?: string; config?: string }; + v2ray_agent?: { unit?: string; active?: string; config_dir_exists?: boolean; note?: string }; hints?: string[]; }; @@ -126,7 +129,7 @@ export default function NetworkPage() { const [filePath, setFilePath] = useState(""); const [fileContent, setFileContent] = useState(""); const [fileImportKey, setFileImportKey] = useState(0); - const [egressMode, setEgressMode] = useState<"off" | "shellcrash">("off"); + const [egressMode, setEgressMode] = useState<"off" | "shellcrash" | "residential">("off"); const [chainResidential, setChainResidential] = useState(false); const [coverNeko, setCoverNeko] = useState(true); const [coverRelay, setCoverRelay] = useState(true); @@ -185,7 +188,7 @@ export default function NetworkPage() { /* editor stays empty if unreadable */ } const mode = String(r.egress?.mode || "off"); - setEgressMode(mode === "shellcrash" ? "shellcrash" : "off"); + setEgressMode(mode === "residential" || mode === "shellcrash" ? mode : "off"); setChainResidential(Boolean(r.egress?.chain_residential)); setCoverNeko(r.egress?.cover?.neko !== false); setCoverRelay(Boolean(r.egress?.cover?.relay)); @@ -228,10 +231,12 @@ export default function NetworkPage() { }); toast.push( egressMode === "off" - ? "已切回直连" - : chainResidential - ? "已启用 ShellCrash + 住宅链式落地" - : "已启用 ShellCrash 机场线路", + ? "已切回机房直连" + : egressMode === "residential" + ? "已启用静态住宅 IP(douyinweb-singbox :17891)" + : chainResidential + ? "已启用 ShellCrash + 住宅链式落地" + : "已启用 ShellCrash 机场线路", "ok", ); await load(); @@ -501,7 +506,7 @@ export default function NetworkPage() {

网络

-

业务出海 · ShellCrash · SOCKS · WireGuard · FRP

+

静态住宅 IP · 业务出海 · SOCKS · WireGuard · FRP

) : ( <> - {/* ===== 业务出海 ===== */} + {/* ===== 业务出海 / 静态住宅 ===== */}
-

业务出海

+

静态住宅 IP(业务全局)

- 统一走 ShellCrash(:7890)。硬规则:*.douyin.com 必须直连 - ;YouTube 出海。家宽不能直连海外住宅 SOCKS——勾选「住宅落地」= dialer-proxy 链式。 + 美国 VPS:默认机房 IP 直出。启用后 YT 直播/长视频/Shorts、TikTok、X/Neko 统一经本机{" "} + :17891 → 住宅 SOCKS。 + 抖音始终直连; + 不改动 v2ray-agent 的 sing-box.service。

@@ -540,15 +547,25 @@ export default function NetworkPage() { [ { id: "off" as const, - title: "直连", - desc: "不经 ShellCrash,国内机器上 YouTube 通常不可用", + title: "机房直连", + desc: "默认 · 业务用美国 VPS 机房 IP(已可访问 Google/YouTube)", }, { - id: "shellcrash" as const, - title: "ShellCrash", - desc: "推荐 · Neko / 推流 / 上传全部进 :7890,由规则分流", - ready: Boolean(eg?.shellcrash?.running || sc?.running), + id: "residential" as const, + title: "静态住宅 IP", + desc: "douyinweb-singbox → 下方 SOCKS 账号;Neko 用无认证本机 HTTP,不伤 v2ray-agent", + ready: Boolean(eg?.douyinweb_singbox?.running || data?.socks?.profiles?.length), }, + ...(eg?.host_profile === "physical" || eg?.modes?.some((m) => m.id === "shellcrash") + ? [ + { + id: "shellcrash" as const, + title: "ShellCrash(物理机)", + desc: "家宽出海 :7890;可选 dialer 链式住宅", + ready: Boolean(eg?.shellcrash?.running || sc?.running), + }, + ] + : []), ] as const ).map((m) => { const active = egressMode === m.id; @@ -558,11 +575,18 @@ export default function NetworkPage() { type="button" onClick={() => { setEgressMode(m.id); - if (m.id === "shellcrash") { + if (m.id === "residential" || m.id === "shellcrash") { setCoverRelay(true); setCoverNeko(true); setCoverUploads(true); } + if (m.id === "residential") { + setSocksEnabled(true); + setChainResidential(false); + } + if (m.id === "off") { + setSocksEnabled(false); + } }} className={`rounded-2xl border p-4 text-left transition ${ active @@ -584,6 +608,7 @@ export default function NetworkPage() { })} + {egressMode === "shellcrash" ? (
- 住宅落地(ShellCrash 链式代理) + 住宅落地(ShellCrash 链式代理 · 物理机) - 不勾选:用机场节点出海。勾选:写入 dy-residential - (socks5 + dialer-proxy → {eg?.dialer || "dialer"}),经前置节点再连住宅 SOCKS。账号在下方「业务 SOCKS」填写。 + 美国 VPS 请用上方「静态住宅 IP」,不要用链式。 - {eg?.exit_node ? ( -

当前出口节点:{eg.exit_node}

- ) : null}
+ ) : null} + + {eg?.v2ray_agent ? ( +

+ v2ray-agent sing-box.service(只读): {String((eg.v2ray_agent as { active?: string }).active || "—")} · + DouyinWEB 单元: {eg.douyinweb_singbox?.running ? "douyinweb-singbox 运行中" : "douyinweb-singbox 未启"} +

+ ) : null}
@@ -668,6 +697,9 @@ export default function NetworkPage() {

{p.http_code} · {p.elapsed_ms}ms · {p.via === "direct" || !p.via ? "直连" : "代理"} + {"body" in p && (p as { body?: string }).body + ? ` · ${(p as { body?: string }).body}` + : ""}

))} @@ -836,9 +868,9 @@ export default function NetworkPage() {
-

业务 SOCKS(住宅落地账号)

+

业务 SOCKS(静态住宅账号)

- 仅在出海勾选「住宅落地」时使用:写入 ShellCrash 链式节点,经 dialer 前置再连此 SOCKS。家宽不会直连它。 + 填写供应商 SOCKS5。启用「静态住宅 IP」后由 douyinweb-singbox 转发到此账号;账号不会进 Chrome URL。

setSocksEnabled(e.target.checked)} /> - 启用为住宅链式账号(与上方「住宅落地」同步) + 启用静态住宅账号(与上方「静态住宅 IP」联动)
diff --git a/scripts/_deploy_git_pull_both.py b/scripts/_deploy_git_pull_both.py index a0d829f..9e680e9 100644 --- a/scripts/_deploy_git_pull_both.py +++ b/scripts/_deploy_git_pull_both.py @@ -103,13 +103,15 @@ def deps_and_restart(c: paramiko.SSHClient, *, label: str, public_health: str) - code, _ = run( c, f"bash -lc 'set -e; cd {REPO}/frontend; npm ci --prefer-offline 2>/dev/null || npm install; npm run build; " - # Next SWC can leave orphan \"usr\" / bare \"node\" spinning at 100%+ after deploy. + # Next SWC can leave orphan usr/pm2/bare-node + .d*/.r* caches spinning CPU. f"pkill -9 -x usr 2>/dev/null || true; " + f"pkill -9 -x pm2 2>/dev/null || true; " f"for p in $(pgrep -x node || true); do " f" cmd=$(tr \"\\0\" \" \" < /proc/$p/cmdline 2>/dev/null); " f" if [ \"$cmd\" = \"node \" ] || [ \"$cmd\" = \"node\" ]; then kill -9 $p || true; fi; " f"done; " - f"rm -rf {REPO}/frontend/.r* 2>/dev/null || true'", + f"rm -rf {REPO}/frontend/.r* {REPO}/frontend/.d* 2>/dev/null || true; " + f"bash {REPO}/scripts/linux/build_orphan_watch.sh 2>/dev/null || true'", timeout=900, label=label, ) diff --git a/scripts/_deploy_residential_test3.py b/scripts/_deploy_residential_test3.py new file mode 100644 index 0000000..2d9badd --- /dev/null +++ b/scripts/_deploy_residential_test3.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +"""Deploy test3 residential egress to both VPS — preserve DB, default residential OFF. + +Safety: + - Never touch sing-box.service / /etc/v2ray-agent + - Never wipe monitor.db / pb_data / neko profiles + - Install douyinweb-singbox.service but do NOT enable residential + - Restart only douyinweb-api / douyinweb-web +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +ROOT = Path(__file__).resolve().parents[1] +PASS = "Xiao4669805" +REMOTE = "https://eric:Xiao4669805@gitea.dsx2020.com/eric/douyinWEB.git" +BRANCH = "test3" +JUMP = "107.173.30.245" +HOSTS = [ + ("dylive", "107.173.30.245", False), + ("dy", "108.174.50.68", True), +] + +UNIT_SRC = (ROOT / "scripts/linux/douyinweb-singbox.service").read_text(encoding="utf-8") + +REMOTE_SH = r''' +set -e +REPO=/opt/douyinWEB +BRANCH=test3 +ts=$(date +%Y%m%d_%H%M%S) + +mkdir -p "$REPO/backend/data" +cp -a "$REPO/backend/data/monitor.db" "$REPO/backend/data/monitor.db.bak.$ts" 2>/dev/null || true + +cd "$REPO" +git remote remove origin 2>/dev/null || true +git remote add origin "__REMOTE__" +git fetch origin "$BRANCH" +git clean -fd -e backend/data -e frontend/.next -e node_modules -e frontend/node_modules \ + -e backend/.venv -e .venv -e "*.db" -e "*.db-*" -e pb_data -e backend/pb_data \ + -e config -e backend/data/neko -e backend/data/ops_neko -e backend/data/clips \ + -e backend/data/covers 2>/dev/null || true +git checkout -f -B "$BRANCH" "origin/$BRANCH" +git reset --hard "origin/$BRANCH" +git log -1 --oneline + +install -d -m 755 /opt/douyinWEB/config +install -m 644 /tmp/douyinweb-singbox.service /etc/systemd/system/douyinweb-singbox.service +if [ ! -x /usr/bin/sing-box ] && command -v sing-box >/dev/null; then + BIN=$(command -v sing-box) + sed -i "s|/usr/bin/sing-box|$BIN|" /etc/systemd/system/douyinweb-singbox.service +fi +systemctl daemon-reload +systemctl stop douyinweb-singbox 2>/dev/null || true +systemctl disable douyinweb-singbox 2>/dev/null || true + +cd "$REPO/backend" +.venv/bin/python -m py_compile app/egress_hub.py app/singbox_manager.py app/tiktok_socks.py app/youtube_live.py +echo py_compile_ok + +cd "$REPO/frontend" +npm ci --prefer-offline 2>/dev/null || npm install +npm run build +pkill -9 -x usr 2>/dev/null || true +pkill -9 -x pm2 2>/dev/null || true +bash "$REPO/scripts/linux/build_orphan_watch.sh" 2>/dev/null || true + +systemctl restart douyinweb-api +systemctl restart douyinweb-web +sleep 5 + +echo "=== VERIFY ===" +systemctl is-active douyinweb-api douyinweb-web +echo -n "host_sing-box="; systemctl is-active sing-box 2>/dev/null || true +echo -n "app_douyinweb-singbox="; systemctl is-active douyinweb-singbox 2>/dev/null || echo inactive +curl -sS -m 8 -o /dev/null -w "health=%{http_code} t=%{time_total}\n" http://127.0.0.1:8014/api/health +cd "$REPO/backend" +.venv/bin/python - <<'PY' +from app import egress_hub, singbox_manager +st = egress_hub.status() +print("egress_mode=", st.get("mode")) +print("v2ray_agent=", st.get("v2ray_agent")) +print("app_sb=", st.get("douyinweb_singbox")) +va = singbox_manager.host_v2ray_agent_status() +print("host_singbox_active=", va.get("active")) +# Host sing-box should remain active (v2ray-agent). Soft warn only if missing. +print("DEPLOY_OK") +PY +echo DONE +''' + + +def main() -> int: + 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) + script = REMOTE_SH.replace("__REMOTE__", REMOTE).replace("\r\n", "\n") + with c.open_sftp() as sf: + with sf.file("/tmp/douyinweb-singbox.service", "w") as f: + f.write(UNIT_SRC.replace("\r\n", "\n")) + with sf.file("/tmp/_deploy_res_test3.sh", "w") as f: + f.write(script) + + for label, host, via_jump in HOSTS: + print(f"\n===== {label} ({host}) =====", flush=True) + if via_jump: + code = c.exec_command( + f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no " + f"/tmp/douyinweb-singbox.service /tmp/_deploy_res_test3.sh root@{host}:/tmp/", + timeout=90, + )[1].channel.recv_exit_status() + if code != 0: + raise SystemExit(f"scp to {label} failed: {code}") + _, o, e = c.exec_command( + f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{host} " + f"bash /tmp/_deploy_res_test3.sh", + timeout=1200, + ) + else: + _, o, e = c.exec_command("bash /tmp/_deploy_res_test3.sh", timeout=1200) + out = (o.read() + e.read()).decode("utf-8", "replace") + print(out[-14000:] if len(out) > 14000 else out, flush=True) + if "DEPLOY_OK" not in out: + raise SystemExit(f"{label} deploy failed") + + c.close() + print("\nBOTH_OK — residential OFF by default; fill SOCKS in 网络页 then enable", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/linux/build_orphan_watch.sh b/scripts/linux/build_orphan_watch.sh index 24b7e20..ea68f6b 100644 --- a/scripts/linux/build_orphan_watch.sh +++ b/scripts/linux/build_orphan_watch.sh @@ -8,16 +8,28 @@ LOG_TAG="[build-orphan-watch]" log() { printf '%s %s\n' "$LOG_TAG" "$*"; } -# 1) SWC/native binary named "usr" (Next turbopack/swc temp) -killed=0 -for p in $(pgrep -x usr 2>/dev/null || true); do +_kill_if_frontend() { + # $1=pid $2=label + local p="$1" label="$2" + local exe cwd exe=$(readlink /proc/$p/exe 2>/dev/null || true) cwd=$(readlink /proc/$p/cwd 2>/dev/null || true) case "$exe$cwd" in *douyinWEB*|*frontend*|*deleted*) - kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed usr pid=$p" + kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed $label pid=$p" ;; esac +} + +# 1) SWC/native binary named "usr" (Next turbopack/swc temp) +killed=0 +for p in $(pgrep -x usr 2>/dev/null || true); do + _kill_if_frontend "$p" usr +done + +# 1b) Fake "pm2" left in Next build cache (.d* / .r*) — not real PM2 daemon +for p in $(pgrep -x pm2 2>/dev/null || true); do + _kill_if_frontend "$p" pm2 done # 2) Bare "node" with no args (orphaned build helper) — never touch youtube-svc / next-server @@ -29,9 +41,29 @@ for p in $(pgrep -x node 2>/dev/null || true); do fi done -# 3) Stale Next temp dirs under frontend +# 2b) Any process whose CWD is a Next temp dir under frontend (.d* / .r*) if [ -d "$FRONTEND_DIR" ]; then - find "$FRONTEND_DIR" -maxdepth 1 -type d -name '.r*' -mmin +5 -print0 2>/dev/null \ + for p in $(ls -1 /proc 2>/dev/null | grep -E '^[0-9]+$' || true); do + cwd=$(readlink /proc/$p/cwd 2>/dev/null || true) + case "$cwd" in + "$FRONTEND_DIR"/.d*|"$FRONTEND_DIR"/.r*) + # Keep next-server / node server.mjs alone if they somehow land here (shouldn't) + cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null) + case "$cmd" in + *next-server*|*server.mjs*|*/.next/standalone*) + ;; + *) + kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed tempdir pid=$p cwd=$cwd" + ;; + esac + ;; + esac + done +fi + +# 3) Stale Next temp dirs under frontend (.r* and .d* build caches) +if [ -d "$FRONTEND_DIR" ]; then + find "$FRONTEND_DIR" -maxdepth 1 -type d \( -name '.r*' -o -name '.d*' \) -mmin +5 -print0 2>/dev/null \ | xargs -0 -r rm -rf fi diff --git a/scripts/linux/douyinweb-singbox.service b/scripts/linux/douyinweb-singbox.service new file mode 100644 index 0000000..b65dfa0 --- /dev/null +++ b/scripts/linux/douyinweb-singbox.service @@ -0,0 +1,24 @@ +[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 +# MUST NOT be named sing-box.service — that unit belongs to v2ray-agent. +WorkingDirectory=/opt/douyinWEB/backend +ExecStart=/usr/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] +WantedBy=multi-user.target