feat(voiceprint): authenticate voiceprint registration via system secret and optimize docker build

- Add dedicated /chat-history/system and /voice-print/system endpoints for service-to-service calls
- Update ShiroConfig.java to protect internal system endpoints with server secret filter
- Refactor 
egister_voiceprint.py and manage_api_client.py to use ManageApiClient system helpers
- Fix circular import dependency in config_loader.py
- Update .dockerignore to exclude MySQL socket files and data directory from build context
This commit is contained in:
Jordan 2026-10-16 12:33:49 -03:00
parent 0d9692d7fc
commit b19b5904e5
7 changed files with 70 additions and 56 deletions

View file

@ -4,4 +4,8 @@ __pycache__
.env
Dockerfile
tmp/
data/
data/
main/xiaozhi-server/mysql/data/*
main/xiaozhi-server/mysql/
*.sock

View file

@ -360,4 +360,11 @@ public class AgentController {
return new Result<Void>().ok(null);
}
@GetMapping("/{id}/chat-history/system")
@Operation(summary = "Obter histórico recente de áudios (chamada pelo serviço do sistema)")
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentIdSystem(@PathVariable("id") String id) {
List<AgentChatHistoryUserVO> data = agentChatHistoryService.getRecentlyFiftyByAgentId(id);
return new Result<List<AgentChatHistoryUserVO>>().ok(data);
}
}

View file

@ -84,4 +84,14 @@ public class AgentVoicePrintController {
return new Result<List<AgentVoicePrintVO>>().ok(list);
}
@PostMapping("/system")
@Operation(summary = "Criar biometria de voz (Chamada interna do sistema)")
public Result<Void> saveSystem(@RequestBody @Valid AgentVoicePrintSaveDTO dto) {
boolean b = agentVoicePrintService.insert(dto);
if (b) {
return new Result<>();
}
return new Result<Void>().error(ErrorCode.AGENT_VOICEPRINT_CREATE_FAILED);
}
}

View file

@ -99,6 +99,9 @@ public class ShiroConfig {
filterMap.put("/agent/play/**", "anon");
filterMap.put("/voiceClone/play/**", "anon");
filterMap.put("/agent/*/clear-memory", "server");
filterMap.put("/agent/*/chat-history/system", "server");
filterMap.put("/agent/voice-print/system", "server");
filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap);

View file

@ -10,7 +10,6 @@ from config.manage_api_client import (
DeviceNotFoundException,
DeviceBindException,
)
from config.settings import DEFAULT_AGENT_ID
def get_project_dir():
"""获取项目根目录"""

View file

@ -308,6 +308,31 @@ async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optio
f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}",
)
@api_guard("Obter histórico de chat do sistema falhou")
async def get_agent_chat_history_system(instance, agent_id: str) -> Optional[list]:
"""Obtém o histórico de áudios do agente via API de serviço"""
return await instance._execute_async_request(
"GET",
f"/agent/{agent_id}/chat-history/system",
)
@api_guard("Registro de biometria de voz falhou")
async def register_voiceprint_system(
instance, agent_id: str, audio_id: str, speaker_id: str
) -> Optional[Dict]:
"""Cadastra a voz do usuário via API de serviço"""
return await instance._execute_async_request(
"POST",
"/agent/voice-print/system",
json={
"agentId": agent_id,
"audioId": audio_id,
"introduce": speaker_id,
"sourceName": speaker_id,
},
)
def init_service(config):
ManageApiClient(config)

View file

