diff --git a/config.yaml b/config.yaml index 184182a8..8972fe1d 100644 --- a/config.yaml +++ b/config.yaml @@ -3,9 +3,17 @@ server: # 服务器监听地址和端口(Server listening address and port) ip: 0.0.0.0 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 + # 认证配置 + auth: + enabled: true # 是否启用认证 + tokens: + - token: "test-token" # 设备1的token + name: "xiaozhi-default" # 设备1标识 + - token: "your-token" # 设备2的token + name: "your-device-name" # 设备2标识 + # 可选:设备白名单 + #allowed_devices: + # - "24:0A:C4:1D:3B:F0" # MAC地址列表 xiaozhi: type: hello @@ -51,7 +59,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: # 定义LLM API类型 type: openai @@ -66,7 +74,7 @@ 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 OllamaLLM: # 定义LLM API类型 type: ollama @@ -77,8 +85,8 @@ LLM: type: dify # 建议使用本地部署的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: # 当前支持的type为edge、doubao,可自行适配 EdgeTTS: diff --git a/core/auth.py b/core/auth.py new file mode 100755 index 00000000..d398c72f --- /dev/null +++ b/core/auth.py @@ -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) + + + diff --git a/core/connection.py b/core/connection.py index 6972af76..1e49f163 100644 --- a/core/connection.py +++ b/core/connection.py @@ -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): """消息路由""" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100755 index 00000000..af9ce3a6 --- /dev/null +++ b/docker-compose.yml @@ -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 + + +