Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(config): PikPak 整理与浏览器控制接口不再落到系统代理

longmeidao78c0bd0ee8cb
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 1bd83649c..b098b7d9c 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -118,6 +118,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_review_csv.py", "test_jav_code_domain.py", "test_organize.py",
"test_link_repair.py", "test_tag_management.py",
"test_subprocess_encoding.py", "test_module_layering.py",
+ "test_outbound_proxy_policy.py", "test_network_reachability.py",
"test_copy_final_state.py", "test_demo_dataset.py",
"test_cloudflared_packaging.py", "test_tunnel.py", "test_process_job.py",
"test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py", "test_macos_media.py",
@@ -145,7 +146,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_migrations.py", "test_ledger_revision.py",
"test_platform.py", "test_mount.py", "test_tray.py", "test_certs.py",
"test_folder_picker.py", "test_fsutil.py", "test_runtime_consistency.py",
- "test_subprocess_encoding.py", "test_windows_update.py", "test_buildinfo.py"),
+ "test_subprocess_encoding.py", "test_outbound_proxy_policy.py", "test_windows_update.py", "test_buildinfo.py"),
"packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py", "test_macos_standalone.py",
"test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py",
"test_cloudflared_packaging.py", "test_desktop_installer.py",
diff --git a/src/peach/browser_transport.py b/src/peach/browser_transport.py
index 018a923cc..7b67b57c2 100644
--- a/src/peach/browser_transport.py
+++ b/src/peach/browser_transport.py
@@ -222,7 +222,9 @@ class _WebSocket:
def _targets(port: int) -> list[dict]:
- with urllib.request.urlopen(f"http://127.0.0.1:{port}/json", timeout=10) as response:
+ # 回环 DevTools 端口不经任何代理;裸 urlopen 读系统代理,绕过名单没列 127.0.0.1 时会被代理接走。
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ with opener.open(f"http://127.0.0.1:{port}/json", timeout=10) as response:
return json.load(response)
diff --git a/src/peach/organize_clouddrive.py b/src/peach/organize_clouddrive.py
index 345207a05..f9712b957 100644
--- a/src/peach/organize_clouddrive.py
+++ b/src/peach/organize_clouddrive.py
@@ -22,6 +22,7 @@ from .downloads_clouddrive import CloudDriveClient, SERVICE, discover
from .downloads import CLOUDDRIVE_CREDENTIAL, DownloadSettings
from .follow_secrets import CredentialStore
from .config import DATABASE_PATH, SECRETS_DIR, STATE_DIR
+from .peach_proxy import http_client
from .scripting import open_readonly
MAX_RESPONSE = 2 * 1024 * 1024
@@ -378,7 +379,7 @@ def pikpak_renames(sample_path: str, roots):
if info is None or info.CloudAPI.name.casefold() != 'webdav':
raise ValueError('既有 PikPak WebDAV 来源未取得')
headers = _download_headers(cloud, sample_path)
- with httpx.Client(headers=headers, timeout=20, follow_redirects=False) as http:
+ with http_client(root=SECRETS_DIR, headers=headers, timeout=20, follow_redirects=False) as http:
dav = PikPakDav(http, 'A:\\', lambda path: _refresh_listing(cloud, path),
listing=lambda path: _cloud_listing(cloud, path),
rename=lambda source, target: _rename_remote(cloud, source, target),
diff --git a/tests/test_outbound_proxy_policy.py b/tests/test_outbound_proxy_policy.py
new file mode 100644
index 000000000..e1ec6afa6
--- /dev/null
+++ b/tests/test_outbound_proxy_policy.py
@@ -0,0 +1,69 @@
+"""出网客户端必须写明代理边界,不许默认落到系统代理。
+
+Peach 代理设置(`peach_proxy`)有跟随系统、直连、自定义代理三种。httpx 不写
+`trust_env`、curl_cffi 不写 `trust_env`、`urllib.request.urlopen` 都会悄悄读取环境
+变量与 Windows 系统代理:用户在配置页选了直连或自定义代理,这些请求照样走系统代理。
+
+所以 `src/peach` 里每个客户端构造都要二选一:
+- 用 `**` 展开 Peach 代理设置(`peach_proxy.client_options()`、`curl_options()`,
+ 或由它们组装出的选项);
+- 写明 `trust_env=False`:只给回环、局域网服务与注入的传输用。
+`urlopen` 一律不用,回环请求用 `build_opener(ProxyHandler({}))`,外网走
+`peach_proxy.read_url`;`build_opener` 必须带 `ProxyHandler`。
+"""
+from __future__ import annotations
+
+import ast
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SOURCE = ROOT / "src" / "peach"
+#: 会读环境代理的客户端构造:httpx 的 Client 与模块级快捷函数、curl_cffi 的 Session。
+CLIENTS = {"Client", "AsyncClient", "Session", "get", "post", "put", "delete", "head", "stream", "request"}
+OWNERS = {"httpx", "requests", "curl_requests"}
+
+
+def violations(tree: ast.AST) -> list[tuple[int, str]]:
+ found = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ name = ast.unparse(node.func)
+ owner, _, attr = name.rpartition(".")
+ if name.endswith("urlopen"):
+ found.append((node.lineno, "urlopen 会读系统代理"))
+ elif attr == "build_opener":
+ if not any(isinstance(arg, ast.Call) and ast.unparse(arg.func).endswith("ProxyHandler")
+ for arg in node.args):
+ found.append((node.lineno, "build_opener 没有 ProxyHandler"))
+ elif owner.rpartition(".")[2] in OWNERS and attr in CLIENTS:
+ spread = any(keyword.arg is None for keyword in node.keywords)
+ direct = any(keyword.arg == "trust_env" and isinstance(keyword.value, ast.Constant)
+ and keyword.value.value is False for keyword in node.keywords)
+ if not (spread or direct):
+ found.append((node.lineno, f"{name} 没有展开 Peach 代理设置,也没写 trust_env=False"))
+ return found
+
+
+class OutboundProxyPolicyTest(unittest.TestCase):
+ def test_every_client_states_its_proxy_boundary(self):
+ problems = [f"{path.relative_to(ROOT).as_posix()}:{line} {reason}"
+ for path in sorted(SOURCE.rglob("*.py"))
+ for line, reason in violations(ast.parse(path.read_text(encoding="utf-8")))]
+ self.assertEqual(problems, [])
+
+ def test_scanner_flags_default_clients(self):
+ tree = ast.parse("import httpx, urllib.request\n"
+ "httpx.Client(timeout=3)\n"
+ "httpx.get('https://example.com')\n"
+ "urllib.request.urlopen('http://127.0.0.1')\n"
+ "urllib.request.build_opener()\n"
+ "httpx.Client(**options)\n"
+ "httpx.get('http://127.0.0.1', trust_env=False)\n"
+ "urllib.request.build_opener(urllib.request.ProxyHandler({}))\n")
+ self.assertEqual([line for line, _ in violations(tree)], [2, 3, 4, 5])
+
+
+if __name__ == "__main__":
+ unittest.main()