# -*- coding: utf-8 -*- """Global SOCKS5 via local sing-box mixed inbound (Linux best practice). Architecture: App / FFmpeg / Neko / httpx → 127.0.0.1:MIXED_PORT (HTTP+SOCKS) ↓ sing-box remote static residential SOCKS5 When disabled: sing-box stopped, no proxy env injected — direct egress. """ from __future__ import annotations import uuid from typing import Any from urllib.parse import quote from .config import BACKEND DEFAULT_PROFILE_ID = "residential-1" LOCAL_MIXED_HOST = "127.0.0.1" LOCAL_MIXED_PORT = 17891 CONFIG_DIR = BACKEND.parent / "config" SINGBOX_CONFIG_PATH = CONFIG_DIR / "sing-box.json" DEFAULT_PROFILES: list[dict[str, Any]] = [] # Fresh installs start with zero SOCKS profiles — operators add their own. # Never ship another project's residential credentials here. # Legacy DB keys kept in sync on save. _LEGACY_ENABLED_KEY = "shorts_upload_socks_enabled" _LEGACY_PROFILE_ID_KEY = "shorts_upload_socks_profile_id" _LEGACY_PROFILES_KEY = "shorts_upload_socks_profiles" _ENABLED_KEY = "global_socks_enabled" _PROFILE_ID_KEY = "global_socks_profile_id" _PROFILES_KEY = "global_socks_profiles" def _norm_profile(raw: Any) -> dict[str, Any] | None: if not isinstance(raw, dict): return None pid = str(raw.get("id") or "").strip() or str(uuid.uuid4()) server = str(raw.get("server") or "").strip() try: port = int(raw.get("port") or 0) except Exception: port = 0 ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5" if ptype not in {"socks5", "socks5h"}: ptype = "socks5" return { "id": pid, "label": str(raw.get("label") or server or pid).strip() or pid, "type": ptype, "server": server, "port": port, "username": str(raw.get("username") or ""), "password": str(raw.get("password") or ""), } def _settings_dict(cfg: dict[str, Any] | None = None) -> dict[str, Any]: if cfg is not None: return dict(cfg) from . import db return dict(db.get_settings_map()) def is_global_socks_enabled(cfg: dict[str, Any] | None = None) -> bool: settings = _settings_dict(cfg) if settings.get(_ENABLED_KEY) is not None: return bool(settings.get(_ENABLED_KEY)) return bool(settings.get(_LEGACY_ENABLED_KEY)) def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]: settings = _settings_dict(cfg) raw = settings.get(_PROFILES_KEY) if not isinstance(raw, list) or not raw: raw = settings.get(_LEGACY_PROFILES_KEY) rows: list[dict[str, Any]] = [] if isinstance(raw, list): for item in raw: p = _norm_profile(item) if p and p["server"] and p["port"] > 0: rows.append(p) if not rows: rows = [dict(x) for x in DEFAULT_PROFILES] if not public: return rows out = [] for p in rows: pwd = str(p.get("password") or "") q = dict(p) q["has_password"] = bool(pwd.strip()) q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "") out.append(q) return out def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None: pid = str(profile_id or "").strip() for p in list_socks_profiles(cfg, public=False): if str(p.get("id") or "") == pid: return p return None def active_profile_id(cfg: dict[str, Any] | None = None) -> str: settings = _settings_dict(cfg) pid = str(settings.get(_PROFILE_ID_KEY) or settings.get(_LEGACY_PROFILE_ID_KEY) or "").strip() if pid: return pid rows = list_socks_profiles(cfg, public=False) if rows: return str(rows[0].get("id") or "").strip() return "" def active_profile(cfg: dict[str, Any] | None = None) -> dict[str, Any] | None: prof = get_socks_profile(active_profile_id(cfg), cfg) if prof: return prof rows = list_socks_profiles(cfg, public=False) return rows[0] if rows else None def upstream_socks_url(profile: dict[str, Any] | None) -> str: """Direct socks5h URL to residential provider (sing-box upstream).""" if not profile: return "" server = str(profile.get("server") or "").strip() try: port = int(profile.get("port") or 0) except Exception: port = 0 if not server or port <= 0: return "" user = str(profile.get("username") or "") pwd = str(profile.get("password") or "") if user or pwd: return f"socks5h://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}" return f"socks5h://{server}:{port}" def local_mixed_url() -> str: """Local sing-box mixed inbound — preferred for httpx / curl / ffmpeg -http_proxy.""" return f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}" def local_socks_url() -> str: return f"socks5://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}" def resolve_app_proxy(cfg: dict[str, Any] | None = None) -> str: """Return local mixed proxy URL when global SOCKS is on and sing-box is up; else ''.""" if not is_global_socks_enabled(cfg): return "" from . import singbox_manager if not singbox_manager.is_running(): # Best-effort start (settings save should have started it already). try: singbox_manager.apply_from_settings(cfg) except Exception: pass if singbox_manager.is_running(): return local_mixed_url() # Fallback: direct socks5h if sing-box binary missing. return upstream_socks_url(active_profile(cfg)) def httpx_proxy(cfg: dict[str, Any] | None = None) -> str | None: url = resolve_app_proxy(cfg) return url or None def requests_proxies(cfg: dict[str, Any] | None = None) -> dict[str, str]: url = resolve_app_proxy(cfg) if not url: return {} return {"http": url, "https": url} def subprocess_env(cfg: dict[str, Any] | None = None, base: dict[str, str] | None = None) -> dict[str, str]: """Linux convention: ALL_PROXY / HTTP_PROXY / HTTPS_PROXY for child processes.""" env = dict(base or {}) url = resolve_app_proxy(cfg) if not url: for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): env.pop(key, None) return env env["HTTP_PROXY"] = url env["HTTPS_PROXY"] = url env["ALL_PROXY"] = local_socks_url() env["http_proxy"] = url env["https_proxy"] = url env["all_proxy"] = local_socks_url() # Never proxy loopback / local services. no_proxy = "127.0.0.1,localhost,::1" env["NO_PROXY"] = no_proxy env["no_proxy"] = no_proxy return env def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str: """Chromium proxy for Neko containers — delegates to egress_hub.""" try: from . import egress_hub return egress_hub.neko_browser_proxy(cfg) except Exception: return resolve_app_proxy(cfg) if is_global_socks_enabled(cfg) else "" def merge_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]: existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)} out: list[dict[str, Any]] = [] if not isinstance(incoming, list): return list(existing.values()) or [dict(x) for x in DEFAULT_PROFILES] # Explicit empty list clears all profiles (fresh install / wipe). if len(incoming) == 0: return [] for item in incoming: p = _norm_profile(item) if not p: continue pid = str(p["id"]) old = existing.get(pid) or {} pwd = str(p.get("password") or "") if (not pwd.strip()) or pwd.startswith("***"): p["password"] = str(old.get("password") or "") if not p["server"] or int(p.get("port") or 0) <= 0: continue out.append(p) return out or [dict(x) for x in DEFAULT_PROFILES] def normalize_settings_patch(patch: dict[str, Any], existing: dict[str, Any] | None = None) -> dict[str, Any]: """Sync global + legacy keys; apply sing-box when toggled.""" out = dict(patch) ex = dict(existing or {}) # Accept either global_* or legacy shorts_upload_socks_* from UI. if "global_socks_enabled" in out: out[_LEGACY_ENABLED_KEY] = bool(out["global_socks_enabled"]) elif _LEGACY_ENABLED_KEY in out: out["global_socks_enabled"] = bool(out[_LEGACY_ENABLED_KEY]) if "global_socks_profile_id" in out: out[_LEGACY_PROFILE_ID_KEY] = str(out["global_socks_profile_id"] or "") elif _LEGACY_PROFILE_ID_KEY in out: out["global_socks_profile_id"] = str(out[_LEGACY_PROFILE_ID_KEY] or "") if "global_socks_profiles" in out: merged = merge_profiles_patch(out.get("global_socks_profiles"), ex) out["global_socks_profiles"] = merged out[_LEGACY_PROFILES_KEY] = merged elif _LEGACY_PROFILES_KEY in out: merged = merge_profiles_patch(out.get(_LEGACY_PROFILES_KEY), ex) out["global_socks_profiles"] = merged out[_LEGACY_PROFILES_KEY] = merged return out def apply_runtime(cfg: dict[str, Any] | None = None) -> dict[str, Any]: from . import singbox_manager return singbox_manager.apply_from_settings(cfg) def public_settings(cfg: dict[str, Any]) -> dict[str, Any]: from . import singbox_manager enabled = is_global_socks_enabled(cfg) st = singbox_manager.status() return { "global_socks_enabled": enabled, "global_socks_profile_id": active_profile_id(cfg), "global_socks_profiles": list_socks_profiles(cfg, public=True), "global_socks_local_mixed": local_mixed_url(), "global_socks_engine": "sing-box", "global_socks_running": bool(st.get("running")), "global_socks_error": str(st.get("error") or ""), # Legacy aliases for older UI / API clients. "shorts_upload_socks_enabled": enabled, "shorts_upload_socks_profile_id": active_profile_id(cfg), "shorts_upload_socks_profiles": list_socks_profiles(cfg, public=True), }