#!/usr/bin/env python3 """Tiny token endpoint for the voice UI. Serves POST /token -> { "token": "" } Signs a LiveKit access token with HS256 using the API key/secret from env. The token carries a roomConfig claim requesting the voice-assistant agent, so LiveKit dispatches the agent when the participant joins. Without this, the auto-created room would get no agent at all. Runs as a separate supervisord process; nginx proxies /token to it. """ import base64 import hashlib import hmac import json import os import time import uuid from http.server import BaseHTTPRequestHandler, HTTPServer API_KEY = os.environ.get("LIVEKIT_API_KEY", "devkey") API_SECRET = os.environ.get("LIVEKIT_API_SECRET", "devsecret") AGENT_NAME = os.environ.get("VOICE_AGENT_NAME", "voice-assistant") def b64url(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def make_token(room_name: str, identity: str) -> str: now = int(time.time()) header = {"alg": "HS256", "typ": "JWT"} payload = { "iss": API_KEY, "sub": identity, "nbf": now - 5, "exp": now + 3600, "jti": str(uuid.uuid4()), "identity": identity, "video": { "roomJoin": True, "room": room_name, "canPublish": True, "canSubscribe": True, "canPublishData": True, }, "roomConfig": { "agents": [{"agentName": AGENT_NAME, "jobType": "JT_ROOM"}], }, } h = b64url(json.dumps(header).encode()) p = b64url(json.dumps(payload).encode()) signing_input = f"{h}.{p}".encode() sig = hmac.new(API_SECRET.encode(), signing_input, hashlib.sha256).digest() return f"{h}.{p}.{b64url(sig)}" class Handler(BaseHTTPRequestHandler): def do_POST(self): if self.path != "/token": self.send_response(404) self.end_headers() return length = int(self.headers.get("Content-Length", 0)) body = json.loads(self.rfile.read(length) or b"{}") # Unique room per session so LiveKit dispatches the agent at creation. room_name = f"voice-{uuid.uuid4().hex[:8]}" identity = body.get("identity") or f"user-{uuid.uuid4().hex[:8]}" token = make_token(room_name, identity) resp = json.dumps({"token": token}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(resp))) self.end_headers() self.wfile.write(resp) def log_message(self, format, *args): pass # silence request logging if __name__ == "__main__": server = HTTPServer(("127.0.0.1", 8091), Handler) print("token endpoint listening on 127.0.0.1:8091") server.serve_forever()