feat: add napcat token verify

pull/58/head
CKylinMC 2025-09-11 18:35:33 +08:00
parent eaee8a45fb
commit f165cf3e2e
3 changed files with 14 additions and 1 deletions

11
main.py
View File

@ -1,6 +1,7 @@
import asyncio
import sys
import json
import http
import websockets as Server
from src.logger import logger
from src.recv_handler.message_handler import message_handler
@ -49,10 +50,18 @@ async def main():
message_send_instance.maibot_router = router
_ = await asyncio.gather(napcat_server(), mmc_start_com(), message_process(), check_timeout_response())
def check_napcat_server_token(conn, request):
token = global_config.napcat_server.token
if not token or token.strip() == "":
return None
auth_header = request.headers.get("Authorization")
if auth_header != f"Bearer {token}":
return Server.Response(http.HTTPStatus.UNAUTHORIZED, "", headers=Server.Headers([("Content-Type", "text/plain")]), body=b"Unauthorized\n")
return None
async def napcat_server():
logger.info("正在启动adapter...")
async with Server.serve(message_recv, global_config.napcat_server.host, global_config.napcat_server.port, max_size=2**26) as server:
async with Server.serve(message_recv, global_config.napcat_server.host, global_config.napcat_server.port, max_size=2**26, process_request=check_napcat_server_token) as server:
logger.info(
f"Adapter已启动监听地址: ws://{global_config.napcat_server.host}:{global_config.napcat_server.port}"
)

View File

@ -28,6 +28,9 @@ class NapcatServerConfig(ConfigBase):
port: int = 8095
"""Napcat服务端的端口号"""
token: str = ""
"""Napcat服务端的访问令牌若无则留空"""
heartbeat_interval: int = 30
"""Napcat心跳间隔时间单位为秒"""

View File

@ -8,6 +8,7 @@ nickname = ""
[napcat_server] # Napcat连接的ws服务设置
host = "localhost" # Napcat设定的主机地址
port = 8095 # Napcat设定的端口
token = "" # Napcat设定的访问令牌若无则留空
heartbeat_interval = 30 # 与Napcat设置的心跳相同按秒计
[maibot_server] # 连接麦麦的ws服务设置