217 lines
7.2 KiB
Python
217 lines
7.2 KiB
Python
"""LiveKit wire helpers for the voice session endpoint (HEL-877).
|
|
|
|
Reuses the already-running LiveKit SFU on .12 without adding the ``livekit``
|
|
package to the API process: access tokens are the same HS256 JWTs, and the
|
|
dispatch / room-delete calls use the same Twirp endpoints with the same
|
|
protobuf bodies that the installed SDK (livekit 1.1.20, read-only verified on
|
|
/opt/voice-agent/agent/venv) sends for /opt/voice-agent/web/server.py's
|
|
working /api/token flow. No keys ever leave the server: only the minted,
|
|
short-lived room token is returned to the browser.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import time
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
TWIRP_PREFIX = "/twirp"
|
|
DISPATCH_SERVICE = "livekit.AgentDispatchService"
|
|
ROOM_SERVICE = "livekit.RoomService"
|
|
|
|
|
|
def _b64url(raw: bytes) -> str:
|
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
|
|
|
|
def _jwt_hs256(secret: str, claims: dict[str, Any]) -> str:
|
|
"""HS256 JWT with the exact header the installed SDK's PyJWT produces."""
|
|
header = _b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
|
|
payload = _b64url(json.dumps(claims, separators=(",", ":"), ensure_ascii=False).encode())
|
|
signing_input = f"{header}.{payload}".encode("ascii")
|
|
signature = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
|
|
return f"{header}.{payload}.{signature}"
|
|
|
|
|
|
def _camel(name: str) -> str:
|
|
head, *rest = name.split("_")
|
|
return head + "".join(part.capitalize() for part in rest)
|
|
|
|
|
|
def mint_token(
|
|
api_key: str,
|
|
api_secret: str,
|
|
*,
|
|
identity: str,
|
|
name: str = "",
|
|
room: str = "",
|
|
room_join: bool = False,
|
|
can_publish: bool = True,
|
|
can_subscribe: bool = True,
|
|
ttl_seconds: float = 300.0,
|
|
now: float | None = None,
|
|
) -> str:
|
|
"""Participant access token; claims mirror livekit.api.AccessToken.to_jwt().
|
|
|
|
Video grants are emitted camelCase with empty values dropped, exactly like
|
|
Claims.asdict() in the installed SDK.
|
|
"""
|
|
now = time.time() if now is None else now
|
|
video = {
|
|
_camel(k): v
|
|
for k, v in {
|
|
"room_join": room_join,
|
|
"room": room,
|
|
"can_publish": can_publish,
|
|
"can_subscribe": can_subscribe,
|
|
"can_publish_data": True,
|
|
}.items()
|
|
if v is not None and v != ""
|
|
}
|
|
claims: dict[str, Any] = {"video": video, "sub": identity, "iss": api_key,
|
|
"nbf": int(now), "exp": int(now + ttl_seconds)}
|
|
if name:
|
|
claims["name"] = name
|
|
return _jwt_hs256(api_secret, claims)
|
|
|
|
|
|
def mint_server_token(api_key: str, api_secret: str, ttl_seconds: float = 60.0,
|
|
now: float | None = None) -> str:
|
|
"""Server-API bearer token; matches Service._auth_header() with no grants."""
|
|
now = time.time() if now is None else now
|
|
return _jwt_hs256(
|
|
api_secret,
|
|
{"iss": api_key, "sub": "", "nbf": int(now), "exp": int(now + ttl_seconds)},
|
|
)
|
|
|
|
|
|
def _proto_string(field_number: int, value: str) -> bytes:
|
|
payload = value.encode()
|
|
return bytes([(field_number << 3) | 2]) + _varint(len(payload)) + payload
|
|
|
|
|
|
def _varint(value: int) -> bytes:
|
|
out = bytearray()
|
|
while value > 0x7F:
|
|
out.append((value & 0x7F) | 0x80)
|
|
value >>= 7
|
|
out.append(value)
|
|
return bytes(out)
|
|
|
|
|
|
@dataclass
|
|
class DispatchResult:
|
|
room: str
|
|
dispatch_id: str
|
|
body: dict
|
|
|
|
|
|
async def create_dispatch(
|
|
http: httpx.AsyncClient,
|
|
*,
|
|
internal_url: str,
|
|
api_key: str,
|
|
api_secret: str,
|
|
agent_name: str,
|
|
room: str,
|
|
metadata: str = "",
|
|
timeout: float = 5.0,
|
|
) -> DispatchResult:
|
|
"""Twirp AgentDispatchService/CreateDispatch with an explicit agent_name.
|
|
|
|
Body is livekit.CreateAgentDispatchRequest: field 1 agent_name, field 2 room,
|
|
field 3 metadata (field numbers verified against the installed protocol pkg).
|
|
"""
|
|
body = _proto_string(1, agent_name) + _proto_string(2, room)
|
|
if metadata:
|
|
body += _proto_string(3, metadata)
|
|
response = await http.post(
|
|
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{DISPATCH_SERVICE}/CreateDispatch",
|
|
content=body,
|
|
headers={
|
|
"authorization": f"Bearer {mint_server_token(api_key, api_secret)}",
|
|
"content-type": "application/protobuf",
|
|
},
|
|
timeout=timeout,
|
|
)
|
|
response.raise_for_status()
|
|
parsed = json.loads(response.content or b"{}")
|
|
return DispatchResult(
|
|
room=room,
|
|
dispatch_id=str(parsed.get("id") or parsed.get("dispatchId") or ""),
|
|
body=parsed,
|
|
)
|
|
|
|
|
|
class RoomDeleteError(RuntimeError):
|
|
"""LiveKit refused a room delete with a status other than 2xx/404.
|
|
|
|
Raised (not returned) so callers cannot mistake a failed delete for a
|
|
settled one — the caller must keep the room owned for a bounded retry
|
|
(HEL-879). A 404 answer means the room is already gone and is reported
|
|
as success instead: the delete's goal (room no longer exists) holds.
|
|
"""
|
|
|
|
def __init__(self, status_code: int, room: str) -> None:
|
|
super().__init__(f"delete room {room!r} failed with HTTP {status_code}")
|
|
self.status_code = status_code
|
|
self.room = room
|
|
|
|
|
|
async def delete_room(
|
|
http: httpx.AsyncClient,
|
|
*,
|
|
internal_url: str,
|
|
api_key: str,
|
|
api_secret: str,
|
|
room: str,
|
|
timeout: float = 5.0,
|
|
) -> bool:
|
|
"""Twirp RoomService/DeleteRoom (livekit.DeleteRoomRequest field 1: room).
|
|
|
|
Deleting the room disconnects every participant, ends the dispatched agent
|
|
job and releases the browser microphone server-side.
|
|
|
|
Returns True when the room is gone: 2xx, or 404 (already deleted — the
|
|
retry after a lost response stays idempotent). Any other status raises
|
|
RoomDeleteError so ownership is retained until the delete really lands.
|
|
"""
|
|
response = await http.post(
|
|
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{ROOM_SERVICE}/DeleteRoom",
|
|
content=_proto_string(1, room),
|
|
headers={
|
|
"authorization": f"Bearer {mint_server_token(api_key, api_secret)}",
|
|
"content-type": "application/protobuf",
|
|
},
|
|
timeout=timeout,
|
|
)
|
|
# LiveKit answers DeleteRoom with an empty protobuf body; 404 = already gone.
|
|
if response.status_code // 100 == 2 or response.status_code == 404:
|
|
return True
|
|
raise RoomDeleteError(response.status_code, room)
|
|
|
|
|
|
def decode_token(token: str) -> tuple[dict[str, Any], bytes]:
|
|
"""Header/claims decode without verification (test helper, never trusting input)."""
|
|
header_b64, payload_b64, _ = token.split(".")
|
|
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
|
|
claims = json.loads(base64.urlsafe_b64decode(pad(payload_b64)))
|
|
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
|
|
return claims, signing_input
|
|
|
|
|
|
def verify_signature(token: str, secret: str) -> bool:
|
|
"""Constant-time HS256 check for tests proving the minted token is genuine."""
|
|
parts = token.split(".")
|
|
if len(parts) != 3:
|
|
return False
|
|
signing_input = f"{parts[0]}.{parts[1]}".encode("ascii")
|
|
expected = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
|
|
return hmac.compare_digest(expected, parts[2])
|