diff --git a/backend/euniv/collectors.py b/backend/euniv/collectors.py index 623fed7..1f96179 100644 --- a/backend/euniv/collectors.py +++ b/backend/euniv/collectors.py @@ -53,10 +53,7 @@ def source_title(name: str) -> str: def is_china(country: str | None) -> bool: text = (country or "").strip() - if not text: - return False - lower = text.lower() - return lower in CHINA or "中国" in text + return text == "中国" or text.lower() in {"cn", "chn", "china"} def collect_all() -> list[ProxyCandidate]: @@ -83,6 +80,10 @@ def _normalize_scheme(value: object) -> str: kind = str(value or "").strip().lower() if kind == "socks": kind = "socks5" + if kind == "socks5h": + kind = "socks5" + if kind == "https": + kind = "http" return kind if kind in SCHEMES else "" @@ -90,6 +91,12 @@ def _normalize_host(value: object) -> str: host = str(value or "").strip() if not host or "://" in host or any(ch.isspace() for ch in host): return "" + from euniv.proxy import ProxyError, assert_public_host + + try: + assert_public_host(host) + except ProxyError: + return "" return host[:255] @@ -205,7 +212,7 @@ class ProxyHubCollector(Collector): "Mcp-Method": "tools/call", "Mcp-Name": "list_proxies", } - with httpx.Client(timeout=20, follow_redirects=True) as client: + with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client: response = client.post(self.url, headers=headers, json=body) response.raise_for_status() return parse_proxyhub_result(_read_mcp(response)) diff --git a/backend/euniv/proxy.py b/backend/euniv/proxy.py index 32d4811..326bb34 100644 --- a/backend/euniv/proxy.py +++ b/backend/euniv/proxy.py @@ -2,12 +2,15 @@ from __future__ import annotations +import ipaddress +import re +import socket from urllib.parse import quote, urlparse import httpx -SCHEMES = ("http", "https", "socks4", "socks5", "socks5h") -SOCKS_SCHEMES = ("socks4", "socks5", "socks5h") +SCHEMES = ("http", "https", "socks4", "socks5") +SOCKS_SCHEMES = ("socks4", "socks5") OFF_SCHEMES = ("", "off", "none", "direct", "close") POOL_SCHEMES = ("pool", "auto") @@ -16,6 +19,55 @@ class ProxyError(ValueError): """代理配置不符合要求。""" +def canonical_scheme(scheme: str | None) -> str: + kind = (scheme or "").strip().lower() + if kind == "socks5h": + return "socks5" + return kind + + +def assert_public_host(host: str) -> None: + """手填和采集都只接受公网地址。""" + address = (host or "").strip() + if not address or any(char in address for char in "@/#?"): + raise ProxyError("代理只允许公网地址") + try: + addresses = [ipaddress.ip_address(address)] + except ValueError: + if not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"): + raise ProxyError("代理地址不合法") + try: + found = socket.getaddrinfo(address, None) + except OSError as exc: + raise ProxyError("代理地址无法解析") from exc + addresses = [] + for item in found: + try: + addresses.append(ipaddress.ip_address(item[4][0])) + except ValueError: + continue + if not addresses: + raise ProxyError("代理地址无法解析") + for ip in addresses: + if ( + ip.is_private + or ip.is_loopback + or ip.is_link_local + or ip.is_reserved + or ip.is_multicast + or ip.is_unspecified + ): + raise ProxyError("代理只允许公网地址") + + +def _host_for_url(host: str) -> str: + try: + ipaddress.IPv6Address(host) + except ValueError: + return host + return f"[{host}]" + + def parse_proxy(value: str | None) -> str | None: """把代理地址规范成内部使用的 URL。空值表示直连。""" text = (value or "").strip() @@ -24,12 +76,19 @@ def parse_proxy(value: str | None) -> str | None: if "://" not in text: text = "http://" + text parsed = urlparse(text) - scheme = (parsed.scheme or "").lower() + scheme = canonical_scheme(parsed.scheme) if scheme not in SCHEMES: raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5") if not parsed.hostname: raise ProxyError("代理地址不完整") - return text + host = _host_for_url(parsed.hostname) + auth = "" + if parsed.username: + user = quote(parsed.username, safe="") + secret = quote(parsed.password or "", safe="") + auth = f"{user}:{secret}@" + port = f":{parsed.port}" if parsed.port else "" + return f"{scheme}://{auth}{host}{port}" def build_proxy_url( @@ -46,11 +105,11 @@ def build_proxy_url( auth = f"{user}:{secret}@" else: auth = "" - return f"{scheme}://{auth}{host}:{port}" + return f"{scheme}://{auth}{_host_for_url(host)}:{port}" def validate_parts(scheme: str, host: str, port: object, username: str = "") -> tuple[str, str, int, str]: - kind = (scheme or "").strip().lower() + kind = canonical_scheme(scheme) if kind not in SCHEMES: raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5") address = (host or "").strip() @@ -97,7 +156,7 @@ def view_of(account) -> dict: on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port) return { "enabled": on, - "scheme": account.proxy_scheme if on else "off", + "scheme": canonical_scheme(account.proxy_scheme) if on else "off", "host": account.proxy_host or "", "port": int(account.proxy_port) if account.proxy_port else None, "username": account.proxy_username or "", @@ -110,7 +169,7 @@ def summary_of(account) -> str: return "自动" if not (account.proxy_scheme and account.proxy_host and account.proxy_port): return "" - return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}" + return f"{canonical_scheme(account.proxy_scheme).upper()} {account.proxy_host}:{account.proxy_port}" def url_of(account) -> str | None: @@ -138,20 +197,29 @@ def apply(account, scheme: str, host: str = "", port: object = None, username: s clear(account) account.use_proxy_pool = True return + kind, address, number, user = validate_parts(scheme, host, port, username) + assert_public_host(address) + if password is not None and len(str(password)) > 256: + raise ProxyError("代理密码过长") employee_id = getattr(account, "employee_id", "") + changed = ( + canonical_scheme(getattr(account, "proxy_scheme", "")) != kind + or (getattr(account, "proxy_host", "") or "") != address + or (getattr(account, "proxy_username", "") or "") != user + or getattr(account, "proxy_port", None) != number + ) if uses_pool(account) and employee_id: from euniv.proxy_pool import release release(str(employee_id)) account.use_proxy_pool = False - kind, address, number, user = validate_parts(scheme, host, port, username) - if password is not None and len(str(password)) > 256: - raise ProxyError("代理密码过长") account.proxy_scheme = kind account.proxy_host = address account.proxy_port = number account.proxy_username = user if password is None: + if changed: + account.proxy_password_cipher = "" return if password == "": account.proxy_password_cipher = "" @@ -201,17 +269,28 @@ def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict: def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client: + kwargs.setdefault("trust_env", False) kwargs.update(client_proxy_args(proxy)) return httpx.Client(**kwargs) def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient: + kwargs.setdefault("trust_env", False) kwargs.update(client_proxy_args(proxy, asynchronous=True)) return httpx.AsyncClient(**kwargs) def is_proxy_failure(exc: BaseException) -> bool: - if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)): - return True - text = f"{type(exc).__name__} {exc}".lower() - return "proxy" in text or "socks" in text + from python_socks import ProxyConnectionError, ProxyError as SocksProxyError, ProxyTimeoutError + + return isinstance( + exc, + ( + httpx.ProxyError, + httpx.ConnectError, + httpx.ConnectTimeout, + SocksProxyError, + ProxyConnectionError, + ProxyTimeoutError, + ), + ) diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index 0f6897c..f2c4b68 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -176,7 +176,7 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: follow_redirects=True, headers={"User-Agent": USER_AGENT}, ) as client: - for target in PROBE_URLS: + for target in (PROBE_URL,): started = time.perf_counter() try: response = client.get(target) @@ -201,6 +201,21 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: return True, average, "" +def _direct_reaches_target() -> bool: + """节点全灭时对照直连,区分代理故障和目标站故障。""" + try: + with sync_httpx_client( + None, + timeout=LATENCY_LIMIT, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + ) as client: + response = client.get(PROBE_URL) + return response.status_code < 500 + except Exception: + return False + + def _short_reason(exc: BaseException) -> str: from python_socks import ProxyConnectionError, ProxyTimeoutError @@ -360,6 +375,12 @@ def _refresh_body() -> dict: ] results = _probe_many(snapshot) + probed = len(results) + failed = sum(1 for _node_id, ok, _latency, _reason in results if not ok) + if probed >= 3 and failed == probed and not _direct_reaches_target(): + results = [] + elif probed < 3: + results = [row for row in results if row[1]] with SessionLocal() as db, _assign_lock: sync = _sync_row(db) for node_id, ok, latency, reason in results: @@ -378,6 +399,7 @@ def _refresh_body() -> dict: _evict_node(node.id) sync.checked_at = _now() sync.running = False + db.flush() _store_counts(db, sync) if sync.alive_count: sync.message = "" diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index ffb21f9..a0dce5e 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -712,7 +712,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: json={ "employee_ids": ["p1-user", "p2-user"], "scheme": "socks5", - "host": "127.0.0.1", + "host": "8.8.8.8", "port": 1080, "username": "u", "password": "secret", @@ -723,7 +723,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: listed = client.get("/api/admin/users").json() one = next(item for item in listed if item["employee_id"] == "p1-user") assert one["has_proxy"] is True - assert one["proxy"] == "SOCKS5 127.0.0.1:1080" + assert one["proxy"] == "SOCKS5 8.8.8.8:1080" detail = client.get("/api/admin/users/p1-user/proxy") assert detail.status_code == 200 assert detail.json()["username"] == "u" @@ -741,7 +741,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: json={ "employee_ids": ["p1-user"], "scheme": "http", - "host": "10.0.0.1", + "host": "1.1.1.1", "port": 8080, "username": "", "password": "", @@ -750,7 +750,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: assert no_auth.status_code == 200 listed = client.get("/api/admin/users").json() one = next(item for item in listed if item["employee_id"] == "p1-user") - assert one["proxy"] == "HTTP 10.0.0.1:8080" + assert one["proxy"] == "HTTP 1.1.1.1:8080" detail = client.get("/api/admin/users/p1-user/proxy") assert detail.json()["has_password"] is False assert detail.json()["username"] == "" @@ -833,7 +833,7 @@ def test_admin_can_turn_off_proxy_with_scheme() -> None: assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 client.put( "/api/admin/users/proxy", - json={"employee_ids": ["off-user"], "scheme": "http", "host": "10.0.0.1", "port": 8080}, + json={"employee_ids": ["off-user"], "scheme": "http", "host": "1.1.1.1", "port": 8080}, ) listed = client.get("/api/admin/users").json() one = next(item for item in listed if item["employee_id"] == "off-user") @@ -893,7 +893,7 @@ def test_admin_can_save_study_settings_in_one_request() -> None: "second": 11, "workers": 2, "scheme": "http", - "host": "10.0.0.8", + "host": "9.9.9.9", "port": 8080, "username": "", "password": "", @@ -905,7 +905,7 @@ def test_admin_can_save_study_settings_in_one_request() -> None: assert one["monthly_target"] == 120 assert one["study_start"] == "每月8日 09:10:11" assert one["course_workers"] == 2 - assert one["proxy"] == "HTTP 10.0.0.8:8080" + assert one["proxy"] == "HTTP 9.9.9.9:8080" def test_admin_can_switch_hours_source() -> None: diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 2e8d8d0..1a446d5 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -545,27 +545,27 @@ def test_user_can_set_proxy_with_or_without_password() -> None: assert "password" not in empty.json() saved = client.put( "/api/settings/proxy", - json={"scheme": "http", "host": "10.0.0.1", "port": 8080, "username": "", "password": ""}, + json={"scheme": "http", "host": "1.1.1.1", "port": 8080, "username": "", "password": ""}, ) assert saved.status_code == 200 assert saved.json() == { "enabled": True, "scheme": "http", - "host": "10.0.0.1", + "host": "1.1.1.1", "port": 8080, "username": "", "has_password": False, } with_auth = client.put( "/api/settings/proxy", - json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": "p@ss"}, + json={"scheme": "socks5", "host": "8.8.8.8", "port": 1080, "username": "u", "password": "p@ss"}, ) assert with_auth.status_code == 200 assert with_auth.json()["has_password"] is True assert "password" not in with_auth.json() kept = client.put( "/api/settings/proxy", - json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": None}, + json={"scheme": "socks5", "host": "8.8.8.8", "port": 1080, "username": "u", "password": None}, ) assert kept.status_code == 200 assert kept.json()["has_password"] is True diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 61465ea..e8461be 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -705,7 +705,7 @@ def test_proxy_pool_scheme_enables_auto() -> None: assert view["enabled"] is True assert view["scheme"] == "pool" assert account.use_proxy_pool is True - apply_proxy(account, "http", "10.0.0.1", 8080) + apply_proxy(account, "http", "1.1.1.1", 8080) assert account.use_proxy_pool is False assert proxy_view(account)["scheme"] == "http" diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index 57aa5ac..d0e59b6 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -9,7 +9,7 @@ from euniv.db import SessionLocal from euniv.models import Account, ProxyNode from euniv.proxy import apply as apply_proxy from euniv.proxy import bind_url, is_proxy_failure, view_of -from euniv.proxy_pool import PROBE_URLS, acquire, mark_failed, page, probe, refresh_once, release +from euniv.proxy_pool import PROBE_URL, acquire, mark_failed, page, probe, refresh_once, release from euniv.proxy_pool import _holds INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"] @@ -127,13 +127,13 @@ def test_bind_url_uses_pool_or_manual() -> None: manual_user = db.get(Account, "manual-user") assert pool_user is not None and manual_user is not None apply_proxy(pool_user, "pool") - apply_proxy(manual_user, "http", "127.0.0.1", 7890) + apply_proxy(manual_user, "http", "1.1.1.1", 7890) db.commit() db.refresh(pool_user) db.refresh(manual_user) assert view_of(pool_user)["scheme"] == "pool" assert bind_url(pool_user) == "http://10.0.0.4:8004" - assert bind_url(manual_user) == "http://127.0.0.1:7890" + assert bind_url(manual_user) == "http://1.1.1.1:7890" apply_proxy(pool_user, "off") db.commit() db.refresh(pool_user) @@ -147,6 +147,7 @@ def test_refresh_marks_slow_and_keeps_fast(monkeypatch) -> None: lambda: [ ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "proxyhub"), ProxyCandidate("http", "2.2.2.2", 80, "cn", "elite", "proxyhub"), + ProxyCandidate("http", "4.4.4.4", 80, "cn", "elite", "proxyhub"), ProxyCandidate("http", "3.3.3.3", 80, "us", "elite", "proxyhub"), ], ) @@ -159,7 +160,8 @@ def test_refresh_marks_slow_and_keeps_fast(monkeypatch) -> None: monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) payload = refresh_once() assert payload["alive"] == 1 - assert payload["dead"] == 1 + assert payload["dead"] == 2 + assert payload["message"] == "" with SessionLocal() as db: listed = page(db) hosts = {item["host"]: item for item in listed["items"]} @@ -240,13 +242,13 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None: seen.append(url) return FakeResponse() - ticks = iter([0.0, 0.12, 0.12, 0.34, 0.34, 0.64]) + ticks = iter([0.0, 0.12]) monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient) monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) - ok, latency, reason = probe("http", "10.0.0.9", 8080) - assert seen == list(PROBE_URLS) + ok, latency, reason = probe("http", "1.1.1.1", 8080) + assert seen == [PROBE_URL] assert ok is True - assert latency == 213 + assert latency == 120 assert reason == "" @@ -264,7 +266,7 @@ def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None: def get(self, _url: str): raise httpx.ConnectError("boom") - ticks = iter([0.0, 0.012, 0.012, 0.018, 0.018, 0.025]) + ticks = iter([0.0, 0.008]) monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient) monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) ok, latency, reason = probe("socks4", "10.0.0.9", 1080)