Peach: Local-first video metadata scraper and media manager.
refactor(web): 共用本机访问判断并隔离路由依赖
longmeidao121a6ad87cc5
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 620c319fa..b05536092 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -283,7 +283,7 @@ JAV 作品详情与馆藏视频共用 `IdentityCell` 的头像、标识和首字清晰度控件复用 Video.js 10.1.0 官方 `@videojs/hlsjs-video` 的 hls.js 引擎。多档播放从实际轨道读取分辨率,自动码率和固定轨道通过引擎选择;单档 HLS 缺少尺寸时读取原生视频元素的实际尺寸,并响应 `loadedmetadata`、`resize`。尺寸未取得时显示「当前画质」,轨道 ID 不作界面名称。来源各自独立的 MP4 档位由 Peach 保留播放位置后切换片源。-画面旋转复用浏览器 CSS `transform` 与 `ResizeObserver`;Peach 仅计算保持比例的显示尺寸、设置菜单及会话释放。采用现有 Video.js 10.1.0,不增加依赖;依赖旧版组件接口的旋转插件不进入运行时。本地播放器复用 Python 标准库 `os.startfile`、`subprocess` 和 macOS `/usr/bin/open`,保留固定播放器名单、媒体根授权、本机直连与 Docker 边界。媒体路径复用 `media.normalized_path`,Windows 保留可直接读取的挂载盘盘符,不向虚拟文件系统请求最终路径。系统能力随 Python/操作系统发布,无额外许可证或包体积;真实桌面应用唤起与浏览器协议支持分别验收,不能由进程请求成功推断解码成功。用法与上游依据见[外部播放器](EXTERNAL_PLAYERS.md)。+画面旋转复用浏览器 CSS `transform` 与 `ResizeObserver`;Peach 仅计算保持比例的显示尺寸、设置菜单及会话释放。采用现有 Video.js 10.1.0,不增加依赖;依赖旧版组件接口的旋转插件不进入运行时。本地播放器复用 Python 标准库 `os.startfile`、`subprocess` 和 macOS `/usr/bin/open`,保留固定播放器名单、媒体根授权、本机直连与 Docker 边界。本机请求判断由 `web_local_access` 供配置与媒体路由共用。媒体路径复用 `media.normalized_path`,Windows 保留可直接读取的挂载盘盘符,不向虚拟文件系统请求最终路径。系统能力随 Python/操作系统发布,无额外许可证或包体积;真实桌面应用唤起与浏览器协议支持分别验收,不能由进程请求成功推断解码成功。用法与上游依据见[外部播放器](EXTERNAL_PLAYERS.md)。播放器按 [Video.js 10 官方迁移指南](https://videojs.org/docs/framework/html/guides/migrate-from-video-js-8) 和 [10.1.0 源码](https://github.com/videojs/video.js/tree/919ad955a9baf2433c68aba8151654dde0e58b5d/packages)接入 `video-player`、`media-container`、官方按钮/滑条与 HLS/DASH 媒体组件。`@videojs/cdn` 10.1.0(Apache-2.0)提供固定 ESM 模块,构建脚本按静态与字面量动态导入闭包分发并登记哈希;浏览器支持沿用项目目标。Peach 保留片源授权、时长口径、统计、字幕菜单和舞台生命周期,原生视频经 `media` 插槽携带字幕与观看上报。`video.js` 10.1.0 包的旧入口只有带错误码的 shim,不作为运行依赖;v8 的组件和 VHS 不进入产物。真实短片回归覆盖 MP4、HLS 和 DASH 解码,质量档位选择按 HLS 引擎验证,DASH 不声明手动档位能力。生产切换与 ledger 不属于依赖接管工作树。diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.pyindex aecd34003..46a73966a 100644--- a/src/peach/routes_configuration.py+++ b/src/peach/routes_configuration.py@@ -10,7 +10,6 @@ from __future__ import annotationsfrom dataclasses import replacefrom collections import dequeimport hashlib-import ipaddressimport osimport shutilimport threading@@ -26,6 +25,7 @@ from . import (access, data_storage, distribution, entry_links, folder_picker, mpush_discovery, settings_file, media_configuration, tunnel, web_downloads)from .routes_auth import require_auth, require_authenticated_client, same_originfrom .web_entry import runtime_fact_entries+from .web_local_access import local_client, managed_configurationfrom . import release_updates, standalone_update, peach_proxy, desktop_startup, desktop_uninstallrouter = APIRouter()@@ -35,12 +35,6 @@ RELOAD_NAME = onboarding.RELOAD_NAMEFILE_MANAGED_NOTICE = "这个部署由配置文件管理服务;在本机编辑下方的设置文件。"-def managed_configuration() -> bool:- """托盘或无桌面入口负责消费配置保存后的重载标记。"""- return (distribution.standalone() or os.environ.get("PEACH_TRAY_MANAGED") == "1"- or os.environ.get("PEACH_HEADLESS_MANAGED") == "1")--def dev_environment() -> bool:"""调试用的裸 serve:`--no-auth` 启动时由 CLI 置上 `PEACH_DEV=1`。@@ -55,49 +49,6 @@ def revision(config) -> str:return hashlib.sha256(config.path.read_bytes()).hexdigest()-def tunnel_forwarded(request: Request) -> bool:- """隧道在跑时,带 Cloudflare 转发头的请求一律按公网来源处理。-- cloudflared 从本机回环连进来,源 IP 与本机浏览器完全一样;转发头是唯一能把- 两者分开的证据,宁可把伪造了这些头的本机请求挡在配置页外面。- """- return tunnel.from_edge(getattr(request.app.state, "tunnel", None), request.headers)---def local_client(request: Request) -> bool:- """按 IP 检查管理请求;桌面限本机,Docker 允许本机与私有网络,拒绝代理转发。"""- if not request.client or tunnel_forwarded(request):- return False- server = request.scope.get("server")- try:- peer = ipaddress.ip_address(request.client.host)- bound = ipaddress.ip_address(server[0]) if server else None- except ValueError:- # ASGI 测试或非 IP 绑定没有可比较的服务端 IP;回环客户端仍可识别。- bound = None- try:- peer = ipaddress.ip_address(request.client.host)- except ValueError:- return False- if os.environ.get("PEACH_HEADLESS_MANAGED") == "1":- if any(header.startswith("x-forwarded-") or header in {"forwarded", "cf-connecting-ip"}- for header in request.headers):- return False- return peer.is_loopback or (peer.is_private and not any((- peer.is_link_local, peer.is_reserved, peer.is_unspecified, peer.is_multicast,- )))- if not peer.is_loopback and (peer != bound or peer.is_unspecified):- return False- if managed_configuration():- name = request.app.state.settings.mdns_name.lower().removesuffix(".local")- hosts = {"127.0.0.1", "localhost", "::1", f"{name}.local"}- if bound and not bound.is_unspecified:- hosts.add(str(bound))- if (request.url.hostname or "").lower().rstrip(".") not in hosts:- return False- return True--def local_only(request: Request) -> None:if not local_client(request):raise HTTPException(403, "请在运行 Peach 的电脑上打开配置")diff --git a/src/peach/routes_media.py b/src/peach/routes_media.pyindex d2090d232..3f200dc1c 100644--- a/src/peach/routes_media.py+++ b/src/peach/routes_media.py@@ -220,7 +220,7 @@ def local_players(request: Request, args=Depends(require_auth)):def _local_playback_client(request: Request) -> bool:- from .routes_configuration import local_client+ from .web_local_access import local_clientreturn local_client(request) and not any(key.startswith('x-forwarded-') or key in {'forwarded', 'cf-connecting-ip'} for key in request.headers)diff --git a/src/peach/web_local_access.py b/src/peach/web_local_access.pynew file mode 100644index 000000000..1b1c2b6ce--- /dev/null+++ b/src/peach/web_local_access.py@@ -0,0 +1,53 @@+"""Web 请求的本机访问判断;配置与本地播放器共用。"""+from __future__ import annotations++import ipaddress+import os++from fastapi import Request++from . import distribution, tunnel+++def managed_configuration() -> bool:+ """托盘或无桌面入口负责消费配置保存后的重载标记。"""+ return (distribution.standalone() or os.environ.get("PEACH_TRAY_MANAGED") == "1"+ or os.environ.get("PEACH_HEADLESS_MANAGED") == "1")+++def tunnel_forwarded(request: Request) -> bool:+ """隧道转发请求按公网来源处理。"""+ return tunnel.from_edge(getattr(request.app.state, "tunnel", None), request.headers)+++def local_client(request: Request) -> bool:+ """桌面限本机,Docker 允许本机与私有网络,拒绝代理转发。"""+ if not request.client or tunnel_forwarded(request):+ return False+ server = request.scope.get("server")+ try:+ peer = ipaddress.ip_address(request.client.host)+ bound = ipaddress.ip_address(server[0]) if server else None+ except ValueError:+ bound = None+ try:+ peer = ipaddress.ip_address(request.client.host)+ except ValueError:+ return False+ if os.environ.get("PEACH_HEADLESS_MANAGED") == "1":+ if any(header.startswith("x-forwarded-") or header in {"forwarded", "cf-connecting-ip"}+ for header in request.headers):+ return False+ return peer.is_loopback or (peer.is_private and not any((+ peer.is_link_local, peer.is_reserved, peer.is_unspecified, peer.is_multicast,+ )))+ if not peer.is_loopback and (peer != bound or peer.is_unspecified):+ return False+ if managed_configuration():+ name = request.app.state.settings.mdns_name.lower().removesuffix(".local")+ hosts = {"127.0.0.1", "localhost", "::1", f"{name}.local"}+ if bound and not bound.is_unspecified:+ hosts.add(str(bound))+ if (request.url.hostname or "").lower().rstrip(".") not in hosts:+ return False+ return Truediff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 2a0b02163..85f26812d 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -2869,7 +2869,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual((await self.client.get('/api/local-players')).status_code, 401)with patch.object(local_playback, 'available', return_value=True), \patch.object(local_playback, 'installed', return_value={'vlc': ('VLC', '/private/vlc')}), \- patch('peach.routes_configuration.local_client', return_value=True), \+ patch('peach.web_local_access.local_client', return_value=True), \patch.object(local_playback, 'open_media') as launch:options = await self.client.get('/api/local-players', headers=headers)self.assertEqual(options.json(), {'players': [