feat: firmware-compatible handshake (header auth, transport=websocket) + /ota onboarding endpoint
- auth from Authorization/Device-Id headers (firmware v2.5.0), frame fallback kept
- server hello carries transport=websocket + session_id (firmware ParseServerHello)
- /ota GET+POST returns {websocket:{url,token,version}, server_time:{timestamp,timezone_offset}, firmware:{version}}
- config.yaml: device registered by MAC, ota block added
- 21 tests pass (added OTA + header-auth coverage)
This commit is contained in:
1 parent
14394859aa
commit
a582c1ff36
10 files changed
+178
-26
No files matched your search
@@ -56,6 +56,23 @@ class ProtocolConfig(BaseModel):
|
||||
frame_ms: int = 20 # typical Xiaozhi Opus frame size
|
||||
|
||||
|
||||
class OtaConfig(BaseModel):
|
||||
"""OTA endpoint data (GET/POST /ota) — xiaozhi device onboarding.
|
||||
|
||||
The device bakes in CONFIG_OTA_URL at build time; on boot it POSTs there
|
||||
and reads ``websocket`` {url, token, version} + ``server_time`` from the
|
||||
response. We deliver OUR server URL here — this is how the device learns
|
||||
it must connect to this bridge (firmware detail, verified in
|
||||
xiaozhi-esp32 v2.5.0 main/ota.cc).
|
||||
"""
|
||||
|
||||
server_ws_url: str # absolute wss:// URL the device should connect to
|
||||
server_token: str # token the device presents on the WS handshake
|
||||
protocol_version: int = 1
|
||||
timezone_minutes: int = 420 # UTC+07:00 (Bangkok)
|
||||
firmware_version: str = "2.5.0" # report our own build version
|
||||
|
||||
|
||||
class SecurityConfig(BaseModel):
|
||||
enabled: bool = True
|
||||
devices: list[DeviceConfig] = Field(default_factory=list)
|
||||
@@ -76,6 +93,7 @@ class Config(BaseModel):
|
||||
hermes: HermesConfig = Field(default_factory=HermesConfig)
|
||||
protocol: ProtocolConfig = Field(default_factory=ProtocolConfig)
|
||||
security: SecurityConfig = Field(default_factory=SecurityConfig)
|
||||
ota: Optional[OtaConfig] = None
|
||||
gpu: GpuConfig = Field(default_factory=GpuConfig)
|
||||
|
||||
@classmethod
|
||||
|
||||
+40
-2
@@ -6,7 +6,7 @@ single device-facing endpoint delegates the whole session to
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI, WebSocket
|
||||
from fastapi import FastAPI, Request, WebSocket
|
||||
|
||||
from .config import Config
|
||||
from .hermes import VoiceProfile
|
||||
@@ -32,9 +32,47 @@ def make_app(cfg: Config | None = None) -> FastAPI:
|
||||
|
||||
@app.websocket(cfg.ws_path)
|
||||
async def xiaozhi_endpoint(ws: WebSocket) -> None:
|
||||
loop = DeviceLoop(cfg, profile, auth)
|
||||
# FIRMWARE handshake (xiaozhi v2.5.0): auth travels in HTTP headers,
|
||||
# not the hello frame — Authorization: Bearer <token>, Device-Id: <MAC>.
|
||||
headers = {k.lower(): v for k, v in ws.headers.items()}
|
||||
device_id = headers.get("device-id", "")
|
||||
authorization = headers.get("authorization", "")
|
||||
loop = DeviceLoop(cfg, profile, auth, headers={
|
||||
"device_id": device_id,
|
||||
"authorization": authorization,
|
||||
"client_id": headers.get("client-id", ""),
|
||||
"protocol_version": headers.get("protocol-version", "1"),
|
||||
})
|
||||
await loop.run(ws)
|
||||
|
||||
if cfg.ota is not None:
|
||||
|
||||
def _ota_payload() -> dict:
|
||||
import time
|
||||
|
||||
ota = cfg.ota
|
||||
now_ms = int(time.time() * 1000)
|
||||
return {
|
||||
"websocket": {
|
||||
"url": ota.server_ws_url,
|
||||
"token": ota.server_token,
|
||||
"version": ota.protocol_version,
|
||||
},
|
||||
"server_time": {
|
||||
"timestamp": now_ms,
|
||||
"timezone_offset": ota.timezone_minutes,
|
||||
},
|
||||
"firmware": {"version": ota.firmware_version},
|
||||
}
|
||||
|
||||
@app.get("/ota")
|
||||
async def ota_get() -> dict:
|
||||
return _ota_payload()
|
||||
|
||||
@app.post("/ota")
|
||||
async def ota_post(request: Request) -> dict:
|
||||
return _ota_payload()
|
||||
|
||||
return app
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
The only module that knows Xiaozhi wire format. Everything else talks to a
|
||||
session object, never to raw frames.
|
||||
"""
|
||||
from .protocol import Hello, HelloReply, build_hello, build_hello_reply
|
||||
from .protocol import Hello, ServerHello, build_hello, build_server_hello
|
||||
|
||||
__all__ = ["Hello", "HelloReply", "build_hello", "build_hello_reply"]
|
||||
__all__ = ["Hello", "ServerHello", "build_hello", "build_server_hello"]
|
||||
+18
-12
@@ -7,6 +7,7 @@ Every constant that must match the firmware is marked ``# FIRMWARE``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -23,22 +24,24 @@ class AudioParams(BaseModel):
|
||||
class Hello(BaseModel):
|
||||
"""Device -> Bridge greeting (first text frame)."""
|
||||
type: str = "hello"
|
||||
device_id: str
|
||||
device_id: str = ""
|
||||
client_id: Optional[str] = None
|
||||
authorization: Optional[str] = None # FIRMWARE: token field name
|
||||
protocol_version: int = 1 # FIRMWARE
|
||||
audio_params: AudioParams = Field(default_factory=AudioParams)
|
||||
|
||||
|
||||
class HelloReply(BaseModel):
|
||||
"""Bridge -> Device acknowledgement (keeps the session conversational)."""
|
||||
class ServerHello(BaseModel):
|
||||
"""Bridge -> Device acknowledgement, firmware v2.5.0-compatible.
|
||||
|
||||
FIRMWARE: ParseServerHello requires ``transport == "websocket"`` and
|
||||
reads ``session_id`` + ``audio_params`` (sample_rate, frame_duration).
|
||||
"""
|
||||
type: str = "hello"
|
||||
protocol_version: int = 1
|
||||
server_time: int = 0
|
||||
transport: str = "websocket"
|
||||
session_id: str = ""
|
||||
audio_params: AudioParams = Field(default_factory=AudioParams)
|
||||
# FIRMWARE: some firmwares expect a "name"/"text" greeting.
|
||||
text: str = ""
|
||||
server_time: int = 0
|
||||
|
||||
|
||||
def build_hello(payload: dict) -> Hello:
|
||||
@@ -58,9 +61,12 @@ def build_hello(payload: dict) -> Hello:
|
||||
return Hello.model_validate(data)
|
||||
|
||||
|
||||
def build_hello_reply(session_id: str, protocol: Hello) -> HelloReply:
|
||||
return HelloReply(
|
||||
session_id=session_id,
|
||||
protocol_version=protocol.protocol_version,
|
||||
audio_params=protocol.audio_params,
|
||||
def build_server_hello(device_hello: Hello) -> ServerHello:
|
||||
"""Firmware-compatible server hello (transport=websocket + session_id)."""
|
||||
import time
|
||||
|
||||
return ServerHello(
|
||||
session_id=str(uuid.uuid4()),
|
||||
audio_params=device_hello.audio_params,
|
||||
server_time=int(time.time() * 1000),
|
||||
)
|
||||
@@ -18,16 +18,35 @@ from ..tts import make_tts
|
||||
from ..audio.vad import make_vad
|
||||
from ..security import DeviceAuth, AuthError
|
||||
from ..metrics import LatencyLogger
|
||||
from .protocol import build_hello, build_hello_reply
|
||||
from .protocol import build_hello, build_server_hello
|
||||
from . import messages as msg
|
||||
from .session import Session
|
||||
|
||||
|
||||
def _bearer(value: str | None) -> str | None:
|
||||
"""Strip an optional ``Bearer `` prefix from an Authorization header."""
|
||||
if value is None:
|
||||
return None
|
||||
v = value.strip()
|
||||
if not v:
|
||||
return None
|
||||
if v.lower().startswith("bearer "):
|
||||
return v[7:].strip()
|
||||
return v
|
||||
|
||||
|
||||
class DeviceLoop:
|
||||
def __init__(self, cfg: Config, profile: VoiceProfile, auth: DeviceAuth) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
cfg: Config,
|
||||
profile: VoiceProfile,
|
||||
auth: DeviceAuth,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
self.cfg = cfg
|
||||
self.profile = profile
|
||||
self.auth = auth
|
||||
self.headers = headers or {}
|
||||
|
||||
async def run(self, ws: WebSocket) -> None:
|
||||
await ws.accept()
|
||||
@@ -65,13 +84,19 @@ class DeviceLoop:
|
||||
await ws.send_text(json.dumps({"type": "error", "message": str(exc)}))
|
||||
return None
|
||||
try:
|
||||
self.auth.authenticate(hello.device_id, hello.authorization or "")
|
||||
# FIRMWARE: auth from HTTP headers (Bearer token), not the frame.
|
||||
# Fall back to frame fields for synthetic/test clients.
|
||||
device_id = self.headers.get("device_id") or hello.device_id
|
||||
token = _bearer(self.headers.get("authorization"))
|
||||
if token is None:
|
||||
token = hello.authorization or ""
|
||||
self.auth.authenticate(device_id, token)
|
||||
except AuthError as exc:
|
||||
await ws.send_text(json.dumps({"type": "error", "message": str(exc)}))
|
||||
await ws.close()
|
||||
return None
|
||||
session_id = str(uuid.uuid4())
|
||||
await ws.send_text(json.dumps(build_hello_reply(session_id, hello).model_dump()))
|
||||
await ws.send_text(json.dumps(build_server_hello(hello).model_dump()))
|
||||
return hello
|
||||
|
||||
async def _turn(self, ws: WebSocket, session: Session, pcm: bytes) -> None:
|
||||
|
||||
Binary file not shown.
+13
-2
@@ -41,8 +41,19 @@ hermes:
|
||||
security:
|
||||
enabled: true
|
||||
devices:
|
||||
- device_id: xiaozhi-main
|
||||
token_hash: "b324d2dc2d1242b4df53aca6d1691b062e1d4c085ff90ac45c03e2cec9f18942"
|
||||
# FIRMWARE: Device-Id header = MAC address (xiaozhi v2.5.0), not "xiaozhi-main"
|
||||
- device_id: "b8:f8:62:e8:62:c0"
|
||||
token_hash: "00a83e022237248c6841e61daeb58354645f8d2e0f7fa29fb855a0d098c879df"
|
||||
|
||||
# OTA onboarding: the device POSTs to CONFIG_OTA_URL (baked into firmware at
|
||||
# build time) and reads websocket.url/token here. MUST match the firmware
|
||||
# build's OTA_URL = https://zhi.moreminimore.com/ota
|
||||
ota:
|
||||
server_ws_url: "wss://zhi.moreminimore.com/ws/xiaozhi"
|
||||
server_token: "3d5816c063b19699cdbb9172d54a95f0"
|
||||
protocol_version: 1
|
||||
timezone_minutes: 420 # UTC+07:00
|
||||
firmware_version: "2.5.0-custom"
|
||||
|
||||
gpu:
|
||||
monitor_enabled: true
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import sys, logging
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
||||
import uvicorn
|
||||
uvicorn.run("app.main:app", host="0.0.0.0", port=8766, log_level="info")
|
||||
@@ -30,6 +30,53 @@ def test_health():
|
||||
assert r.json()["status"] == "ok"
|
||||
|
||||
|
||||
def test_ota_endpoint_delivers_server():
|
||||
"""FIRMWARE: device reads websocket.url/token from /ota POST."""
|
||||
cfg = _cfg()
|
||||
from app.config import OtaConfig
|
||||
|
||||
cfg.ota = OtaConfig(
|
||||
server_ws_url="wss://zhi.moreminimore.com/ws/xiaozhi",
|
||||
server_token=TOKEN,
|
||||
)
|
||||
client = TestClient(make_app(cfg))
|
||||
r = client.post("/ota", json={"device_id": "d1"})
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["websocket"]["url"] == "wss://zhi.moreminimore.com/ws/xiaozhi"
|
||||
assert body["websocket"]["token"] == TOKEN
|
||||
assert "server_time" in body
|
||||
|
||||
|
||||
def test_ws_auth_via_headers():
|
||||
"""FIRMWARE: token in Authorization header, Device-Id = MAC."""
|
||||
client = TestClient(make_app(_cfg()))
|
||||
with client.websocket_connect(
|
||||
"/ws/xiaozhi",
|
||||
headers={
|
||||
"Device-Id": "d1",
|
||||
"Authorization": f"Bearer {TOKEN}",
|
||||
},
|
||||
) as ws:
|
||||
# hello frame WITHOUT auth fields — auth came in headers
|
||||
ws.send_text(json.dumps({"device_id": "d1"}))
|
||||
reply = json.loads(ws.receive_text())
|
||||
assert reply["type"] == "hello"
|
||||
assert reply["transport"] == "websocket"
|
||||
assert reply["session_id"]
|
||||
|
||||
|
||||
def test_ws_header_auth_rejects_bad_token():
|
||||
client = TestClient(make_app(_cfg()))
|
||||
with client.websocket_connect(
|
||||
"/ws/xiaozhi",
|
||||
headers={"Device-Id": "d1", "Authorization": "Bearer wrong"},
|
||||
) as ws:
|
||||
ws.send_text(json.dumps({"device_id": "d1"}))
|
||||
reply = json.loads(ws.receive_text())
|
||||
assert reply["type"] == "error"
|
||||
|
||||
|
||||
def test_ws_handshake_and_turn():
|
||||
client = TestClient(make_app(_cfg()))
|
||||
with client.websocket_connect("/ws/xiaozhi") as ws:
|
||||
|
||||
+7
-4
@@ -6,7 +6,7 @@ import asyncio
|
||||
import pytest
|
||||
|
||||
from app.config import Config
|
||||
from app.xiaozhi.protocol import build_hello, build_hello_reply
|
||||
from app.xiaozhi.protocol import build_hello, build_server_hello
|
||||
from app.xiaozhi import messages as msg
|
||||
from app.xiaozhi.session import Session
|
||||
from app.stt import make_stt
|
||||
@@ -26,11 +26,14 @@ def test_hello_parses_firmware_aliases():
|
||||
assert hello.audio_params.sample_rate == 16000
|
||||
|
||||
|
||||
def test_hello_reply_carries_session():
|
||||
def test_server_hello_firmware_compat():
|
||||
hello = build_hello({"device_id": "d1"})
|
||||
reply = build_hello_reply("sess-1", hello)
|
||||
assert reply.session_id == "sess-1"
|
||||
reply = build_server_hello(hello)
|
||||
# FIRMWARE: ParseServerHello requires transport + session_id
|
||||
assert reply.type == "hello"
|
||||
assert reply.transport == "websocket"
|
||||
assert reply.session_id # non-empty uuid
|
||||
assert reply.audio_params.sample_rate == 16000
|
||||
|
||||
|
||||
# ---- auth (REQ-009) ------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user