S-20 访问控制白名单黑名单
这个提交存在于:
父节点
36af501aa9
当前提交
69f9c3007f
共有 8 个文件被更改,包括 645 次插入 和 12 次删除
10
README.md
10
README.md
|
|
@ -9,6 +9,16 @@
|
|||
- `/jm scan`:手动触发一次 Komga 扫描。
|
||||
- `/jm cleanup`:清理超过 `cleanup_retention_days` 的临时工作目录。
|
||||
|
||||
## 访问控制
|
||||
|
||||
插件默认启用白名单:只有 `access_control` 白名单中的群聊或私聊账号可以触发命令。黑名单优先于白名单。
|
||||
|
||||
- OneBot v11 / aiocqhttp 群聊:`allow_group_ids` 填群号,例如 `123456789`。
|
||||
- OneBot v11 / aiocqhttp 私聊:`allow_private_user_ids` 填 QQ 号,例如 `10001`。
|
||||
- OneBot v11 / aiocqhttp 机器人自身账号:`allow_self_ids` 填机器人 QQ 号,可用于多账号场景。
|
||||
- 多平台实例:可写 `平台ID:群号` 或 `平台ID:QQ号`,也可用完整 UMO:`平台ID:GroupMessage:群号`、`平台ID:FriendMessage:QQ号`。
|
||||
- 平台 ID:来自 AstrBot 平台实例 ID,`/jm status` 会显示当前事件的 `平台 ID`、`机器人自身 ID`、`群聊 ID`、`发送者 ID` 和 `UMO`。
|
||||
|
||||
## 归档结构
|
||||
|
||||
默认归档为 `cbz`,目录结构如下:
|
||||
|
|
|
|||
|
|
@ -65,6 +65,77 @@
|
|||
"type": "int",
|
||||
"default": 20
|
||||
},
|
||||
"access_control": {
|
||||
"description": "JMDownload 触发访问控制。黑名单优先;默认只有白名单中的群聊或私聊账号可以触发。",
|
||||
"type": "object",
|
||||
"items": {
|
||||
"enabled": {
|
||||
"description": "启用插件级白名单/黑名单。",
|
||||
"type": "bool",
|
||||
"default": true
|
||||
},
|
||||
"require_whitelist": {
|
||||
"description": "是否要求命令来源必须命中白名单。默认开启;关闭后仅黑名单生效。",
|
||||
"type": "bool",
|
||||
"default": true
|
||||
},
|
||||
"allow_platform_ids": {
|
||||
"description": "允许触发的 AstrBot 平台 ID 列表。命中后该平台全部群聊/私聊允许触发。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"allow_self_ids": {
|
||||
"description": "允许触发的机器人自身 ID 列表。OneBot v11 中是机器人 QQ 号;可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"allow_group_ids": {
|
||||
"description": "允许触发的群聊 ID 列表。OneBot v11 使用群号;可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"allow_private_user_ids": {
|
||||
"description": "允许触发的私聊账号 ID 列表。OneBot v11 使用 QQ 号;可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"allow_unified_origins": {
|
||||
"description": "允许触发的完整 AstrBot UMO,例如 aiocqhttp:GroupMessage:123456 或 平台ID:FriendMessage:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_platform_ids": {
|
||||
"description": "禁止触发的 AstrBot 平台 ID 列表。黑名单优先于白名单。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_self_ids": {
|
||||
"description": "禁止触发的机器人自身 ID 列表。OneBot v11 中是机器人 QQ 号;可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_group_ids": {
|
||||
"description": "禁止触发的群聊 ID 列表。可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_private_user_ids": {
|
||||
"description": "禁止触发的私聊账号 ID 列表。可写 123456 或 平台ID:123456。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_unified_origins": {
|
||||
"description": "禁止触发的完整 AstrBot UMO。黑名单优先于白名单。",
|
||||
"type": "list",
|
||||
"default": []
|
||||
},
|
||||
"deny_message": {
|
||||
"description": "拒绝触发时回复的文本。留空则静默拒绝。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"jm_proxy": {
|
||||
"description": "JM 下载代理配置。",
|
||||
"type": "object",
|
||||
|
|
|
|||
|
|
@ -78,7 +78,91 @@ komga.password
|
|||
POST /api/v1/libraries/{libraryId}/scan
|
||||
```
|
||||
|
||||
## 4. JM 代理与登录
|
||||
## 4. 访问控制
|
||||
|
||||
插件默认启用访问控制,并且要求命令来源命中白名单:
|
||||
|
||||
```text
|
||||
access_control.enabled: true
|
||||
access_control.require_whitelist: true
|
||||
```
|
||||
|
||||
OneBot v11 / aiocqhttp 的 ID 识别方式:
|
||||
|
||||
```text
|
||||
群聊消息:event.get_group_id() 是群号,event.get_sender_id() 是发送者 QQ 号
|
||||
私聊消息:event.get_group_id() 为空,event.get_sender_id() 是对方 QQ 号
|
||||
机器人自身 ID:event.get_self_id() 是机器人 QQ 号
|
||||
平台 ID:event.get_platform_id() 是 AstrBot 平台实例 ID
|
||||
UMO:event.unified_msg_origin,格式为 平台ID:消息类型:会话ID
|
||||
```
|
||||
|
||||
允许某个群触发:
|
||||
|
||||
```text
|
||||
access_control.allow_group_ids:
|
||||
- 123456789
|
||||
```
|
||||
|
||||
允许某个私聊账号触发:
|
||||
|
||||
```text
|
||||
access_control.allow_private_user_ids:
|
||||
- 10001
|
||||
```
|
||||
|
||||
允许某个 OneBot 机器人账号下的全部会话触发:
|
||||
|
||||
```text
|
||||
access_control.allow_self_ids:
|
||||
- 30003
|
||||
```
|
||||
|
||||
多个 OneBot / aiocqhttp 实例并存时,建议带上平台 ID:
|
||||
|
||||
```text
|
||||
access_control.allow_group_ids:
|
||||
- qq-main:123456789
|
||||
access_control.allow_private_user_ids:
|
||||
- qq-main:10001
|
||||
access_control.allow_self_ids:
|
||||
- qq-main:30003
|
||||
```
|
||||
|
||||
也可以使用完整 UMO:
|
||||
|
||||
```text
|
||||
access_control.allow_unified_origins:
|
||||
- qq-main:GroupMessage:123456789
|
||||
- qq-main:FriendMessage:10001
|
||||
```
|
||||
|
||||
黑名单优先于白名单:
|
||||
|
||||
```text
|
||||
access_control.deny_group_ids:
|
||||
- 987654321
|
||||
access_control.deny_private_user_ids:
|
||||
- 20002
|
||||
access_control.deny_self_ids:
|
||||
- 30003
|
||||
```
|
||||
|
||||
如果想只使用黑名单,不要求白名单:
|
||||
|
||||
```text
|
||||
access_control.require_whitelist: false
|
||||
```
|
||||
|
||||
拒绝时默认静默处理。需要提示时可配置:
|
||||
|
||||
```text
|
||||
access_control.deny_message: 当前会话不在 JMDownload 白名单内。
|
||||
```
|
||||
|
||||
首次配置时如果不知道 ID,可以临时设置 `access_control.require_whitelist: false`,执行 `/jm status` 查看当前事件的 `平台 ID`、`机器人自身 ID`、`群聊 ID`、`发送者 ID` 和 `UMO`,复制完成后再重新开启白名单。
|
||||
|
||||
## 5. JM 代理与登录
|
||||
|
||||
jmcomic 的代理配置位于 `client.postman.meta_data.proxies`。本插件在 WebUI 中提供 `jm_proxy`:
|
||||
|
||||
|
|
@ -135,7 +219,7 @@ jm_login.impl: html
|
|||
|
||||
注意:AVS Cookie 和访问域名有关,使用的 JM 域名要和 Cookie 来源域名一致。
|
||||
|
||||
## 5. 命令
|
||||
## 6. 命令
|
||||
|
||||
```text
|
||||
/jm download <id>
|
||||
|
|
@ -145,9 +229,10 @@ jm_login.impl: html
|
|||
/jm cleanup
|
||||
```
|
||||
|
||||
## 6. 故障排查
|
||||
## 7. 故障排查
|
||||
|
||||
- 插件无法加载:检查 `requirements.txt` 是否安装成功。
|
||||
- 命令没有反应:默认需要命中 `access_control` 白名单;先确认当前群号、QQ 号或 UMO 已配置。
|
||||
- 下载后没有文件:检查 `jm_domains` 是否可用,或降低 `jm_batch_count`。
|
||||
- 代理未生效:检查 `jm_proxy.mode`,custom 模式下确认代理端口可用。
|
||||
- 登录后仍不可下载:账号密码方式可切换 `jm_login.impl` 为 `html` 试试;手动 Cookie 方式需确认 `jm_avs_cookie` 来自当前实际访问的 JM 域名。
|
||||
|
|
@ -155,7 +240,7 @@ jm_login.impl: html
|
|||
- 文件发送失败:不同平台对文件消息支持不同;归档仍会保存在 `archive_root`。
|
||||
- PDF 转换失败:确认 `PyPDF2` 已安装,或改用默认 `cbz`。
|
||||
|
||||
## 7. 本地测试
|
||||
## 8. 本地测试
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests
|
||||
|
|
|
|||
66
main.py
66
main.py
|
|
@ -9,6 +9,7 @@ import astrbot.api.message_components as Comp
|
|||
from astrbot.api.star import Context, Star, StarTools
|
||||
|
||||
from .services.archive import ArchiveResult, ArchiveService
|
||||
from .services.access import AccessControl, AccessDecision, EventIdentity
|
||||
from .services.download import DownloadProgress, JMDownloadService
|
||||
from .services.errors import JMDownloadError
|
||||
from .services.komga import KomgaClient, KomgaScanResult
|
||||
|
|
@ -25,6 +26,7 @@ class JMDownloadPlugin(Star):
|
|||
self.downloader = JMDownloadService(self.settings)
|
||||
self.archiver = ArchiveService(self.settings)
|
||||
self.komga = KomgaClient(self.settings.komga)
|
||||
self.access_control = AccessControl(self.settings.access_control)
|
||||
self.task_semaphore = asyncio.Semaphore(self.settings.max_concurrent_tasks)
|
||||
|
||||
async def initialize(self) -> None:
|
||||
|
|
@ -45,8 +47,10 @@ class JMDownloadPlugin(Star):
|
|||
@jm.command("download", alias={"下载"})
|
||||
async def download(self, event: AstrMessageEvent, comic_id: str):
|
||||
"""Download a JM album, archive it, and optionally ask Komga to scan."""
|
||||
if self._deny_non_admin(event):
|
||||
yield event.plain_result("JMDownload is admin-only in the current config.")
|
||||
deny_message = self._deny_request(event, require_admin=True)
|
||||
if deny_message is not None:
|
||||
if deny_message:
|
||||
yield event.plain_result(deny_message)
|
||||
event.stop_event()
|
||||
return
|
||||
|
||||
|
|
@ -89,6 +93,14 @@ class JMDownloadPlugin(Star):
|
|||
@jm.command("status")
|
||||
async def status(self, event: AstrMessageEvent):
|
||||
"""Show current JMDownload archive and Komga settings."""
|
||||
deny_message = self._deny_request(event, require_admin=False)
|
||||
if deny_message is not None:
|
||||
if deny_message:
|
||||
yield event.plain_result(deny_message)
|
||||
event.stop_event()
|
||||
return
|
||||
|
||||
identity = EventIdentity.from_event(event)
|
||||
lines = [
|
||||
"JMDownload 状态",
|
||||
f"归档目录:{self.settings.archive_root}",
|
||||
|
|
@ -97,6 +109,15 @@ class JMDownloadPlugin(Star):
|
|||
f"并发任务数:{self.settings.max_concurrent_tasks}",
|
||||
f"下载重试次数:{self.settings.download_retry_count}",
|
||||
f"进度提示间隔:{self.settings.progress_interval_seconds} 秒",
|
||||
f"访问控制:{'启用' if self.settings.access_control.enabled else '关闭'}",
|
||||
f"需要白名单:{self.settings.access_control.require_whitelist}",
|
||||
f"当前平台类型:{identity.platform_name or '未知'}",
|
||||
f"当前平台 ID:{identity.platform_id or '未知'}",
|
||||
f"当前机器人自身 ID:{identity.self_id or '未知'}",
|
||||
f"当前会话类型:{identity.message_type or '未知'}",
|
||||
f"当前群聊 ID:{identity.group_id or '无'}",
|
||||
f"当前私聊/发送者 ID:{identity.sender_id or '未知'}",
|
||||
f"当前 UMO:{identity.unified_msg_origin or '未知'}",
|
||||
f"JM 代理模式:{self.settings.jm_proxy.mode}",
|
||||
f"JM 账号登录:{'已启用' if self.settings.jm_login.can_login else '未配置'}",
|
||||
f"JM 登录 Cookie:{'已配置' if self.settings.jm_avs_cookie else '未配置'}",
|
||||
|
|
@ -113,8 +134,10 @@ class JMDownloadPlugin(Star):
|
|||
@jm.command("scan")
|
||||
async def scan(self, event: AstrMessageEvent):
|
||||
"""Trigger a Komga scan for the configured library."""
|
||||
if self._deny_non_admin(event):
|
||||
yield event.plain_result("JMDownload is admin-only in the current config.")
|
||||
deny_message = self._deny_request(event, require_admin=True)
|
||||
if deny_message is not None:
|
||||
if deny_message:
|
||||
yield event.plain_result(deny_message)
|
||||
event.stop_event()
|
||||
return
|
||||
|
||||
|
|
@ -126,8 +149,10 @@ class JMDownloadPlugin(Star):
|
|||
@jm.command("cleanup")
|
||||
async def cleanup(self, event: AstrMessageEvent):
|
||||
"""Cleanup old JMDownload work directories."""
|
||||
if self._deny_non_admin(event):
|
||||
yield event.plain_result("JMDownload 当前配置仅允许管理员执行清理命令。")
|
||||
deny_message = self._deny_request(event, require_admin=True)
|
||||
if deny_message is not None:
|
||||
if deny_message:
|
||||
yield event.plain_result(deny_message)
|
||||
event.stop_event()
|
||||
return
|
||||
|
||||
|
|
@ -140,8 +165,33 @@ class JMDownloadPlugin(Star):
|
|||
yield event.plain_result(f"清理完成:删除 {removed} 个临时工作目录。")
|
||||
event.stop_event()
|
||||
|
||||
def _deny_non_admin(self, event: AstrMessageEvent) -> bool:
|
||||
return bool(self.settings.admin_only and not event.is_admin())
|
||||
def _deny_request(
|
||||
self,
|
||||
event: AstrMessageEvent,
|
||||
*,
|
||||
require_admin: bool,
|
||||
) -> str | None:
|
||||
decision = self.access_control.check(event)
|
||||
if not decision.allowed:
|
||||
self._log_access_denied(decision)
|
||||
return self.settings.access_control.deny_message
|
||||
if require_admin and self.settings.admin_only and not event.is_admin():
|
||||
return "JMDownload 当前配置仅允许 AstrBot 管理员执行此命令。"
|
||||
return None
|
||||
|
||||
def _log_access_denied(self, decision: AccessDecision) -> None:
|
||||
identity = decision.identity
|
||||
logger.info(
|
||||
"JMDownload access denied: "
|
||||
f"reason={decision.reason}, "
|
||||
f"platform_id={identity.platform_id}, "
|
||||
f"platform_name={identity.platform_name}, "
|
||||
f"self_id={identity.self_id}, "
|
||||
f"target_kind={identity.target_kind}, "
|
||||
f"target_id={identity.target_id}, "
|
||||
f"sender_id={identity.sender_id}, "
|
||||
f"umo={identity.unified_msg_origin}",
|
||||
)
|
||||
|
||||
def _format_success(
|
||||
self,
|
||||
|
|
|
|||
221
services/access.py
普通文件
221
services/access.py
普通文件
|
|
@ -0,0 +1,221 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .settings import AccessControlSettings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EventIdentity:
|
||||
platform_id: str
|
||||
platform_name: str
|
||||
message_type: str
|
||||
session_id: str
|
||||
unified_msg_origin: str
|
||||
self_id: str
|
||||
group_id: str
|
||||
sender_id: str
|
||||
is_private: bool
|
||||
|
||||
@classmethod
|
||||
def from_event(cls, event: Any) -> "EventIdentity":
|
||||
group_id = _call_string(event, "get_group_id")
|
||||
sender_id = _call_string(event, "get_sender_id")
|
||||
message_type = _message_type(event)
|
||||
is_private = _is_private(event, message_type, group_id)
|
||||
return cls(
|
||||
platform_id=_platform_id(event),
|
||||
platform_name=_platform_name(event),
|
||||
message_type=message_type,
|
||||
session_id=_session_id(event),
|
||||
unified_msg_origin=_unified_origin(event),
|
||||
self_id=_call_string(event, "get_self_id"),
|
||||
group_id=group_id,
|
||||
sender_id=sender_id,
|
||||
is_private=is_private,
|
||||
)
|
||||
|
||||
@property
|
||||
def target_kind(self) -> str:
|
||||
return "private" if self.is_private else "group"
|
||||
|
||||
@property
|
||||
def target_id(self) -> str:
|
||||
return self.sender_id if self.is_private else self.group_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccessDecision:
|
||||
allowed: bool
|
||||
reason: str
|
||||
identity: EventIdentity
|
||||
|
||||
|
||||
class AccessControl:
|
||||
def __init__(self, settings: AccessControlSettings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
def check(self, event: Any) -> AccessDecision:
|
||||
identity = EventIdentity.from_event(event)
|
||||
if not self.settings.enabled:
|
||||
return AccessDecision(True, "access control disabled", identity)
|
||||
|
||||
if _contains(
|
||||
self.settings.deny_platform_ids,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(False, "platform is blacklisted", identity)
|
||||
if _contains_scoped(
|
||||
self.settings.deny_self_ids,
|
||||
identity.self_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(False, "self id is blacklisted", identity)
|
||||
if _contains_exact(self.settings.deny_unified_origins, identity.unified_msg_origin):
|
||||
return AccessDecision(False, "unified origin is blacklisted", identity)
|
||||
|
||||
if identity.is_private:
|
||||
if _contains_scoped(
|
||||
self.settings.deny_private_user_ids,
|
||||
identity.sender_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(False, "private user is blacklisted", identity)
|
||||
elif _contains_scoped(
|
||||
self.settings.deny_group_ids,
|
||||
identity.group_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(False, "group is blacklisted", identity)
|
||||
|
||||
if not self.settings.require_whitelist:
|
||||
return AccessDecision(True, "whitelist not required", identity)
|
||||
|
||||
if _contains(
|
||||
self.settings.allow_platform_ids,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(True, "platform is whitelisted", identity)
|
||||
if _contains_scoped(
|
||||
self.settings.allow_self_ids,
|
||||
identity.self_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(True, "self id is whitelisted", identity)
|
||||
if _contains_exact(self.settings.allow_unified_origins, identity.unified_msg_origin):
|
||||
return AccessDecision(True, "unified origin is whitelisted", identity)
|
||||
|
||||
if identity.is_private:
|
||||
if _contains_scoped(
|
||||
self.settings.allow_private_user_ids,
|
||||
identity.sender_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(True, "private user is whitelisted", identity)
|
||||
elif _contains_scoped(
|
||||
self.settings.allow_group_ids,
|
||||
identity.group_id,
|
||||
identity.platform_id,
|
||||
identity.platform_name,
|
||||
):
|
||||
return AccessDecision(True, "group is whitelisted", identity)
|
||||
|
||||
return AccessDecision(False, "not in whitelist", identity)
|
||||
|
||||
|
||||
def _contains(values: list[str] | None, *candidates: str) -> bool:
|
||||
normalized_values = {value.strip() for value in values or [] if value.strip()}
|
||||
return any(candidate and candidate in normalized_values for candidate in candidates)
|
||||
|
||||
|
||||
def _contains_exact(values: list[str] | None, candidate: str) -> bool:
|
||||
normalized_values = {value.strip() for value in values or [] if value.strip()}
|
||||
return bool(candidate and candidate in normalized_values)
|
||||
|
||||
|
||||
def _contains_scoped(
|
||||
values: list[str] | None,
|
||||
raw_id: str,
|
||||
platform_id: str,
|
||||
platform_name: str,
|
||||
) -> bool:
|
||||
if not raw_id:
|
||||
return False
|
||||
candidates = {raw_id}
|
||||
if platform_id:
|
||||
candidates.add(f"{platform_id}:{raw_id}")
|
||||
if platform_name:
|
||||
candidates.add(f"{platform_name}:{raw_id}")
|
||||
return _contains(values, *candidates)
|
||||
|
||||
|
||||
def _call_string(event: Any, method_name: str) -> str:
|
||||
method = getattr(event, method_name, None)
|
||||
if not callable(method):
|
||||
return ""
|
||||
try:
|
||||
value = method()
|
||||
except Exception:
|
||||
return ""
|
||||
return _string_value(value)
|
||||
|
||||
|
||||
def _call_bool(event: Any, method_name: str) -> bool | None:
|
||||
method = getattr(event, method_name, None)
|
||||
if not callable(method):
|
||||
return None
|
||||
try:
|
||||
return bool(method())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _string_value(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
raw = getattr(value, "value", value)
|
||||
return str(raw).strip()
|
||||
|
||||
|
||||
def _message_type(event: Any) -> str:
|
||||
value = _call_string(event, "get_message_type")
|
||||
return value or _string_value(getattr(getattr(event, "session", None), "message_type", ""))
|
||||
|
||||
|
||||
def _session_id(event: Any) -> str:
|
||||
return (
|
||||
_call_string(event, "get_session_id")
|
||||
or _string_value(getattr(event, "session_id", ""))
|
||||
or _string_value(getattr(getattr(event, "session", None), "session_id", ""))
|
||||
)
|
||||
|
||||
|
||||
def _is_private(event: Any, message_type: str, group_id: str) -> bool:
|
||||
explicit = _call_bool(event, "is_private_chat")
|
||||
if explicit is not None:
|
||||
return explicit
|
||||
if message_type:
|
||||
return message_type == "FriendMessage"
|
||||
return not bool(group_id)
|
||||
|
||||
|
||||
def _unified_origin(event: Any) -> str:
|
||||
return _string_value(getattr(event, "unified_msg_origin", ""))
|
||||
|
||||
|
||||
def _platform_id(event: Any) -> str:
|
||||
return _call_string(event, "get_platform_id") or _string_value(
|
||||
getattr(getattr(event, "session", None), "platform_id", ""),
|
||||
)
|
||||
|
||||
|
||||
def _platform_name(event: Any) -> str:
|
||||
return _call_string(event, "get_platform_name")
|
||||
|
|
@ -14,6 +14,12 @@ DEFAULT_JM_DOMAINS = [
|
|||
]
|
||||
|
||||
|
||||
def _list_value(value: Any) -> list[str]:
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
return [str(item).strip() for item in value if str(item).strip()]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JmProxySettings:
|
||||
mode: str = "inherit"
|
||||
|
|
@ -116,6 +122,41 @@ class KomgaSettings:
|
|||
return bool(self.enabled and self.base_url and self.library_id and has_auth)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccessControlSettings:
|
||||
enabled: bool = True
|
||||
require_whitelist: bool = True
|
||||
allow_platform_ids: list[str] | None = None
|
||||
allow_self_ids: list[str] | None = None
|
||||
allow_group_ids: list[str] | None = None
|
||||
allow_private_user_ids: list[str] | None = None
|
||||
allow_unified_origins: list[str] | None = None
|
||||
deny_platform_ids: list[str] | None = None
|
||||
deny_self_ids: list[str] | None = None
|
||||
deny_group_ids: list[str] | None = None
|
||||
deny_private_user_ids: list[str] | None = None
|
||||
deny_unified_origins: list[str] | None = None
|
||||
deny_message: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config: dict[str, Any]) -> "AccessControlSettings":
|
||||
return cls(
|
||||
enabled=bool(config.get("enabled", True)),
|
||||
require_whitelist=bool(config.get("require_whitelist", True)),
|
||||
allow_platform_ids=_list_value(config.get("allow_platform_ids", [])),
|
||||
allow_self_ids=_list_value(config.get("allow_self_ids", [])),
|
||||
allow_group_ids=_list_value(config.get("allow_group_ids", [])),
|
||||
allow_private_user_ids=_list_value(config.get("allow_private_user_ids", [])),
|
||||
allow_unified_origins=_list_value(config.get("allow_unified_origins", [])),
|
||||
deny_platform_ids=_list_value(config.get("deny_platform_ids", [])),
|
||||
deny_self_ids=_list_value(config.get("deny_self_ids", [])),
|
||||
deny_group_ids=_list_value(config.get("deny_group_ids", [])),
|
||||
deny_private_user_ids=_list_value(config.get("deny_private_user_ids", [])),
|
||||
deny_unified_origins=_list_value(config.get("deny_unified_origins", [])),
|
||||
deny_message=str(config.get("deny_message", "")).strip(),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PluginSettings:
|
||||
data_dir: Path
|
||||
|
|
@ -133,6 +174,7 @@ class PluginSettings:
|
|||
progress_interval_seconds: int = 30
|
||||
max_concurrent_tasks: int = 1
|
||||
jm_batch_count: int = 20
|
||||
access_control: AccessControlSettings = AccessControlSettings()
|
||||
jm_proxy: JmProxySettings = JmProxySettings()
|
||||
jm_login: JmLoginSettings = JmLoginSettings()
|
||||
jm_avs_cookie: str = ""
|
||||
|
|
@ -164,6 +206,10 @@ class PluginSettings:
|
|||
if not isinstance(jm_login_config, dict):
|
||||
jm_login_config = {}
|
||||
|
||||
access_control_config = config.get("access_control", {})
|
||||
if not isinstance(access_control_config, dict):
|
||||
access_control_config = {}
|
||||
|
||||
komga_config = config.get("komga", {})
|
||||
if not isinstance(komga_config, dict):
|
||||
komga_config = {}
|
||||
|
|
@ -201,6 +247,7 @@ class PluginSettings:
|
|||
_int_value(config.get("max_concurrent_tasks"), 1),
|
||||
),
|
||||
jm_batch_count=max(1, _int_value(config.get("jm_batch_count"), 20)),
|
||||
access_control=AccessControlSettings.from_config(access_control_config),
|
||||
jm_proxy=JmProxySettings.from_config(jm_proxy_config),
|
||||
jm_login=JmLoginSettings.from_config(jm_login_config),
|
||||
jm_avs_cookie=str(config.get("jm_avs_cookie", "")).strip(),
|
||||
|
|
|
|||
147
tests/test_access_control.py
普通文件
147
tests/test_access_control.py
普通文件
|
|
@ -0,0 +1,147 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from services.access import AccessControl, EventIdentity
|
||||
from services.settings import AccessControlSettings
|
||||
|
||||
|
||||
class FakeEvent:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
platform_id: str = "aiocqhttp",
|
||||
platform_name: str = "aiocqhttp",
|
||||
self_id: str = "30003",
|
||||
message_type: str = "GroupMessage",
|
||||
group_id: str = "10001",
|
||||
sender_id: str = "20002",
|
||||
) -> None:
|
||||
self._platform_id = platform_id
|
||||
self._platform_name = platform_name
|
||||
self._self_id = self_id
|
||||
self._message_type = message_type
|
||||
self._group_id = group_id
|
||||
self._sender_id = sender_id
|
||||
self.session_id = sender_id if message_type == "FriendMessage" else group_id
|
||||
self.unified_msg_origin = f"{platform_id}:{message_type}:{self.session_id}"
|
||||
|
||||
def get_platform_id(self) -> str:
|
||||
return self._platform_id
|
||||
|
||||
def get_platform_name(self) -> str:
|
||||
return self._platform_name
|
||||
|
||||
def get_message_type(self) -> str:
|
||||
return self._message_type
|
||||
|
||||
def get_self_id(self) -> str:
|
||||
return self._self_id
|
||||
|
||||
def get_session_id(self) -> str:
|
||||
return self.session_id
|
||||
|
||||
def get_group_id(self) -> str:
|
||||
return self._group_id
|
||||
|
||||
def get_sender_id(self) -> str:
|
||||
return self._sender_id
|
||||
|
||||
def is_private_chat(self) -> bool:
|
||||
return self._message_type == "FriendMessage"
|
||||
|
||||
|
||||
class AccessControlTest(unittest.TestCase):
|
||||
def test_default_requires_whitelist(self) -> None:
|
||||
decision = AccessControl(AccessControlSettings()).check(FakeEvent())
|
||||
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual(decision.reason, "not in whitelist")
|
||||
|
||||
def test_group_whitelist_allows_onebot_group_id(self) -> None:
|
||||
decision = AccessControl(
|
||||
AccessControlSettings(allow_group_ids=["10001"]),
|
||||
).check(FakeEvent())
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(decision.reason, "group is whitelisted")
|
||||
|
||||
def test_platform_scoped_group_whitelist(self) -> None:
|
||||
settings = AccessControlSettings(allow_group_ids=["bot-qq:10001"])
|
||||
|
||||
allowed = AccessControl(settings).check(FakeEvent(platform_id="bot-qq"))
|
||||
denied = AccessControl(settings).check(FakeEvent(platform_id="other-qq"))
|
||||
|
||||
self.assertTrue(allowed.allowed)
|
||||
self.assertFalse(denied.allowed)
|
||||
|
||||
def test_private_whitelist_allows_onebot_user_id(self) -> None:
|
||||
event = FakeEvent(message_type="FriendMessage", group_id="", sender_id="20002")
|
||||
decision = AccessControl(
|
||||
AccessControlSettings(allow_private_user_ids=["20002"]),
|
||||
).check(event)
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(decision.identity.target_kind, "private")
|
||||
self.assertEqual(decision.identity.target_id, "20002")
|
||||
|
||||
def test_blacklist_overrides_whitelist(self) -> None:
|
||||
settings = AccessControlSettings(
|
||||
allow_group_ids=["10001"],
|
||||
deny_group_ids=["10001"],
|
||||
)
|
||||
decision = AccessControl(settings).check(FakeEvent())
|
||||
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual(decision.reason, "group is blacklisted")
|
||||
|
||||
def test_platform_whitelist_allows_any_session_on_platform(self) -> None:
|
||||
event = FakeEvent(platform_id="qq-main", group_id="999")
|
||||
decision = AccessControl(
|
||||
AccessControlSettings(allow_platform_ids=["qq-main"]),
|
||||
).check(event)
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(decision.reason, "platform is whitelisted")
|
||||
|
||||
def test_self_id_whitelist_allows_any_session_for_bot_account(self) -> None:
|
||||
event = FakeEvent(platform_id="qq-main", self_id="30003", group_id="999")
|
||||
decision = AccessControl(
|
||||
AccessControlSettings(allow_self_ids=["qq-main:30003"]),
|
||||
).check(event)
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(decision.reason, "self id is whitelisted")
|
||||
|
||||
def test_self_id_blacklist_overrides_group_whitelist(self) -> None:
|
||||
settings = AccessControlSettings(
|
||||
allow_group_ids=["10001"],
|
||||
deny_self_ids=["30003"],
|
||||
)
|
||||
decision = AccessControl(settings).check(FakeEvent(self_id="30003"))
|
||||
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual(decision.reason, "self id is blacklisted")
|
||||
|
||||
def test_unified_origin_can_be_whitelisted(self) -> None:
|
||||
event = FakeEvent(platform_id="qq-main", group_id="10001")
|
||||
decision = AccessControl(
|
||||
AccessControlSettings(allow_unified_origins=["qq-main:GroupMessage:10001"]),
|
||||
).check(event)
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
|
||||
def test_identity_extracts_astrbot_ids(self) -> None:
|
||||
event = FakeEvent(platform_id="qq-main", platform_name="aiocqhttp")
|
||||
identity = EventIdentity.from_event(event)
|
||||
|
||||
self.assertEqual(identity.platform_id, "qq-main")
|
||||
self.assertEqual(identity.platform_name, "aiocqhttp")
|
||||
self.assertEqual(identity.self_id, "30003")
|
||||
self.assertEqual(identity.group_id, "10001")
|
||||
self.assertEqual(identity.sender_id, "20002")
|
||||
self.assertEqual(identity.unified_msg_origin, "qq-main:GroupMessage:10001")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -26,6 +26,8 @@ class SettingsTest(unittest.TestCase):
|
|||
self.assertEqual(settings.download_timeout_seconds, 3600)
|
||||
self.assertEqual(settings.jm_batch_count, 20)
|
||||
self.assertEqual(settings.komga.scan_timeout_seconds, 30)
|
||||
self.assertTrue(settings.access_control.enabled)
|
||||
self.assertTrue(settings.access_control.require_whitelist)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用