diff --git a/app/api/endpoints/system.py b/app/api/endpoints/system.py index 861f6c544..864a65547 100644 --- a/app/api/endpoints/system.py +++ b/app/api/endpoints/system.py @@ -39,6 +39,7 @@ from app.application.configuration import ( from app.application.database import get_database_governance from app.application.image import ImageHelper from app.application.mediaserver import get_mediaserver_configs +from app.application.messaging.image import verify_wechat_image_url from app.application.messaging.message import MessageHelper from app.application.network import get_configured_network_test_service from app.application.rules import RuleHelper @@ -331,6 +332,47 @@ async def cache_img( ) +@router.get( # type: ignore[misc] + "/notification-image", + summary="通知图片代理", + response_model=None, + response_class=Response, + responses={ + 200: { + "description": "通知图片内容", + "content": { + "image/jpeg": {"schema": {"type": "string", "format": "binary"}}, + "image/png": {"schema": {"type": "string", "format": "binary"}}, + "image/webp": {"schema": {"type": "string", "format": "binary"}}, + }, + }, + 304: {"description": "图片缓存未修改"}, + }, +) +async def notification_image( + url: str, + if_none_match: Annotated[str | None, Header()] = None, +) -> Response: + """ + 返回带企业微信通知签名的外部图片。 + + 企业微信取图请求不携带用户 Cookie,因此只接受绑定原图和用途的签名地址, + 再复用统一图片代理的域名、DNS 和图片内容校验。 + """ + source_url = verify_wechat_image_url(url) + if not source_url: + raise HTTPException(status_code=404, detail="Not Found") + + response = await fetch_image( + url=source_url, + use_cache=bool(get_runtime_settings().get("GLOBAL_IMAGE_CACHE")), + if_none_match=if_none_match, + ) + if response is None: + raise HTTPException(status_code=502, detail="Failed to fetch the image") + return response + + @router.get( "/global", summary="查询非敏感系统设置", diff --git a/app/application/messaging/image.py b/app/application/messaging/image.py new file mode 100644 index 000000000..49616b50f --- /dev/null +++ b/app/application/messaging/image.py @@ -0,0 +1,65 @@ +"""消息渠道使用的外部图片地址转换与签名能力。""" + +from __future__ import annotations + +from typing import Optional +from urllib.parse import urlparse + +from app.application.security.url import SecurityUtils +from app.foundation.url import UrlUtils +from app.runtime.settings import get_runtime_setting + +WECHAT_IMAGE_SIGNATURE_PURPOSE = "wechat-notification-image" +_WECHAT_IMAGE_PROXY_PATH = "/system/notification-image" + + +def _is_douban_image_url(image_url: str) -> bool: + """判断地址是否来自豆瓣图片 CDN,避免公开代理暴露其他资源。""" + hostname = (urlparse(image_url).hostname or "").lower().rstrip(".") + return hostname == "doubanio.com" or hostname.endswith(".doubanio.com") + + +def build_wechat_image_url(image_url: Optional[str]) -> Optional[str]: + """ + 为企业微信通知图片生成可由微信服务器访问的签名代理地址。 + + 企业微信服务器不会携带 MoviePilot 的登录 Cookie,只有配置了对外域名时 + 才能访问本地代理;未配置时保留原始地址,避免改变现有通知行为。 + """ + normalized_url = (image_url or "").strip() + if not normalized_url: + return image_url + + parsed_url = urlparse(normalized_url) + if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc: + return image_url + if not _is_douban_image_url(normalized_url): + return image_url + + try: + app_domain = str(get_runtime_setting("APP_DOMAIN") or "").strip() + api_v1_path = str(get_runtime_setting("API_V1_STR") or "/api/v1").rstrip("/") + except AttributeError: + return image_url + if not app_domain: + return image_url + + signed_url = SecurityUtils.sign_url( + normalized_url, + purpose=WECHAT_IMAGE_SIGNATURE_PURPOSE, + ) + proxy_url = UrlUtils.combine_url( + host=app_domain, + path=f"{api_v1_path}{_WECHAT_IMAGE_PROXY_PATH}", + query={"url": signed_url}, + ) + return proxy_url or image_url + + +def verify_wechat_image_url(image_url: str) -> Optional[str]: + """验证企业微信豆瓣图片代理地址并返回去签名的原始图片地址。""" + source_url = SecurityUtils.verify_signed_url( + image_url, + purpose=WECHAT_IMAGE_SIGNATURE_PURPOSE, + ) + return source_url if source_url and _is_douban_image_url(source_url) else None diff --git a/app/modules/wechat/wechat.py b/app/modules/wechat/wechat.py index 4063601cc..4c3755ed4 100644 --- a/app/modules/wechat/wechat.py +++ b/app/modules/wechat/wechat.py @@ -12,6 +12,7 @@ from app.domain.metainfo import MetaInfo from app.runtime.log import logger from app.runtime.execution import retry from app.adapters.network.http import RequestUtils +from app.application.messaging.image import build_wechat_image_url from app.foundation import size as size_tools from app.foundation.url import UrlUtils @@ -238,7 +239,7 @@ class WeChat: { "title": title, "description": text, - "picurl": image_url, + "picurl": build_wechat_image_url(image_url), "url": link } ] @@ -516,7 +517,9 @@ class WeChat: articles.append({ "title": title, "description": "", - "picurl": media.get_message_image() if index == 1 else media.get_poster_image(), + "picurl": build_wechat_image_url( + media.get_message_image() if index == 1 else media.get_poster_image() + ), "url": media.detail_link }) index += 1 @@ -570,7 +573,9 @@ class WeChat: articles.append({ "title": torrent_title, "description": torrent.description if index == 1 else "", - "picurl": mediainfo.get_message_image() if index == 1 else "", + "picurl": build_wechat_image_url( + mediainfo.get_message_image() if index == 1 else "" + ), "url": torrent.page_url }) index += 1 diff --git a/app/modules/wechat/wechatbot.py b/app/modules/wechat/wechatbot.py index 23106a938..bf60c1ca1 100644 --- a/app/modules/wechat/wechatbot.py +++ b/app/modules/wechat/wechatbot.py @@ -13,6 +13,7 @@ from Crypto.Cipher import AES from app.adapters.network.http import RequestUtils from app.application.messaging.channel.admin import matches_channel_admin +from app.application.messaging.image import build_wechat_image_url from app.application.messaging.ingress import submit_message_to_host from app.domain.context import Context, MediaInfo from app.domain.metainfo import MetaInfo @@ -556,13 +557,14 @@ class WeChatBot: text: Optional[str] = None, image: Optional[str] = None, link: Optional[str] = None) -> str: + """构造企业微信智能机器人使用的 Markdown 消息正文。""" parts = [] if title: parts.append(f"**{title}**") if text: parts.append(text.replace("\n\n", "\n")) if image: - parts.append(f"![]({image})") + parts.append(f"![]({build_wechat_image_url(image)})") if link: parts.append(f"[点击查看]({link})") return "\n\n".join(part for part in parts if part).strip() diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 19eece540..1718b7614 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -762,8 +762,8 @@ flowchart LR | 指标 | 当前值 | |---|---:| -| Python 模块 | 1104 | -| 内部导入边 | 9,304 | +| Python 模块 | 1105 | +| 内部导入边 | 9,316 | | 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 49(债务已清零,49 条精确 containment) | diff --git a/docs/refactor/optimization-checklist.md b/docs/refactor/optimization-checklist.md index 8d1f0eb6a..bc703c43d 100644 --- a/docs/refactor/optimization-checklist.md +++ b/docs/refactor/optimization-checklist.md @@ -98,7 +98,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 1104 / 9,304 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 | +| 宿主 Python 模块 / 内部依赖边 | 1105 / 9,316 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档 | | 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 923d755f1..8370a42ea 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -941,8 +941,8 @@ "runtime_only": true } }, - "edge_count": 9304, - "edge_sha256": "c5124c9dfe6371833ac0b442f91fb11cc55e5d88c4b8f08a7aae1deef50c0546", + "edge_count": 9316, + "edge_sha256": "67e1155ee7b6151823fb42cabbe48a5dc7ec611d88165668c7b0379a449931e3", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -3114,6 +3114,7 @@ "app.api.endpoints.system -> app.application.image", "app.api.endpoints.system -> app.application.mediaserver", "app.api.endpoints.system -> app.application.messaging", + "app.api.endpoints.system -> app.application.messaging.image", "app.api.endpoints.system -> app.application.messaging.message", "app.api.endpoints.system -> app.application.network", "app.api.endpoints.system -> app.application.rules", @@ -3690,6 +3691,13 @@ "app.application.messaging.chat -> app.schemas", "app.application.messaging.chat -> app.schemas.agent", "app.application.messaging.chat -> app.schemas.exception", + "app.application.messaging.image -> app.application", + "app.application.messaging.image -> app.application.security", + "app.application.messaging.image -> app.application.security.url", + "app.application.messaging.image -> app.foundation", + "app.application.messaging.image -> app.foundation.url", + "app.application.messaging.image -> app.runtime", + "app.application.messaging.image -> app.runtime.settings", "app.application.messaging.ingress -> app.runtime", "app.application.messaging.ingress -> app.runtime.log", "app.application.messaging.ingress -> app.runtime.settings", @@ -8415,6 +8423,9 @@ "app.modules.wechat.wechat -> app.adapters", "app.modules.wechat.wechat -> app.adapters.network", "app.modules.wechat.wechat -> app.adapters.network.http", + "app.modules.wechat.wechat -> app.application", + "app.modules.wechat.wechat -> app.application.messaging", + "app.modules.wechat.wechat -> app.application.messaging.image", "app.modules.wechat.wechat -> app.domain", "app.modules.wechat.wechat -> app.domain.context", "app.modules.wechat.wechat -> app.domain.metainfo", @@ -8431,6 +8442,7 @@ "app.modules.wechat.wechatbot -> app.application.messaging", "app.modules.wechat.wechatbot -> app.application.messaging.channel", "app.modules.wechat.wechatbot -> app.application.messaging.channel.admin", + "app.modules.wechat.wechatbot -> app.application.messaging.image", "app.modules.wechat.wechatbot -> app.application.messaging.ingress", "app.modules.wechat.wechatbot -> app.domain", "app.modules.wechat.wechatbot -> app.domain.context", @@ -10249,7 +10261,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 1104, + "module_count": 1105, "modules": [ "app", "app.adapters", @@ -10562,6 +10574,7 @@ "app.application.messaging.channel", "app.application.messaging.channel.admin", "app.application.messaging.chat", + "app.application.messaging.image", "app.application.messaging.ingress", "app.application.messaging.interaction", "app.application.messaging.interaction.agent", diff --git a/tests/test_api_response.py b/tests/test_api_response.py index 148b95f44..8ca23356d 100644 --- a/tests/test_api_response.py +++ b/tests/test_api_response.py @@ -677,6 +677,7 @@ def test_v1_model_free_routes_match_audited_native_allowlist(): ), ("/system/img/{proxy}", "proxy_img"), ("/system/cache/image", "cache_img"), + ("/system/notification-image", "notification_image"), ("/system/progress/{process_type}", "get_progress"), ("/system/message", "get_message"), ("/system/logging", "get_logging"), diff --git a/tests/test_wechat_notification_image.py b/tests/test_wechat_notification_image.py new file mode 100644 index 000000000..97d790c8c --- /dev/null +++ b/tests/test_wechat_notification_image.py @@ -0,0 +1,128 @@ +"""企业微信豆瓣图片代理的签名、取图和消息载荷测试。""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import AsyncMock +from urllib.parse import parse_qs, urlparse + +import pytest +from fastapi import HTTPException, Response + +from app.api.endpoints import system as system_endpoint +from app.application.messaging import image as image_urls +from app.modules.wechat.wechat import WeChat + + +def _settings_with_domain(key: str) -> Any: + """提供企业微信图片 URL 构造所需的最小运行配置。""" + return { + "APP_DOMAIN": "https://moviepilot.example", + "API_V1_STR": "/api/v1", + }[key] + + +def test_build_wechat_image_url_signs_only_douban_images(monkeypatch: pytest.MonkeyPatch) -> None: + """只为豆瓣图片生成公开代理地址,其他图片保持原始 URL。""" + monkeypatch.setattr(image_urls, "get_runtime_setting", _settings_with_domain) + source_url = "https://img9.doubanio.com/view/photo/l/public/p2932615136.webp" + + proxy_url = image_urls.build_wechat_image_url(source_url) + parsed = urlparse(proxy_url or "") + signed_source = parse_qs(parsed.query)["url"][0] + + assert parsed.scheme == "https" + assert parsed.netloc == "moviepilot.example" + assert parsed.path == "/api/v1/system/notification-image" + assert image_urls.verify_wechat_image_url(signed_source) == source_url + assert image_urls.build_wechat_image_url("https://image.tmdb.org/poster.jpg") == ( + "https://image.tmdb.org/poster.jpg" + ) + + +def test_build_wechat_image_url_keeps_original_without_public_domain( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """未配置对外域名时不生成微信无法访问的本地地址。""" + monkeypatch.setattr( + image_urls, + "get_runtime_setting", + lambda key: "" if key == "APP_DOMAIN" else "/api/v1", + ) + source_url = "https://img9.doubanio.com/view/photo/l/public/p2932615136.webp" + + assert image_urls.build_wechat_image_url(source_url) == source_url + + +@pytest.mark.asyncio +async def test_notification_image_rejects_wrong_signature_and_domain() -> None: + """公开入口拒绝错误用途签名及非豆瓣来源,避免退化为通用代理。""" + from app.application.security.url import SecurityUtils + + signed_tmdb_url = SecurityUtils.sign_url( + "https://image.tmdb.org/poster.jpg", + purpose=image_urls.WECHAT_IMAGE_SIGNATURE_PURPOSE, + ) + + with pytest.raises(HTTPException) as error: + await system_endpoint.notification_image(url=signed_tmdb_url) + + assert error.value.status_code == 404 + + +@pytest.mark.asyncio +async def test_notification_image_fetches_verified_source(monkeypatch: pytest.MonkeyPatch) -> None: + """验证通过后复用统一图片代理,并保留全局缓存和 ETag 参数。""" + from app.application.security.url import SecurityUtils + + source_url = "https://img9.doubanio.com/view/photo/l/public/p2932615136.webp" + signed_url = SecurityUtils.sign_url( + source_url, + purpose=image_urls.WECHAT_IMAGE_SIGNATURE_PURPOSE, + ) + response = Response(content=b"image", media_type="image/webp") + fetch_image = AsyncMock(return_value=response) + monkeypatch.setattr(system_endpoint, "fetch_image", fetch_image) + monkeypatch.setattr( + system_endpoint, + "get_runtime_settings", + lambda: {"GLOBAL_IMAGE_CACHE": True}, + ) + + result = await system_endpoint.notification_image( + url=signed_url, + if_none_match="etag", + ) + + assert result is response + fetch_image.assert_awaited_once_with( + url=source_url, + use_cache=True, + if_none_match="etag", + ) + + +def test_wechat_news_payload_uses_signed_douban_proxy( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """企业微信图文载荷应把豆瓣图片替换为可公开取图的地址。""" + monkeypatch.setattr(image_urls, "get_runtime_setting", _settings_with_domain) + captured: dict[str, Any] = {} + client = WeChat.__new__(WeChat) + client._appid = "1" + monkeypatch.setattr( + client, + "_WeChat__post_request", + lambda url, payload: captured.update(payload) or True, + ) + source_url = "https://img9.doubanio.com/view/photo/l/public/p2932615136.webp" + + assert client._WeChat__send_image_message( + title="奥德赛", + text="已添加订阅", + image_url=source_url, + ) is True + + image_url = captured["news"]["articles"][0]["picurl"] + signed_source = parse_qs(urlparse(image_url).query)["url"][0] + assert image_urls.verify_wechat_image_url(signed_source) == source_url