@ -1,10 +1,13 @@
from typing import TYPE_CHECKING, Optional
import requests
import logging
import traceback
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from config.logger import setup_logging
from config.settings import XIAOZHI_BASE_URL, XIAOZHI_USER_TOKEN, DEFAULT_AGENT_ID
from config.manage_api_client import (
get_agent_chat_history_system,
register_voiceprint_system,
)
from config.settings import DEFAULT_AGENT_ID
if TYPE_CHECKING:
from core.connection import ConnectionHandler
@ -34,50 +37,35 @@ register_voiceprint_function_desc = {
@register_function(
"register_voiceprint", register_voiceprint_function_desc, ToolType.SYSTEM_CTL
)
def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = None):
async def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = None):
try:
# Configuração do Agent ID e Token de Autenticação ainda hardcoded
# TODO: Implementar a obtenção dinâmica do token de autenticação, aparentemente o agent_id não muda
agent_id = getattr(conn, "agent_id", None) or DEFAULT_AGENT_ID
agent_id = DEFAULT_AGENT_ID
user_token = XIAOZHI_USER_TOKEN
base_url = XIAOZHI_BASE_URL
headers = {"Content-Type": "application/json"}
if user_token:
headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token
# Buscar histórico recente de áudios via helper do ManageApiClient
logger.bind(tag=TAG).info(f"[Voiceprint] Buscando histórico para o agente {agent_id}")
audio_list = await get_agent_chat_history_system(agent_id)
# Consultar o histórico de áudios
history_url = f"{base_url}/agent/{agent_id}/chat-history/user"
logger.bind(tag=TAG).info(f"[Voiceprint] Buscando histórico em: {history_url}")
history_res = requests.get(history_url, headers=headers, timeout=5)
logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do histórico ({history_res.status_code}): {history_res.text}")
if history_res.status_code != 200:
if audio_list is None:
return ActionResponse(
action=Action.NONE,
result=f"Erro na API de histórico: status {history_res.status_code}",
result="Erro na API ao buscar histórico",
response="Não consegui obter o histórico recente para cadastrar sua voz."
)
history_data = history_res.json()
audio_list = history_data.get("data", [])
if not audio_list:
logger.bind(tag=TAG).warning("[Voiceprint] A API retornou uma lista de áudios vazia (data: []).")
logger.bind(tag=TAG).warning("[Voiceprint] Histórico de áudios retornado está vazio.")
return ActionResponse(
action=Action.NONE,
result="Nenhum áudio encontrado no histórico do agente",
response="Não encontrei nenhum registro de voz recente no histórico."
)
# evita registrar a voz se o usuário apenas perguntou "quem sou eu" ou algo similar
# Evita registrar se for apenas pergunta de identidade
user_text = audio_list[0].get("content", "").lower()
perguntas_identidade = ["quem sou", "me diga quem", "qual é o meu nome", "qual meu nome"]
if any(p in user_text for p in perguntas_identidade):
logger.bind(tag=TAG).info(f"[Voiceprint] Interceptado: Usuário apenas perguntou a identidade ('{user_text}'). Cancelando registro.")
logger.bind(tag=TAG).info(f"[Voiceprint] Interceptado: Pergunta de identidade ('{user_text}'). Cancelando registro.")
return ActionResponse(
action=Action.NONE,
result="Ignorado: O usuário apenas perguntou quem ele é.",
@ -98,42 +86,20 @@ def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = N
logger.bind(tag=TAG).info(f"[Voiceprint] Áudio selecionado: audioId={audio_id}, texto='{latest_audio.get('content')}'")
# Enviar requisição de salvamento do Voiceprint
register_url = f"{base_url}/agent/voice-print"
payload = {
"agentId": agent_id,
"audioId": audio_id,
"introduce": speaker_id,
"sourceName": speaker_id
}
# Registrar biometria de voz no backend Java
logger.bind(tag=TAG).info(f"[Voiceprint] Registrando biometria para {speaker_id}")
res = await register_voiceprint_system(agent_id, audio_id, speaker_id)
logger.bind(tag=TAG).info(f"[Voiceprint] Enviando cadastro: {payload}")
register_res = requests.post(register_url, json=payload, headers=headers, timeout=5)
logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do cadastro ({register_res.status_code}): {register_res.text}")
res_json = register_res.json() if register_res.status_code == 200 else {}
code = res_json.get("code")
# Sucesso
if register_res.status_code == 200 and code == 0:
if res is not None:
return ActionResponse(
action=Action.RESPONSE,
result=f"Voiceprint de {speaker_id} registrado com sucesso",
response=f"Pronto! Cadastrei a voz de {speaker_id} no sistema."
)
# Tratamento da voz já cadastrada
elif code == 10080:
logger.bind(tag=TAG).info(f"[Voiceprint] Voz já cadastrada anteriormente como {speaker_id}.")
return ActionResponse(
action=Action.RESPONSE,
result=f"Voz já cadastrada para {speaker_id}",
response=f"Sua voz já está cadastrada no sistema como {speaker_id}."
)
# Outros erros
else:
return ActionResponse(
action=Action.NONE,
result=f"Falha no salvamento: {register_res.text}",
result="Falha no salvamento do Voiceprint",
response="Ocorreu um erro no servidor ao tentar salvar sua voz."
)