feat(notification): relay AppPush through private MoviePilot Server

This commit is contained in:
jxxghp
2026-10-24 07:14:42 +08:00
parent d62e9ba579
commit 3ac7526930
20 changed files with 515 additions and 9 deletions

View File

@@ -195,6 +195,39 @@ class MoviePilotServerHelper:
_user_uid: Optional[str] = None
_github_user: Optional[str] = None
@staticmethod
def relay_push(server: str, key: str, method: str, path: str, data: dict[str, Any]) -> dict[str, Any]:
"""
向显式配置的私有 Server 转发通知,发送密钥只放请求头且不跟随重定向。
:param server: 管理员配置的 HTTPS 中转地址;本机联调允许回环 HTTP
:param key: 该实例专用的中转发送密钥
:param method: 内部限定的 GET、POST 或 DELETE 方法
:param path: 内部限定的 push 接口路径
:param data: 已绑定当前用户的注册或消息数据
:return: Server 返回的对象;失败抛出不含凭据或原始响应的 ValueError
"""
target = urlsplit(server)
local = target.hostname in {"localhost", "127.0.0.1", "::1"}
if (target.scheme != "https" and not (local and target.scheme == "http")) or not target.hostname or target.username or target.password or target.query or target.fragment:
raise ValueError("中转地址必须使用 HTTPS,本机回环调试除外")
if method not in {"GET", "POST", "DELETE"} or path not in {"devices", "pairings", "messages"}:
raise ValueError("不支持的通知接口")
if len(key) < 32:
raise ValueError("请配置至少 32 位的中转发送密钥")
response = RequestUtils(timeout=60, headers={"Authorization": f"Bearer {key}"}).request(
method, f"{server.rstrip('/')}/push/{path}", allow_redirects=False, verify=True,
params=data if method == "GET" else None,
json=data if method != "GET" else None,
)
if response is None or response.status_code != 200:
code = response.status_code if response is not None else 0
raise ValueError(f"私有通知服务请求失败({code})")
try:
return _response_mapping(response)
except ValueError as error:
raise ValueError("私有通知服务响应无效") from error
@classmethod
def _report_service(cls) -> ServerReportService:
"""

View File

@@ -6,11 +6,13 @@ from typing import Any, Dict
from fastapi import Body, Depends
from app.api.dependencies.auth import get_current_active_superuser
from app.api.dependencies.auth import get_current_active_superuser, get_current_active_user
from app.api.principal import ApiPrincipal
from app.api.response import ResponseAPIRouter
from app.application.configuration import get_configured_system_config
from app.chain.notification import NotificationChain
from app.schemas.common import ManageRequest as _SchemaManageRequest
from app.schemas.push import AppPushRequest
from app.schemas.response import Response as _SchemaResponse
from app.schemas.system import NotificationConf
from app.schemas.types import SystemConfigKey
@@ -18,6 +20,22 @@ from app.schemas.types import SystemConfigKey
router = ResponseAPIRouter()
@router.post("/app", summary="管理当前用户的 App 通知", response_model=_SchemaResponse[Dict[str, Any]])
def manage_app_notification(
request: AppPushRequest,
current_user: ApiPrincipal = Depends(get_current_active_user),
) -> _SchemaResponse[object]:
"""
复用现有用户认证并强制注入账号通知身份,客户端不能操作其他用户设备。
"""
if not current_user.notification_identity:
return _SchemaResponse(success=False, message="请完成数据库升级后重新登录")
params = request.model_dump(exclude={"action"})
result = NotificationChain().manage_channel(channel="AppPush", action=request.action,
owner=current_user.notification_identity, **params)
return _SchemaResponse(success=bool(result.get("success")), message=result.get("message") or "", data=result.get("data"))
def _normalize_configs(value: list[NotificationConf], *, validate_identities: bool = True) -> list[dict[str, Any]]:
"""
规整通知配置身份和名称,拒绝会导致运行目录覆盖的输入。

View File

