Files
OwnCord/Server/ws/livekit_webhook.go
T
jevb 7978ec40e8 fix: security hardening, LiveKit class refactor, and eng review fixes
Server:
- Fix YAML injection in LiveKit config generation (quote values)
- Revert token TTL to 4h (no server-side JWT revocation)
- Derive LiveKit publish permissions from user role (prevent SFU bypass)
- Add CAS guard for webhook/voice_leave race condition
- Add voice_leave broadcast to rollbackVoiceJoin (prevent ghost state)
- Limit webhook body to 64KB (prevent memory abuse)
- Add rate limit to voice_token_refresh handler (1/60s)
- Add LiveKit health check endpoint (GET /api/v1/livekit/health, 503 on degraded)
- Add voice_token_refresh WS handler for client-initiated token refresh
- Consolidate voice quality constants (single source of truth)
- Fix video limit TOCTOU race (count from DB instead of LiveKit API)
- Raise default voice_max_video from 10 to 25 (Discord parity)
- Add CountActiveCameras DB query
- Non-blocking broadcast send, circuit breaker, exponential backoff
- Close send channel before context cancel in serve.go
- Guard voice mute/deafen for active channel
- Delete orphaned message on attachment link failure
- Redact query string from proxy logs (prevent token leak)
- Use instance-level HTTP client for health checks (no redirect following)
- Set cmd.WaitDelay to prevent goroutine leak on Windows
- Log buildJSON marshal errors

Client:
- Refactor livekitSession.ts from singleton module to LiveKitSession class
- Share single AudioContext for all analysers (was 1 per participant)
- Extract createRoom() helper (DRY)
- Add token refresh timer (3.5h interval, re-arms on failure)
- Skip setSpeakers if unchanged (sort in-place, no allocations)
- Distinguish user-initiated leave from connection error in retry
- Add YouTube videoId validation (prevent iframe src injection)
- Add try/finally to disableCamera
- Wrap store subscription callbacks in try/catch
- Track and cancel initial scroll RAF on cleanup
- Add 5s timeout + encodeURIComponent to YouTube oEmbed fetch
- Clean raw mic stream on RNNoise suppressor failure
- Full voice cleanup on logout via cleanupAll()

Tests:
- Add 7 new server tests (webhook parsing, voice guards, quality fallback)
- Fix 2 pre-existing test failures (mute/deafen invalid payload)
2026-03-21 11:59:14 +01:00

181 lines
5.2 KiB
Go

package ws
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
)
// NewLiveKitWebhookHandler returns an HTTP handler that processes LiveKit
// webhook events. It synchronises LiveKit room state back into OwnCord's
// voice_states DB — primarily for crash recovery when a participant
// disconnects from LiveKit without sending a WS voice_leave.
//
// Speaker detection is handled client-side via LiveKit's
// RoomEvent.ActiveSpeakersChanged (lower latency than webhooks).
func (h *Hub) NewLiveKitWebhookHandler(apiKey, apiSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 64*1024))
if err != nil {
slog.Error("livekit webhook: read body failed", "error", err)
http.Error(w, "bad request", http.StatusBadRequest)
return
}
// Verify the webhook token from the Authorization header.
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
slog.Warn("livekit webhook: missing Authorization header")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// LiveKit sends "Bearer <token>" in the Authorization header.
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
verifier, err := auth.ParseAPIToken(tokenStr)
if err != nil {
slog.Warn("livekit webhook: invalid token", "error", err)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if verifier.APIKey() != apiKey {
slog.Warn("livekit webhook: API key mismatch",
"got", verifier.APIKey(), "want", apiKey)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if _, _, err := verifier.Verify(apiSecret); err != nil {
slog.Warn("livekit webhook: token verification failed", "error", err)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// Parse the webhook event payload.
var event livekit.WebhookEvent
if err := json.Unmarshal(body, &event); err != nil {
slog.Warn("livekit webhook: invalid JSON", "error", err)
http.Error(w, "bad request", http.StatusBadRequest)
return
}
switch event.Event {
case "participant_joined":
h.handleWebhookParticipantJoined(&event)
case "participant_left":
h.handleWebhookParticipantLeft(&event)
default:
slog.Debug("livekit webhook: unhandled event", "event", event.Event)
}
w.WriteHeader(http.StatusOK)
}
}
// parseIdentity extracts a user ID from a LiveKit participant identity
// formatted as "user-{id}".
func parseIdentity(identity string) (int64, error) {
if !strings.HasPrefix(identity, "user-") {
return 0, fmt.Errorf("invalid identity format: %s", identity)
}
return strconv.ParseInt(identity[5:], 10, 64)
}
// parseRoomChannelID extracts a channel ID from a LiveKit room name
// formatted as "channel-{id}".
func parseRoomChannelID(roomName string) (int64, error) {
if !strings.HasPrefix(roomName, "channel-") {
return 0, fmt.Errorf("invalid room name format: %s", roomName)
}
return strconv.ParseInt(roomName[8:], 10, 64)
}
func (h *Hub) handleWebhookParticipantJoined(event *livekit.WebhookEvent) {
p := event.GetParticipant()
if p == nil {
return
}
userID, err := parseIdentity(p.Identity)
if err != nil {
slog.Warn("livekit webhook: participant_joined bad identity",
"identity", p.Identity, "error", err)
return
}
slog.Info("livekit webhook: participant joined",
"user_id", userID,
"room", event.GetRoom().GetName())
// State is already persisted by handleVoiceJoin before the token is
// issued. This webhook confirms the client actually connected.
}
func (h *Hub) handleWebhookParticipantLeft(event *livekit.WebhookEvent) {
p := event.GetParticipant()
room := event.GetRoom()
if p == nil || room == nil {
return
}
userID, err := parseIdentity(p.Identity)
if err != nil {
slog.Warn("livekit webhook: participant_left bad identity",
"identity", p.Identity, "error", err)
return
}
channelID, err := parseRoomChannelID(room.Name)
if err != nil {
slog.Warn("livekit webhook: participant_left bad room",
"room", room.Name, "error", err)
return
}
slog.Info("livekit webhook: participant left",
"user_id", userID,
"channel_id", channelID)
// Clean up voice state if the user disconnected from LiveKit
// without sending a WS voice_leave (e.g. crash, network loss).
h.mu.RLock()
c, exists := h.clients[userID]
h.mu.RUnlock()
if exists {
// Only clean up if the user is still in the channel that fired the
// webhook. If they've already moved or left, don't touch their state.
currentChID := c.getVoiceChID()
if currentChID == channelID {
c.clearVoiceChID()
if h.db != nil {
_ = h.db.LeaveVoiceChannel(userID)
}
h.BroadcastToAll(buildVoiceLeave(channelID, userID))
slog.Info("livekit webhook: cleaned up stale voice state",
"user_id", userID,
"channel_id", channelID)
}
} else {
// Client already disconnected from WS — ensure DB is clean.
if h.db != nil {
_ = h.db.LeaveVoiceChannel(userID)
}
}
}
// MountWebhookRoute is a helper for the router to mount the webhook endpoint.
func MountWebhookRoute(h *Hub, apiKey, apiSecret string) http.HandlerFunc {
return h.NewLiveKitWebhookHandler(apiKey, apiSecret)
}