mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-22 07:03:53 +08:00
feat: 添加WS TOKEN 认证功能
This commit is contained in:
+17
-6
@@ -5,7 +5,18 @@ server:
|
||||
port: 8000
|
||||
# 服务器是否只接受来自esp32-小智的连接,为了安全起见,建议设置为true
|
||||
# Whether the server only accepts connections from ESP32-Ash is recommended to be set to true for security purposes
|
||||
only_esp32_xiaozhi_connect: false
|
||||
only_esp32_xiaozhi_connect: true
|
||||
# 认证配置
|
||||
auth:
|
||||
enabled: true # 是否启用认证
|
||||
tokens:
|
||||
- token: "your-secure-token-1" # 设备1的token
|
||||
name: "device1" # 设备标识
|
||||
- token: "your-secure-token-2" # 设备2的token
|
||||
name: "device2"
|
||||
# 可选:设备白名单
|
||||
#allowed_devices:
|
||||
# - "24:0A:C4:1D:3B:F0" # MAC地址列表
|
||||
|
||||
xiaozhi:
|
||||
type: hello
|
||||
@@ -27,7 +38,7 @@ delete_audio: true
|
||||
selected_module:
|
||||
ASR: FunASR
|
||||
VAD: SileroVAD
|
||||
LLM: ChatGLMLLM
|
||||
LLM: DifyLLM
|
||||
TTS: EdgeTTS
|
||||
|
||||
ASR:
|
||||
@@ -46,7 +57,7 @@ LLM:
|
||||
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
||||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||
model_name: qwen-turbo
|
||||
api_key: 你的阿里云dashscope api key
|
||||
api_key: 你的deepseek api key
|
||||
DeepSeekLLM:
|
||||
# 可在这里找到你的api key https://platform.deepseek.com/
|
||||
model_name: deepseek-chat
|
||||
@@ -56,12 +67,12 @@ LLM:
|
||||
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
||||
model_name: glm-4-flash
|
||||
url: https://open.bigmodel.cn/api/paas/v4/
|
||||
api_key: 你的bigmodel api key
|
||||
api_key: 你的ChatGLMLLM api key
|
||||
DifyLLM:
|
||||
# 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限
|
||||
# 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词
|
||||
base_url: 你的私有化部署的dify接口地址
|
||||
api_key: 你的dify api key
|
||||
base_url: https://api.dify.cn/v1
|
||||
api_key: 你的DifyLLM api key
|
||||
TTS:
|
||||
EdgeTTS:
|
||||
voice: zh-CN-XiaoxiaoNeural
|
||||
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
# xiaozhi-esp32-server-main/core/auth.py
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class AuthenticationError(Exception):
|
||||
"""认证异常"""
|
||||
pass
|
||||
|
||||
class AuthMiddleware:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.auth_config = config["server"].get("auth", {})
|
||||
# 构建token查找表
|
||||
self.tokens = {
|
||||
item["token"]: item["name"]
|
||||
for item in self.auth_config.get("tokens", [])
|
||||
}
|
||||
# 设备白名单
|
||||
self.allowed_devices = set(
|
||||
self.auth_config.get("allowed_devices", [])
|
||||
)
|
||||
|
||||
async def authenticate(self, headers):
|
||||
"""验证连接请求"""
|
||||
# 检查是否启用认证
|
||||
if not self.auth_config.get("enabled", False):
|
||||
return True
|
||||
|
||||
# 验证Authorization header
|
||||
auth_header = headers.get("Authorization", "")
|
||||
if not auth_header.startswith("Bearer "):
|
||||
logger.error("Missing or invalid Authorization header")
|
||||
raise AuthenticationError("Missing or invalid Authorization header")
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
if token not in self.tokens:
|
||||
logger.error(f"Invalid token: {token}")
|
||||
raise AuthenticationError("Invalid token")
|
||||
|
||||
# 验证Device-Id
|
||||
device_id = headers.get("Device-Id")
|
||||
if not device_id:
|
||||
logger.error("Missing Device-Id header")
|
||||
raise AuthenticationError("Missing Device-Id header")
|
||||
|
||||
# 检查设备白名单
|
||||
if self.allowed_devices and device_id not in self.allowed_devices:
|
||||
logger.error(f"Device not in whitelist: {device_id}")
|
||||
raise AuthenticationError("Device not in whitelist")
|
||||
|
||||
logger.info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}")
|
||||
return True
|
||||
|
||||
def get_token_name(self, token):
|
||||
"""获取token对应的设备名称"""
|
||||
return self.tokens.get(token)
|
||||
|
||||
|
||||
|
||||
+37
-20
@@ -15,12 +15,14 @@ from core.handle.textHandle import handleTextMessage
|
||||
from core.utils.util import get_string_no_punctuation_or_emoji
|
||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
||||
from core.handle.audioHandle import handleAudioMessage, sendAudioMessage
|
||||
from .auth import AuthMiddleware, AuthenticationError
|
||||
|
||||
|
||||
class ConnectionHandler:
|
||||
def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts):
|
||||
self.config = config
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.auth = AuthMiddleware(config)
|
||||
|
||||
self.websocket = None
|
||||
self.headers = None
|
||||
@@ -67,27 +69,42 @@ class ConnectionHandler:
|
||||
self.tts_duration = 0
|
||||
|
||||
async def handle_connection(self, ws):
|
||||
self.websocket = ws
|
||||
"""处理单个WebSocket连接"""
|
||||
self.headers = dict(self.websocket.request.headers)
|
||||
self.logger.info(f"连接建立,请求头:\n{self.headers}")
|
||||
|
||||
self.welcome_msg = self.config["xiaozhi"]
|
||||
self.session_id = str(uuid.uuid4())
|
||||
self.welcome_msg["session_id"] = self.session_id
|
||||
await self.websocket.send(json.dumps(self.welcome_msg))
|
||||
|
||||
await self.loop.run_in_executor(None, self._initialize_components)
|
||||
|
||||
tts_priority = threading.Thread(target=self._priority_thread, daemon=True)
|
||||
tts_priority.start()
|
||||
|
||||
try:
|
||||
async for message in self.websocket:
|
||||
await self._route_message(message)
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
self.logger.info("客户端断开连接")
|
||||
await self.close()
|
||||
# 获取并验证headers
|
||||
self.headers = dict(ws.request.headers)
|
||||
self.logger.info(f"New connection request - Headers: {self.headers}")
|
||||
|
||||
# 进行认证
|
||||
await self.auth.authenticate(self.headers)
|
||||
|
||||
# 认证通过,继续处理
|
||||
self.websocket = ws
|
||||
self.session_id = str(uuid.uuid4())
|
||||
|
||||
self.welcome_msg = self.config["xiaozhi"]
|
||||
self.welcome_msg["session_id"] = self.session_id
|
||||
await self.websocket.send(json.dumps(self.welcome_msg))
|
||||
|
||||
await self.loop.run_in_executor(None, self._initialize_components)
|
||||
|
||||
tts_priority = threading.Thread(target=self._priority_thread, daemon=True)
|
||||
tts_priority.start()
|
||||
|
||||
try:
|
||||
async for message in self.websocket:
|
||||
await self._route_message(message)
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
self.logger.info("客户端断开连接")
|
||||
await self.close()
|
||||
|
||||
except AuthenticationError as e:
|
||||
self.logger.error(f"Authentication failed: {str(e)}")
|
||||
await ws.close()
|
||||
return
|
||||
except Exception as e:
|
||||
self.logger.error(f"Connection error: {str(e)}")
|
||||
await ws.close()
|
||||
return
|
||||
|
||||
async def _route_message(self, message):
|
||||
"""消息路由"""
|
||||
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
services:
|
||||
xiaozhi-esp32-server:
|
||||
image: xiaozhi-esp32-server:0213
|
||||
container_name: xiaozhi-esp32-server
|
||||
restart: always
|
||||
#security_opt:
|
||||
# - seccomp:unconfined
|
||||
ports:
|
||||
- "9005:8000"
|
||||
volumes:
|
||||
- ./config.yaml:/opt/xiaozhi-es32-server/config.yaml
|
||||
- ./models:/opt/xiaozhi-es32-server/models
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user