@@ -12,11 +12,13 @@ class ApiPrincipal(Protocol):
:ivar id: 已认证用户的数据库主键
:ivar name: 已认证用户的账号名称
:ivar is_superuser: 当前用户是否拥有系统管理员权限
:ivar notification_identity: 系统分配的不可变通知身份,不接受客户端指定
"""
id: int
name: str
is_superuser: bool
notification_identity: str
__all__ = ["ApiPrincipal"]

View File

@@ -59,6 +59,7 @@ class UserSnapshot:
:param is_otp: 是否启用基于时间的一次性密码验证
:param permissions: 用户权限的只读快照
:param settings: 用户个性化设置的只读快照
:param notification_identity: 不可变的通知绑定身份,不从客户端设置中读取
"""
id: int
@@ -70,6 +71,7 @@ class UserSnapshot:
is_otp: bool
permissions: Mapping[str, FrozenJson]
settings: Mapping[str, FrozenJson]
notification_identity: str = ""
@classmethod
def build(
@@ -84,6 +86,7 @@ class UserSnapshot:
is_otp: Optional[bool],
permissions: Optional[Mapping[str, Any]],
settings: Optional[Mapping[str, Any]],
notification_identity: str = "",
) -> "UserSnapshot":
"""
复制持久化字段并构造不可变的公开用户快照。
@@ -98,6 +101,7 @@ class UserSnapshot:
is_otp=bool(is_otp),
permissions=_freeze_mapping(permissions),
settings=_freeze_mapping(settings),
notification_identity=notification_identity,
)

View File

@@ -43,6 +43,7 @@ def _to_snapshot(model: User) -> UserSnapshot:
is_otp=model.is_otp,
permissions=model.permissions,
settings=model.settings,
notification_identity=model.notification_identity or "",
)
@@ -364,7 +365,13 @@ class TransactionalUserRepository(ChainUserRepository):
同步读取用户通知设置的只读快照。
"""
user = self.get_by_name(name)
return user.settings if user else None
if user is None:
return None
settings = dict(user.settings)
settings.pop("apppush", None)
if user.is_active and user.notification_identity:
settings["apppush"] = user.notification_identity
return settings
async def async_get_notification_settings(
self,
@@ -374,7 +381,13 @@ class TransactionalUserRepository(ChainUserRepository):
异步读取用户通知设置的只读快照。
"""
user = await self.async_get_by_name(name)
return user.settings if user else None
if user is None:
return None
settings = dict(user.settings)
settings.pop("apppush", None)
if user.is_active and user.notification_identity:
settings["apppush"] = user.notification_identity
return settings
def find_name_by_bindings(
self,

View File

@@ -5,6 +5,7 @@
"""
from typing import Any, Optional, Self
from uuid import uuid4
from sqlalchemy import JSON, Boolean, Index, String, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -40,6 +41,8 @@ class User(Base):
permissions: Mapped[Optional[Any]] = mapped_column(JSON, default=dict)
# 用户个性化设置 json
settings: Mapped[Optional[Any]] = mapped_column(JSON, default=dict)
# 通知使用不可变账号身份;主键复用、改名或删除重建不能继承旧设备。
notification_identity: Mapped[str] = mapped_column(String(32), default=lambda: uuid4().hex, nullable=False)
__table_args__ = (Index("ux_user_name", "name", unique=True),)

View File

@@ -199,6 +199,7 @@
"storage_type 无效": "Invalid storage_type",
"媒体服务器请求失败": "Media server request failed",
"附件保存失败": "Failed to save attachment",
"请完成数据库升级后重新登录": "Please complete the database upgrade and sign in again",
"通知配置保存成功": "Notification configuration saved successfully",
"通知配置保存失败": "Failed to save notification configuration",
"通知配置已保存,但缓存同步失败,请重试": "Notification configuration was saved, but cache synchronization failed. Please try again",

View File

@@ -0,0 +1,140 @@
"""
将现有 MoviePilot 通知经私有 Server 投递到 App 或主屏幕通知网页。
"""
from typing import Any, Optional, Union
from app.adapters.external.server import MoviePilotServerHelper
from app.modules import _MessageBase, _ModuleBase
from app.runtime.log import logger
from app.schemas.message import Message
from app.schemas.system import NotificationConf
from app.schemas.types import ModuleType, NotificationChannel
class AppPushModule(_ModuleBase, _MessageBase[object]):
"""
复用现有渠道配置、消息类型开关和用户路由,不持有 Apple 或 VAPID 私钥。
"""
_notification_user_target_keys = ("apppush",)
def init_module(self) -> None:
"""
声明 AppPush 渠道,配置随现有通知配置生命周期更新。
"""
super().init_service(service_name="apppush")
self._channel = NotificationChannel.AppPush
@staticmethod
def get_name() -> str:
"""
提供渠道目录与前端配置使用的规范名称。
"""
return "AppPush"
@staticmethod
def get_type() -> ModuleType:
"""
声明为通知模块,沿用消息队列和分发器。
"""
return ModuleType.Notification
@staticmethod
def get_subtype() -> NotificationChannel:
"""
返回 AppPush 的渠道枚举。
"""
return NotificationChannel.AppPush
@staticmethod
def get_priority() -> int:
"""
与其他单向通知渠道一起分发,不拦截原 Web Push。
"""
return 7
def init_setting(self) -> Optional[tuple[str, Union[str, bool]]]:
"""
由通知渠道配置启用,不新增全局环境开关。
"""
return None
def stop(self) -> None:
"""
HTTP 使用共享请求入口,本模块没有长期连接需要关闭。
"""
def test(self) -> tuple[bool, str]:
"""
检查配置是否存在,实际投递由绑定用户的测试操作验证。
"""
return (True, "") if self.get_configs() else (False, "请先启用 AppPush 渠道")
def _request(self, conf: NotificationConf, method: str, path: str, data: dict[str, Any]) -> dict[str, Any]:
"""
从渠道配置读取唯一中转地址和实例密钥,不将密钥返回客户端或写入日志。
"""
config = conf.config or {}
return MoviePilotServerHelper.relay_push(str(config.get("PUSH_SERVER_URL") or ""),
str(config.get("PUSH_RELAY_KEY") or ""), method, path, data)
def channel_manage(self, channel: str, action: str, **params: Any) -> Optional[dict[str, Any]]:
"""
处理已鉴权的设备管理;owner 只由专用端点注入,不使用通用管理员动作的隐式广播。
"""
if channel != "AppPush":
return None
configs = self.get_configs()
source = params.get("source")
conf = configs.get(source) if source else next(iter(configs.values()), None)
owner = params.get("owner")
if not conf or not isinstance(owner, str) or not owner:
return {"success": False, "message": "请先配置并启用 AppPush 私有通知渠道"}
installation = params.get("installation")
origin = params.get("origin")
try:
if action == "status":
data = self._request(conf, "GET", "devices", {"owner": owner})
data.update(owner=owner, relay_url=str((conf.config or {}).get("PUSH_SERVER_URL") or "").rstrip("/") + "/push/app/")
elif action == "pair":
data = self._request(conf, "POST", "pairings", {"owner": owner, "origin": origin, "installation": installation})
data["relay_url"] = str((conf.config or {}).get("PUSH_SERVER_URL") or "").rstrip("/") + "/push/app/"
elif action == "register":
if not params.get("token") or not params.get("topic"):
return {"success": False, "message": "尚未取得系统推送令牌"}
data = self._request(conf, "POST", "devices", {key: params[key] for key in (
"owner", "origin", "installation", "token", "topic", "environment",
)})
elif action == "unregister":
data = self._request(conf, "DELETE", "devices", {"owner": owner, "installation": installation})
elif action == "test":
data = self._request(conf, "POST", "messages", {"owner": owner, "title": "MoviePilot 测试通知", "body": "通知服务已连接"})
else:
return {"success": False, "message": "不支持的 AppPush 操作"}
return {"success": True, "data": data}
except ValueError as error:
return {"success": False, "message": str(error)}
def post_message(self, message: Message, **kwargs: object) -> None:
"""
仅向路由确定的不可变账号身份投递;缺少绑定绝不退回全设备广播。
"""
for conf in self.get_configs().values():
if not self.check_message(message, conf.name):
continue
owner = str((self.get_notification_targets(message) or {}).get("apppush") or "")
if not owner:
continue
link = message.link or "/?shotcut=message"
# 外部下载或媒体链接留在消息列表中,系统通知点击始终交给本实例。
route = link if link.startswith("/") and not link.startswith("//") and "\\" not in link else "/?shotcut=message"
try:
result = self._request(conf, "POST", "messages", {
"owner": owner, "title": (message.title or "MoviePilot")[:256],
"body": (message.text or "")[:1000], "route": route,
})
if result.get("failed"):
logger.warning(f"AppPush 有 {len(result['failed'])} 个设备投递失败,请检查 Server 配置")
except ValueError as error:
logger.warning(f"AppPush 投递失败:{error}")

View File

@@ -0,0 +1,22 @@
schema_version = 1
id = "AppPushModule"
kind = "host_module"
entrypoint = "app.modules.apppush:AppPushModule"
depends_on = []
[metadata]
name = "AppPush"
type = "notification"
subtype = "AppPush"
priority = 7
[activation]
policy = "when_configured"
watch = ["Notifications"]
[activation.selector]
kind = "system_config_item"
key = "Notifications"
match_field = "type"
match_value = "apppush"
enabled_field = "enabled"

View File

@@ -125,6 +125,16 @@ MODULE_QUALITY_PROFILES = {
}
MODULE_QUALITY_PROFILES.update({
"apppush": ModuleQualityProfile(
module="apppush",
level=ModuleQualityLevel.ASSESSED,
owner="MoviePilot core",
verified_rules=COMMON_ASSESSED_RULES | frozenset({
"fake-client-or-fixture", "sensitive-log-redaction", "reload-stop-idempotent",
"auth-rate-timeout-offline-semantics", "sync-async-boundary",
}),
exemption_reason="同步单向 HTTP 中转,无轮询、长连接或入站回调;设备配额和投递并发由私有 Server 约束",
),
"bangumi": ModuleQualityProfile(
module="bangumi",
level=ModuleQualityLevel.ASSESSED,

34
app/schemas/push.py Normal file
View File

@@ -0,0 +1,34 @@
"""
原生容器的通知管理请求,不允许指定其他用户或提交中转发送密钥。
"""
from typing import Literal, Optional
from urllib.parse import urlsplit
from pydantic import BaseModel, ConfigDict, Field, field_validator
class AppPushRequest(BaseModel):
"""
通知操作绑定当前登录身份;来源由启用的通知渠道配置选择。
"""
model_config = ConfigDict(extra="forbid")
action: Literal["status", "register", "unregister", "pair", "test"] = Field(description="通知管理动作")
installation: str = Field(min_length=16, max_length=64, pattern=r"^[a-zA-Z0-9_-]+$", description="App 安装的随机标识")
origin: str = Field(min_length=1, max_length=2048, description="App 正在连接的实例地址")
token: Optional[str] = Field(default=None, min_length=32, max_length=512, pattern=r"^[0-9a-fA-F]+$", description="系统 APNs 令牌,仅注册时使用")
topic: Optional[str] = Field(default=None, min_length=1, max_length=255, description="签名 Bundle ID")
environment: Literal["sandbox", "production"] = Field(default="sandbox", description="签名对应的 APNs 环境")
source: Optional[str] = Field(default=None, max_length=255, description="指定启用的 AppPush 渠道名称,省略时选第一个")
@field_validator("origin")
@classmethod
def validate_origin(cls, value: str) -> str:
"""
只允许不带账号、查询或片段的 HTTP(S) 实例地址。
"""
parsed = urlsplit(value)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError("实例地址无效")
return value.rstrip("/")

View File

@@ -87,7 +87,7 @@ class NotificationConf(BaseModel):
name: Optional[str] = Field(default=None, description="名称")
type: Optional[str] = Field(
default=None,
description="类型 telegram/wechat/feishu/vocechat/synologychat/slack/webpush/qqbot",
description="类型 telegram/wechat/feishu/vocechat/synologychat/slack/webpush/qqbot/apppush",
)
config: Optional[dict[str, Any]] = Field(default_factory=dict, description="配置")
switchs: Optional[list[str]] = Field(

View File

@@ -607,6 +607,8 @@ class NotificationChannel(Enum):
WebAgent = "WebAgent"
# 浏览器推送渠道
WebPush = "WebPush"
# MoviePilot-Server 中转的 App 和主屏幕网页通知渠道
AppPush = "AppPush"
# QQ 消息渠道
QQ = "QQ"

View File

@@ -0,0 +1,37 @@
"""
为通知设备绑定增加不可变用户身份,避免用户名或数据库主键复用造成串号。
"""
from uuid import uuid4
import sqlalchemy as sa
from alembic import op
revision = "da73b6f20418"
down_revision = "c9e2f6a04173"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""
为既有账号逐个分配独立身份;新库由 ORM 建表时已有字段,仍可幂等执行。
"""
bind = op.get_bind()
columns = {item["name"] for item in sa.inspect(bind).get_columns("user")}
if "notification_identity" not in columns:
op.add_column("user", sa.Column("notification_identity", sa.String(32), nullable=True))
table = sa.table("user", sa.column("id", sa.Integer()), sa.column("notification_identity", sa.String(32)))
for user_id in bind.execute(sa.select(table.c.id).where(sa.or_(table.c.notification_identity.is_(None), table.c.notification_identity == ""))).scalars():
bind.execute(table.update().where(table.c.id == user_id).values(notification_identity=uuid4().hex))
columns = {item["name"]: item for item in sa.inspect(bind).get_columns("user")}
if columns["notification_identity"]["nullable"]:
with op.batch_alter_table("user") as batch:
batch.alter_column("notification_identity", existing_type=sa.String(32), nullable=False)
def downgrade() -> None:
"""
只移除新增身份字段,不修改账号及其余认证数据。
"""
op.drop_column("user", "notification_identity")

View File

@@ -32,6 +32,14 @@
改名应保留原 `id`;复制为新的渠道实例应使用新的 `id`,避免共享登录凭据。
通过消息渠道发起普通重启时,完成回执保留发起时的 `source` 配置。
`POST /api/v1/notification/app` 使用当前激活用户的既有 Bearer 登录态管理 AppPush,
请求包含 `action`(`status/register/unregister/pair/test`)、随机 `installation` 和实例 `origin`。
`register` 另需 APNs `token/topic/environment`;`source` 可选,用于选择启用的 AppPush 渠道。
账号通知身份由后台注入,客户端不能指定其他用户。注销同时撤销该安装配对的主屏幕通知网页。
AppPush 配置只保存 `PUSH_SERVER_URL` 和实例专用 `PUSH_RELAY_KEY`,Apple/VAPID 私钥放在私有 Server。
消息沿用现有类型开关和管理员/用户路由;无明确用户目标时不广播。部署与免费自签说明见
[MoviePilot-Server](https://github.com/jxxghp/MoviePilot-Server#私有-app-消息推送)。
Discord 仅指定 `userid` 的定向通知使用私聊;无法私聊时返回失败,不转发公共频道。
`/skills` 安装和删除按展示时的条目身份操作,刷新或翻页后的旧按钮会失效,应使用最新列表重新选择。

View File

@@ -332,7 +332,7 @@ python scripts/mp-db.py write "UPDATE subscribe SET state = 'S' WHERE id = 123"
- Purpose: Stores user accounts, password hashes, administrator state, OTP, permissions, and preferences.
- Useful queries: Authorized diagnostics of account state, permissions, or authentication configuration.
- Write boundary: Security-sensitive; manage through user, permission, password, and two-factor APIs.
- Columns: `id`, `name`, `email`, `hashed_password`, `is_active`, `is_superuser`, `avatar`, `is_otp`, `otp_secret`, `permissions`, `settings`
- Columns: `id`, `name`, `email`, `hashed_password`, `is_active`, `is_superuser`, `avatar`, `is_otp`, `otp_secret`, `permissions`, `settings`, `notification_identity`
### `userconfig`
- Purpose: Stores per-user JSON configuration isolated by username and key.

View File

@@ -959,8 +959,8 @@
"runtime_only": true
}
},
"edge_count": 9715,
"edge_sha256": "f0613215dea0fa239b7444ab4dc0955fdf32e0bad1ebf5f1ae0b01221f5920b0",
"edge_count": 9727,
"edge_sha256": "4c4361d6a435793000158fa6bf8896ac4a7dd3c5a15046a46556a46fba094245",
"edges": [
"app -> app.foundation",
"app -> app.foundation.environment",
@@ -2791,6 +2791,7 @@
"app.api.endpoints.notification -> app.api",
"app.api.endpoints.notification -> app.api.dependencies",
"app.api.endpoints.notification -> app.api.dependencies.auth",
"app.api.endpoints.notification -> app.api.principal",
"app.api.endpoints.notification -> app.api.response",
"app.api.endpoints.notification -> app.application",
"app.api.endpoints.notification -> app.application.configuration",
@@ -2798,6 +2799,7 @@
"app.api.endpoints.notification -> app.chain.notification",
"app.api.endpoints.notification -> app.schemas",
"app.api.endpoints.notification -> app.schemas.common",
"app.api.endpoints.notification -> app.schemas.push",
"app.api.endpoints.notification -> app.schemas.response",
"app.api.endpoints.notification -> app.schemas.system",
"app.api.endpoints.notification -> app.schemas.types",
@@ -7156,6 +7158,16 @@
"app.modules.anilist.anilist -> app.runtime.cache",
"app.modules.anilist.anilist -> app.runtime.log",
"app.modules.anilist.anilist -> app.runtime.settings",
"app.modules.apppush -> app.adapters",
"app.modules.apppush -> app.adapters.external",
"app.modules.apppush -> app.adapters.external.server",
"app.modules.apppush -> app.modules",
"app.modules.apppush -> app.runtime",
"app.modules.apppush -> app.runtime.log",
"app.modules.apppush -> app.schemas",
"app.modules.apppush -> app.schemas.message",
"app.modules.apppush -> app.schemas.system",
"app.modules.apppush -> app.schemas.types",
"app.modules.bangumi -> app.adapters",
"app.modules.bangumi -> app.adapters.network",
"app.modules.bangumi -> app.adapters.network.http",
@@ -10678,7 +10690,7 @@
"app.workflow.actions.transfer_file -> app.workflow",
"app.workflow.actions.transfer_file -> app.workflow.actions"
],
"module_count": 1129,
"module_count": 1131,
"modules": [
"app",
"app.adapters",
@@ -11410,6 +11422,7 @@
"app.modules.amll.module",
"app.modules.anilist",
"app.modules.anilist.anilist",
"app.modules.apppush",
"app.modules.bangumi",
"app.modules.bangumi.bangumi",
"app.modules.dingtalk",
@@ -11701,6 +11714,7 @@
"app.schemas.notification",
"app.schemas.openai",
"app.schemas.plugin",
"app.schemas.push",
"app.schemas.query",
"app.schemas.recommend",
"app.schemas.response",

136
tests/test_apppush.py Normal file
View File

@@ -0,0 +1,136 @@
"""
私有 AppPush 的认证边界、用户身份迁移和现有通知路由回归。
"""
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import pytest
from alembic.migration import MigrationContext
from alembic.operations import Operations
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, inspect, text
from app.adapters.external.server import MoviePilotServerHelper
from app.api.dependencies.auth import get_current_active_user
from app.api.endpoints import notification
from app.modules.apppush import AppPushModule
from app.schemas.message import Message
from app.schemas.system import NotificationConf
from app.schemas.types import MessageType, NotificationChannel
def test_app_device_endpoint_forces_authenticated_owner(monkeypatch):
"""
当前用户可管理自己的安装,正文提交其他 owner 必须在进入渠道前拒绝。
"""
calls = []
class Chain:
"""
记录最终进入通知链的参数,不触发真实模块和网络。
"""
def manage_channel(self, **params):
"""
返回测试绑定并保留由端点注入的账号身份。
"""
calls.append(params)
return {"success": True, "data": {"owner": params["owner"]}}
monkeypatch.setattr(notification, "NotificationChain", Chain)
app = FastAPI()
app.include_router(notification.router, prefix="/notification")
app.dependency_overrides[get_current_active_user] = lambda: SimpleNamespace(notification_identity="a" * 32)
body = {"action": "status", "installation": "installation-001", "origin": "https://mp.test"}
with TestClient(app) as client:
assert client.post("/notification/app", json={**body, "owner": "b" * 32}).status_code == 422
result = client.post("/notification/app", json=body)
assert result.status_code == 200
assert result.json()["data"]["owner"] == "a" * 32
assert len(calls) == 1
assert calls[0]["channel"] == "AppPush"
def test_apppush_reuses_message_switches_and_never_broadcasts(monkeypatch):
"""
仅命中现有消息开关、渠道、来源与定向用户时向 Server 发送。
"""
conf = NotificationConf(name="private", type="apppush", enabled=True, switchs=["资源下载"])
module = AppPushModule.__new__(AppPushModule)
module._channel = NotificationChannel.AppPush
module._configs = {"private": conf}
monkeypatch.setattr(module, "get_configs", lambda: {"private": conf})
calls = []
monkeypatch.setattr(module, "_request", lambda *args: calls.append(args) or {"total": 1, "accepted": 1})
base = {"mtype": MessageType.Download, "title": "下载完成", "targets": {"apppush": "a" * 32}}
message = Message(**base, link="https://foreign.test")
message.set_notification_route_scope("user")
module.post_message(message)
assert len(calls) == 1
assert calls[0][3]["owner"] == "a" * 32
assert calls[0][3]["route"] == "/?shotcut=message"
module.post_message(Message(**{**base, "targets": {}}))
module.post_message(Message(**base, channel=NotificationChannel.Telegram))
module.post_message(Message(**base, source="other"))
conf.switchs = []
module.post_message(Message(**base))
assert len(calls) == 1
def test_server_request_keeps_key_in_header_and_rejects_redirects(monkeypatch):
"""
中转只允许固定接口和 HTTPS,不跟随重定向,不把错误正文或密钥暴露给客户端。
"""
captured = {}
class Request:
"""
在实际传输调用处记录 headers、params 和重定向策略。
"""
def __init__(self, **kwargs):
"""
保存 HTTP 客户端初始化参数。
"""
captured.update(kwargs)
def request(self, method, url, **kwargs):
"""
模拟 Server 返回成功或重定向响应。
"""
captured.update(method=method, url=url, **kwargs)
return SimpleNamespace(status_code=200, json=lambda: {"devices": []})
monkeypatch.setattr("app.adapters.external.server.RequestUtils", Request)
key = "private-key-" * 4
assert MoviePilotServerHelper.relay_push("https://relay.test", key, "GET", "devices", {"owner": "a" * 32}) == {"devices": []}
assert captured["headers"] == {"Authorization": "Bearer " + key}
assert captured["allow_redirects"] is False and captured["verify"] is True
assert key not in captured["url"] and key not in str(captured["params"])
with pytest.raises(ValueError, match="HTTPS"):
MoviePilotServerHelper.relay_push("http://relay.test", key, "POST", "messages", {})
def test_notification_identity_migration_is_stable_and_non_nullable(tmp_path):
"""
旧用户逐个获得不同身份,重复迁移不改已绑定值,改名和主键复用不会串设备。
"""
path = Path(__file__).parents[1] / "database/versions/da73b6f20418_notification_identity.py"
spec = importlib.util.spec_from_file_location("notification_migration", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
with engine.begin() as connection:
connection.execute(text('CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'))
connection.execute(text("INSERT INTO user (name) VALUES ('alice'), ('bob')"))
with Operations.context(MigrationContext.configure(connection)):
module.upgrade()
first = list(connection.execute(text('SELECT notification_identity FROM user ORDER BY id')).scalars())
module.upgrade()
assert len(set(first)) == 2 and all(len(value) == 32 for value in first)
assert list(connection.execute(text('SELECT notification_identity FROM user ORDER BY id')).scalars()) == first
assert next(column for column in inspect(connection).get_columns('user') if column['name'] == 'notification_identity')['nullable'] is False
engine.dispose()

View File

@@ -87,7 +87,8 @@ def test_identity_upgrade_chain_preserves_plugin_installation_snapshot(monkeypat
config = Config()
config.set_main_option("script_location", "database")
script = ScriptDirectory.from_config(config)
assert script.get_heads() == ["c9e2f6a04173"]
assert script.get_heads() == ["da73b6f20418"]
assert script.get_revision("da73b6f20418").down_revision == "c9e2f6a04173"
assert script.get_revision("c9e2f6a04173").down_revision == "b8d2f5a01962"
predecessor = importlib.import_module("database.versions.b8d2f5a01962_plugin_data_identity")
migration = importlib.import_module("database.versions.c9e2f6a04173_subscription_identity")

View File

@@ -583,3 +583,31 @@ async def test_user_delete_and_config_set_cannot_recreate_orphan(tmp_path) -> No
assert rows == []
assert snapshot is None
@pytest.mark.asyncio
async def test_notification_targets_use_immutable_identity_and_ignore_user_settings(user_repository):
"""
通知目标只取 ORM 身份;改名保留、删除重建更新、停用用户不能注入他人目标。
"""
repository, sync_factory = user_repository
user_id = _insert_user(sync_factory, settings={"apppush": "injected-owner"})
first = repository.get_notification_settings("alice")["apppush"]
assert first != "injected-owner" and len(first) == 32
assert (await repository.async_get_notification_settings("alice"))["apppush"] == first
with sync_factory() as session:
model = session.get(User, user_id)
model.name = "renamed"
session.commit()
assert repository.get_notification_settings("renamed")["apppush"] == first
with sync_factory() as session:
model = session.get(User, user_id)
model.is_active = False
session.commit()
assert "apppush" not in repository.get_notification_settings("renamed")
assert "apppush" not in await repository.async_get_notification_settings("renamed")
with sync_factory() as session:
session.delete(session.get(User, user_id))
session.commit()
_insert_user(sync_factory, id=user_id, name="renamed")
assert repository.get_notification_settings("renamed")["apppush"] != first