mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(admin): reject banned users in admin auth (F1) adminAuthMiddleware accepted a Bearer token on session validity plus the ADMINISTRATOR bit alone and never consulted ban state, so a ban never revoked admin-panel access. Adds the auth.IsEffectivelyBanned guard that api.AuthMiddleware already uses, at both admin credential-resolution points. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): gate the voice-channel text subscription on READ_MESSAGES (F2) registerNow subscribed any client with voice state to that channel's text-message topic regardless of READ_MESSAGES. The handshake's already-computed readable-channel set is now passed into registerNow and the subscription only happens when the voice channel is in it, preserving authorized reconnect delivery. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): require READ_MESSAGES to delete messages (F4) The non-DM delete gate checked MANAGE_MESSAGES without READ_MESSAGES, so a role locked out of a private channel could still delete every message in it. Requires ReadMessages alongside ManageMessages (and alongside SendMessages on the author path) and derives the mod flag from that same gate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): require READ_MESSAGES alongside MANAGE_MESSAGES in SetMessagePinned (F8) Pin/unpin checked only MANAGE_MESSAGES, so a role denied READ on a private channel could still pin and unpin its messages. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(service): enforce the DM block at every DM interaction sink (F5) The DM block was only checked on send, leaving edit, reactions, pins and typing as bypasses. One shared requireDMNotBlocked is now called from all of them. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): re-check CONNECT_VOICE when minting a refreshed LiveKit token (F6) voice_token_refresh re-minted a LiveKit token without re-checking CONNECT_VOICE, so a revoked permission kept working for the life of the session. The permission is now re-checked where the token is minted, and a 60s sweep evicts participants whose permission was revoked. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): rate-limit voice_e2ee_offer after validation, keyed on server state (F7) The limiter key was built from unvalidated client input, letting an attacker grow the limiter map without bound. The limiter now runs after validation and keys on (sender, voiceChannelID), never on client input. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(ws): deliver voice_state/voice_leave only to roles that may read the channel (F9) Voice state of private channels was broadcast to every connected client, leaking channel membership. All 11 emit sites now route through one READ-filtered fan-out, channel-tagged so replay filters too. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): redact the LiveKit access token from proxy dial-failure logs (F10) A dial failure wrote the LiveKit access-token JWT into the server log via the URL in the error. redactKey now runs on the error before it reaches slog. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): reserve the [deleted-N] username namespace (F11, F12) The tombstone username namespace used by account deletion was freely registrable, letting a user impersonate a deleted account. The namespace is now reserved at validation, and DeleteAccount retries with a random suffix on collision. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): strip Unicode format characters from upload filenames (F13) The attachment filename sanitizer stripped control characters but not unicode.Cf, allowing bidi-override extension spoofing. Cf is now stripped alongside controls and foreign path separators are cut. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): reserve the login attempt before the bcrypt compare (F3) The per-username lockout was a read-only IsLockedOut check followed by a failure recorded only after the ~250ms bcrypt compare, so N concurrent requests all passed the stale check before any of them recorded a failure. The per-username cap is the only cross-IP brute-force defence (the middleware limits per IP), so a distributed burst landed N guesses per 15-minute window instead of 10. Both counters are now reserved atomically with limiter.Allow before the compare, and the lockout decision moves to the read-only limiter.Check so the reservation is not double-counted. The limits are sized at threshold+1, which leaves the sequential accepted-input set byte-identical to the previous behaviour: failures 1-10 still land, the 10th still trips the lockout, and the account owner's correct password on attempt 10 still returns 200. Sizing at threshold instead would make 9 cheap wrong guesses convert the victim's own correct password into a 15-minute lockout - the regression that got two earlier attempts at this fix rejected, now pinned by a boundary test. Deliberately scoped to handleLogin. The report also suggested widening to the password-confirmation endpoints, but those are authenticated, share a single pw_confirm_fail key across the TOTP endpoints, and widening there is what got the first attempt rejected. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(deps): bump five Rust dependencies in /Client/tauri-client/src-tauri Rolls up dependabot #1259, #1260, #1261, #1262 and #1263: tauri-build 2.5.6 -> 2.6.3 tauri-plugin-fs 2.4.5 -> 2.5.1 tauri-plugin-http 2.5.7 -> 2.5.9 tauri-plugin-store 2.4.2 -> 2.4.4 webpki-roots 1.0.6 -> 1.0.9 All five are lockfile-only; the manifest constraints already permitted the new versions. The five PRs each rewrote overlapping regions of the same Cargo.lock and so could not be merged independently, so the lockfile was regenerated with cargo update --precise for each crate instead. The combined result is smaller than the sum of the five diffs because they share transitive updates. Verified with cargo check --locked --all-targets (exit 0). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(deps): bump typescript-eslint from 8.58.0 to 8.65.0 in /Client/tauri-client Dependabot #1258. 8.65.0 improves @typescript-eslint/no-unnecessary-type-assertion, which surfaces four assertions that were already redundant and now fail the lint gate. They are removed here rather than in a follow-up so no commit in this branch leaves `npm run lint` red: UserBar.ts / members.store.ts "online" as UserStatus -> "online" (the receiver already accepts the literal) media.ts drops `as RequestInit` on a literal that is already assignable LoginForm.ts drops `as { message: unknown }` made redundant by the `"message" in err` narrowing All four are the rule's own autofix. Verified: npm run typecheck, npm run lint, npm run format:check all clean, and the unit suite is 3572/3572 green across 129 files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
240 lines
8.5 KiB
Go
240 lines
8.5 KiB
Go
package ws
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/livekit/protocol/auth"
|
|
"github.com/livekit/protocol/livekit"
|
|
"github.com/livekit/protocol/webhook"
|
|
)
|
|
|
|
// webhookMaxBodyBytes bounds the webhook request body to prevent unbounded
|
|
// reads from an unauthenticated caller.
|
|
const webhookMaxBodyBytes = 64 * 1024
|
|
|
|
// 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 {
|
|
// The SDK receiver verifies the token signature AND that the token's sha256
|
|
// claim matches the request body hash, binding verification to the body so
|
|
// a captured token cannot be replayed against a forged payload.
|
|
provider := auth.NewSimpleKeyProvider(apiKey, apiSecret)
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// Check Authorization header BEFORE reading the body to avoid
|
|
// allocating memory for unauthenticated requests.
|
|
if r.Header.Get("Authorization") == "" {
|
|
slog.Warn("livekit webhook: missing Authorization header")
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Bound the body before the SDK reads it (ReceiveWebhookEvent uses an
|
|
// unbounded io.ReadAll internally).
|
|
r.Body = http.MaxBytesReader(w, r.Body, webhookMaxBodyBytes)
|
|
|
|
// ReceiveWebhookEvent verifies the JWT signature, the token's body-hash
|
|
// claim, and the exp/nbf claims, then parses the payload. This replaces
|
|
// the previous manual ParseAPIToken/Verify sequence, which was not bound
|
|
// to the request body (forgery/replay).
|
|
event, err := webhook.ReceiveWebhookEvent(r, provider)
|
|
if err != nil {
|
|
slog.Warn("livekit webhook: verification failed", "error", err)
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
slog.Info("livekit webhook received",
|
|
"event", event.Event,
|
|
"room", event.GetRoom().GetName(),
|
|
"participant", event.GetParticipant().GetIdentity(),
|
|
)
|
|
|
|
switch event.Event {
|
|
case "participant_joined":
|
|
h.handleWebhookParticipantJoined(r.Context(), event)
|
|
case "participant_left":
|
|
h.handleWebhookParticipantLeft(r.Context(), event)
|
|
default:
|
|
slog.Debug("livekit webhook: unhandled event", "event", event.Event)
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// parseParticipantIdentity extracts a user ID and optional join token from a
|
|
// LiveKit participant identity formatted as "user-{id}" or
|
|
// "user-{id}:{joinToken}".
|
|
func parseParticipantIdentity(identity string) (int64, string, error) {
|
|
if !strings.HasPrefix(identity, "user-") {
|
|
return 0, "", fmt.Errorf("invalid identity format: %s", identity)
|
|
}
|
|
body := identity[5:]
|
|
idPart, joinToken, _ := strings.Cut(body, ":")
|
|
userID, err := strconv.ParseInt(idPart, 10, 64)
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
return userID, joinToken, nil
|
|
}
|
|
|
|
// 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(ctx context.Context, event *livekit.WebhookEvent) {
|
|
p := event.GetParticipant()
|
|
room := event.GetRoom()
|
|
if p == nil || room == nil {
|
|
return
|
|
}
|
|
|
|
userID, joinToken, err := parseParticipantIdentity(p.Identity)
|
|
if err != nil {
|
|
slog.Warn("livekit webhook: participant_joined bad identity",
|
|
"identity", p.Identity, "error", err)
|
|
return
|
|
}
|
|
|
|
channelID, err := parseRoomChannelID(room.Name)
|
|
if err != nil {
|
|
slog.Warn("livekit webhook: participant_joined bad room",
|
|
"room", room.Name, "error", err)
|
|
return
|
|
}
|
|
|
|
slog.Info("livekit webhook: participant joined",
|
|
"user_id", userID,
|
|
"channel_id", channelID,
|
|
"room", room.Name)
|
|
|
|
// Validate that the participant has a matching voice_states row (BUG-127).
|
|
// A replayed token from a previous session will not have a matching row,
|
|
// so we remove the rogue participant from LiveKit.
|
|
if h.db != nil {
|
|
state, stateErr := h.db.GetVoiceState(ctx, userID)
|
|
if stateErr != nil || state == nil || state.ChannelID != channelID {
|
|
slog.Warn("livekit webhook: rogue participant_joined — no matching voice state, removing",
|
|
"user_id", userID, "channel_id", channelID)
|
|
if h.livekit != nil {
|
|
if rmErr := h.livekit.RemoveParticipant(ctx, channelID, userID, joinToken); rmErr != nil {
|
|
slog.Error("livekit webhook: failed to remove rogue participant",
|
|
"error", rmErr, "user_id", userID, "channel_id", channelID)
|
|
}
|
|
}
|
|
return
|
|
}
|
|
// Verify join token matches to prevent token replay from old sessions.
|
|
if joinToken != "" && state.JoinedAt != joinToken {
|
|
slog.Warn("livekit webhook: stale join token on participant_joined, removing",
|
|
"user_id", userID, "channel_id", channelID,
|
|
"expected_token", state.JoinedAt, "got_token", joinToken)
|
|
if h.livekit != nil {
|
|
if rmErr := h.livekit.RemoveParticipant(ctx, channelID, userID, joinToken); rmErr != nil {
|
|
slog.Error("livekit webhook: failed to remove stale participant",
|
|
"error", rmErr, "user_id", userID, "channel_id", channelID)
|
|
}
|
|
}
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) handleWebhookParticipantLeft(ctx context.Context, event *livekit.WebhookEvent) {
|
|
p := event.GetParticipant()
|
|
room := event.GetRoom()
|
|
if p == nil || room == nil {
|
|
return
|
|
}
|
|
|
|
userID, joinToken, err := parseParticipantIdentity(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, F5 reload).
|
|
h.mu.RLock()
|
|
c, exists := h.clients[userID]
|
|
h.mu.RUnlock()
|
|
|
|
if exists {
|
|
currentChID, currentJoinToken := c.getVoiceState()
|
|
if currentChID == channelID && currentJoinToken != "" && currentJoinToken == joinToken {
|
|
// Double-check voice state to guard against a concurrent voice_join
|
|
// that updated the state between the read above and clearVoiceState (L8).
|
|
if reChID, reJT := c.getVoiceState(); reChID == channelID && reJT == joinToken {
|
|
c.clearVoiceState()
|
|
|
|
if h.db != nil {
|
|
if err := leaveVoiceChannelWithRetry(ctx, h, userID, channelID, joinToken); err != nil {
|
|
slog.Error("livekit webhook: LeaveVoiceChannel exhausted retries",
|
|
"error", err, "user_id", userID, "channel_id", channelID)
|
|
}
|
|
}
|
|
|
|
h.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, userID))
|
|
slog.Info("livekit webhook: cleaned up stale voice state",
|
|
"user_id", userID,
|
|
"channel_id", channelID)
|
|
}
|
|
} else if h.db != nil {
|
|
// Client has voiceChID=0 or moved to a different channel (e.g.
|
|
// after F5 reload), or this webhook is for an older join instance.
|
|
deleted, dbErr := h.db.LeaveVoiceChannelIfMatch(ctx, userID, channelID, joinToken)
|
|
if dbErr != nil {
|
|
slog.Error("livekit webhook: LeaveVoiceChannelIfMatch failed (stale DB row)",
|
|
"error", dbErr, "user_id", userID, "channel_id", channelID)
|
|
} else if deleted {
|
|
h.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, userID))
|
|
slog.Info("livekit webhook: cleaned stale DB voice row after reconnect",
|
|
"user_id", userID, "channel_id", channelID)
|
|
}
|
|
}
|
|
} else if h.db != nil {
|
|
// Client already disconnected from WS — use channel-conditional delete
|
|
// to avoid wiping a newer row if the user reconnected and rejoined.
|
|
deleted, dbErr := h.db.LeaveVoiceChannelIfMatch(ctx, userID, channelID, joinToken)
|
|
if dbErr != nil {
|
|
slog.Error("livekit webhook: LeaveVoiceChannelIfMatch failed (client gone)",
|
|
"error", dbErr, "user_id", userID, "channel_id", channelID)
|
|
} else if deleted {
|
|
h.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, 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)
|
|
}
|