Files
OwnCord/Server/ws/voice_join.go
T
J3vbandClaude Opus 5 39551de4a6 refactor(server): work off the complexity backlog — 62 findings to 0 (#1389)
* refactor(ws): split handleVoiceJoin into cohesive join-stage helpers

handleVoiceJoin was 130 statements / cyclomatic 59 / nestif 11, breaking all
three complexity budgets at once. Split along the stage boundaries the doc
comment already described: precheck, leave-current, persist, restore
moderator flags, grant token, complete. The publish-permission derivation
becomes its own helper because it is the one branch-heavy block inside the
token grant.

Pure move: every statement is preserved verbatim. The only edits are bare
`return`s becoming the typed returns of their new helper, `c.userID` becoming
the `userID` parameter inside voiceJoinPublishPerms, and voiceJoinComplete
re-reading `ch.VoiceMaxUsers` instead of receiving it — `ch` is never mutated,
so the value is identical.

Verified by normalising both revisions of the region to sorted, comment- and
whitespace-stripped statements and diffing: the only deltas are the ones
listed above.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: collapse the three duplicated sibling pairs

dupl flagged three pairs of adjacent near-identical functions. Each pair is
now one parameterised implementation plus two thin, still-greppable wrappers.

- ws/voice_controls.go: handleVoiceMuteV2 / handleVoiceDeafenV2 share
  voiceSelfToggleV2; handleVoiceCameraV2 / handleVoiceScreenshareV2 share
  voiceStreamToggleV2. Camera and screenshare drawing from one
  voice_max_video budget (OC-0023) was a bug caused by exactly this
  duplication drifting, so one body is the point, not a side effect.
- db/mention_queries.go: ListMentionTargetsByRoles / ListMentionTargetsByUserIDs
  share listMentionTargets. The matched column is a closed named type
  (mentionTargetColumn) rather than a bare string, so the value interpolated
  into the SELECT cannot become caller-supplied.

Behaviour is unchanged: every rate-limit key, error code, error string, slog
message and slog key is preserved verbatim, including the two "failed to
update <kind> state" messages, which are now assembled the same way
enableVideoSlot already assembled them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(api): extract readEmojiUpload from handleCreateEmoji

handleCreateEmoji was 101 lines against a 100-line budget. The upload-bytes
stage — pull the file out of the parsed form, cap its size, sniff its MIME
type and sniff its dimensions — is the one self-contained block in it, and it
already wrote its own refusals, so it moves out whole as readEmojiUpload.

The permission-before-parse ordering the doc comment calls out is unchanged;
so is every error string. file.Close() now runs when the helper returns
rather than when the handler does, which is strictly earlier and unobservable:
the bytes are already copied into raw and nothing else touches the handle.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: extract one cohesive block from three single-budget offenders

Each of these was over exactly one budget, so each gets exactly one extraction
rather than a restructure:

- api/totp_handler.go handleVerifyTOTP (102 lines / 100): the block that
  resolves the user behind the partial-auth challenge and decrypts their TOTP
  secret becomes totpChallengeSecret. The ban-inside-the-partial-window check
  moves with it.
- service/message_reactions.go handleReaction (cyclop 21 / 20): the whole
  authorisation chain — channel lookup, archived gate, DM participant and
  block checks, non-DM permission check — becomes reactionAudience, which
  also returns the DM fan-out audience it already resolved. Check order is
  unchanged and load-bearing.
- db/admin_queries.go BackupToSafe (cyclop 21 / 20): the character allowlist
  loop and the SQL-comment rejection become validateBackupPathChars. That
  loop alone was most of the branch count.

No error string, no check and no ordering changed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(plugin): split InstallFromZip into staged install helpers

104 statements / cyclomatic 44 / nestif 12. Split along the stages the code
already had: installZipExtract (the per-entry write loop, with
installZipEntryDest holding the mode/symlink/zip-slip guard chain and
installZipWriteEntry the size-capped copy), installZipStagedManifest,
installZipPromote, and installZipReactivate for the :399 nested block.

Every zip-slip, symlink, entry-mode and uncompressed-size check is preserved
in the same order relative to the writes it guards. The 19 inline
`cleanup(); return` sites collapse to 4 in the orchestrator, one per stage,
because each helper now returns an error instead of unwinding itself — the
staging directory is still removed on exactly the same set of failures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(api): split newWAFMiddleware into engine build and per-phase helpers

184 lines / cyclomatic 38, and the request-body block at :382 was the worst
nested site in the tree at nestif 17.

Engine construction moves out of the closure (wafInlineEngine, wafCRSEngine —
the Coraza directive string is lifted verbatim), and each request phase
becomes its own helper: wafInlineRequestHeaders, wafCRSRequestHeaders
(including the Host/Transfer-Encoding re-add for CRS 920280), wafFeedCRSBody
and wafInspectRequestBody, which is the old :382 block.

The three `handleWAFInterruption(w, it); return` sites inside the body block
become one: the helper now returns the interruption and the orchestrator
handles it. No statement runs between the two points on either side, so the
verdict is honoured identically — in particular a CRS body interruption still
returns without replacing r.Body.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(service): split SendMessage and lift EditMessage's access check

SendMessage was 79 statements / cyclomatic 35 with an 11-deep nested
attachment block at :101; EditMessage was one point over cyclop.

SendMessage becomes sendMessagePrecheck (permission and DM-block gates,
content sanitisation), sendMessageLinkAttachments (the :101 block: attachment
ownership, claim and link) and sendMessageDMSideEffects. EditMessage gets
editMessageCheckAccess and nothing else — one budget over earns one
extraction.

The sanitizeContent fixpoint and the attachment ownership check are unchanged,
as is the order of every gate. The DM side effects run behind
`isDM && !s.sendMessageDMSideEffects(...)`, so a non-DM never enters them;
inside, only the GetDMParticipantIDs failure returns false, matching the one
error the original early-returned on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(admin): split handlePatchUser into per-field apply helpers

106 lines / cyclomatic 29, with the ban block at :154 nested 9 deep.

Each optional field of the partial edit becomes its own helper —
patchUserPrecheck, patchUserAuthorizeRole, patchUserApplyBan (the :154 block,
including the session disconnect and the broadcast) and patchUserApplyRole.
Each returns a bool meaning "keep going"; none of them writes a success
response, so the single response site in the orchestrator is unchanged.

Field application order, the permission-cache invalidation on a role change
and the disconnect-and-broadcast on a ban are all preserved, as are the three
fail-closed `mod == nil` guards, which now sit at the top of their own helper
and still fire on exactly the same conditions.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(admin): split handleSetup into first-run setup stages

143 lines / cyclomatic 30, with the optional-wizard block at :219 sitting
exactly on the nestif threshold.

Split into the stages the endpoint already had: request gating (rate limit and
origin check, which run before any auth exists on a fresh server), owner
account creation, and the wizard application that was the :219 block.

Every gate in front of the handler is a security control on an unauthenticated
endpoint; none moved relative to the work it protects. setup_wizard.go is
untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: split run() into named bootstrap and shutdown steps

131 statements / cyclomatic 57, with the executable-path fallback at :126
nested 9 deep.

The five anonymous `defer func(){...}()` blocks become named functions —
telemetryStop, runClosePlugins, runStopEventPersistence, runStopAuditWriter,
maintenanceStop — and the bootstrap stages move out likewise.

Every defer is still registered in run() itself, at the same point in the
sequence, so the LIFO teardown order is unchanged; that order is documented
in the surrounding comments and is load-bearing (the audit-writer stop must
follow database.Close's registration, the event-persistence stop must precede
it). runStopEventPersistence is now registered unconditionally with a nil
persister meaning "disabled", where the old code registered its defer inside
the enabled branch — a no-op occupying that slot cannot change the relative
order of the others.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(ws): split handleReconnect into resume stages

77 statements / cyclomatic 41, plus the replay block at :199 and, in
handleFreshConnect, the voice-state restore at :622.

handleReconnect becomes reconnectPrecheck, reconnectSelectReplay (with
reconnectVetColdTail for the cold-tier gap check), reconnectRegister and
reconnectWriteReplay. handleFreshConnect's stale-voice cleanup moves to its
own helper, where the `if h.livekit != nil` wrapper becomes a guard clause —
that block was the tail of its scope, so returning early and falling off the
end are the same.

The parts that carry the invariants are moved verbatim: reconnectRegister
still takes h.seqMu, still calls registerNow inside that same critical
section (BUG-123 / OC-0206), still unlocks on every exit, and still emits the
"full" tier counter and telemetry on each of its three re-check failures.
handleReconnect's two-boolean contract is unchanged — the collapsed
`return false, false` sites are all fall-through-to-full-ready, and the
single `return true, false` is still the handshake-write-failure path whose
teardown already ran (OC-0051).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(server): fold in the adversarial review of the complexity refactors

Eleven skeptic passes over the refactor commits on this branch found no
blocker and no major — behaviour is preserved throughout. They did find
comment and accuracy defects worth correcting:

- db/mention_queries.go: the mentionTargetColumn rationale claimed the named
  type made the interpolated column "only ever one of the two constants". A
  Go named type is not closed, so that is a convention the type makes visible,
  not one it enforces. Reworded, gosec justification included.
- ws/voice_controls.go: the dupl collapse generalised away three specifics —
  that a server deafen is the moderator's to lift (now on the serverDeafen
  field), the concrete voice_states.camera / voice_states.screenshare column
  names, and the half of the OC-0023 rationale about neither stream kind
  hiding from the other's count. All three restored.
- ws/voice_join.go: `maxUsers := ch.VoiceMaxUsers` had been hoisted to the top
  of voiceJoinComplete, moving a read across the tail supersession guard. The
  read is inert, but it was the one statement in that commit whose position
  relative to a security guard changed; it now sits at its use, as before.
- ws/*_test.go: three test comments cited voice_join.go line numbers that the
  split invalidated. They now cite the helper by name instead.
- service/message_reactions.go: reactionAudience's doc claimed to enforce
  "every gate on reacting"; it enforces the channel-scoped ones, and the doc
  now says which gates stay with the caller.
- api/emoji_handler.go: the readEmojiUpload call reused the outer `ok` from
  the auth check by assignment; it gets its own readOK.
- admin/setup_handler.go: a moved comment kept a "the response above" deictic
  that no longer had a response above it.

No behaviour change. Build, vet, full tests and -race on five packages green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(ws): clear the remaining complexity budgets across the hub

Eight files, thirteen findings. Each function is split at the stages it
already had; no branch is reordered, merged or inverted.

- handlers.go handleMessage (cyclop 28, 88 stmts): session re-check, frame
  decode and result application become handleMessageSessionRecheck,
  handleMessageDecode and handleMessageApply. The V2 constructor lookup ->
  DispatchV2 -> Result resolution order is untouched.
- serve_ready.go buildReady (cyclop 26, 61 stmts): the per-section fetches
  split out, readyChannelPayloads among them. Every visibility predicate is
  preserved verbatim — this is the payload that decides what a client may see.
- serve_pumps.go writePump (cyclop 31): writePumpWrite, writePumpDeliver,
  writePumpDrainChannel and writePumpDrainAndClose. Every channel receive
  stays in the same select statement, so scheduling is unchanged.
- hub_sweep.go sweepStaleVoiceStates (cyclop 22, 56 stmts): the staleness
  predicate, the hub-lock ordering and the position of the race hook are all
  as they were — handleVoiceJoin's BUG-088 ordering depends on them.
- hub_broadcast.go channelReadAudienceImpl and RefreshChannelVisibility
  (cyclop 22 each, 57 stmts): channelReadAudienceDM and
  refreshChannelVisibilityCanSend. The audience predicate is the OC-0090
  group-DM leak surface, so it is extracted, never simplified.
- livekit_webhook.go (nestif 13 and 14): webhookJoinedEnforceVoiceState,
  webhookLeftCleanupClient and webhookLeftFinishLeave. DB delete still
  precedes broadcast on every path.
- livekit_download.go EnsureLiveKitBinary (52 stmts): one extraction,
  ensureLiveKitStageBinary, keeping every archive path check intact.
- voice_moderation.go (nestif 8): voiceModDeafenRollback. The persisted
  server_muted flag remains the authority.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(api): clear the remaining complexity budgets across the HTTP layer

- router.go NewRouter (cyclop 28, 84 stmts): split by wiring concern into
  routerTOTPKey, routerHealthDeps, routerMiddleware, routerUploadRoutes,
  routerPluginWiring, routerVoiceRoutes and routerMetricsRoutes. Middleware
  ORDER is a security property (auth before handler, WAF before body parse,
  rate limit before work) and is unchanged; the returned cleanup func still
  closes over and releases everything it did before.
- auth_handler.go handleRegister (133 lines) and handleLogin (cyclop 21,
  152 lines): registerPolicyGate, registerReadRequest, loginReadRequest and
  loginAuthenticate. The always-compare posture, every rate-limit key, every
  counter reset and the ban-check-versus-password-compare order are all
  preserved — including loginUserFailureThreshold staying unscaled by
  scaledAuthLimit, which is deliberate and commented.
- upload_handler.go handleServeFile (cyclop 31, 128 lines): serveFileResolve
  and serveFileAuthorize. Every header this sets — Content-Disposition
  included, which is what stops a stored file being served as active content —
  is still set with the same value in the same circumstances.
- profile_handler.go handleUploadAvatar (120 lines): avatarUploadReadImage,
  mirroring readEmojiUpload in shape but with the avatar caps and MIME set.
  The two deliberately do not share a helper.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: clear the last complexity budgets in db and admin

- db/account.go DeleteAccount (cyclop 28, 55 stmts): grouped by subsystem into
  deleteAccountAdminGuard, deleteAccountDMChannels and
  deleteAccountCloseDMChannels, each taking the same transaction. The
  transaction boundary, the delete ORDER (which foreign keys depend on) and
  the rollback path are unchanged.
- admin/logstream.go handleLogStream (cyclop 24): logStreamAuthorize. Flush
  cadence, heartbeat and disconnect detection untouched.
- admin/setup_wizard.go validateWizard (cyclop 23): grouped by section into
  wizardValidateIdentity, wizardValidateNetwork and wizardValidateMedia. Every
  message and bound is unchanged — this is the first input-validation boundary
  on a fresh server, before any auth exists.

With this the tree is at zero: golangci-lint run reports 0 issues against the
budgets set in #1384 (funlen 100/50, cyclop 20, nestif 8, dupl 150), with no
//nolint and no exclusion added anywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-18 20:39:45 +02:00

656 lines
30 KiB
Go

package ws
import (
"context"
"encoding/json"
"errors"
"log/slog"
"time"
"github.com/owncord/server/auth"
"github.com/owncord/server/db"
"github.com/owncord/server/permissions"
"github.com/owncord/server/service"
)
// Voice join/leave rate limits. voice_join and voice_leave each fan out a
// broadcast to every connected client, so a single user must not be able to
// trigger them in a tight loop. Mirrors the named-constant idiom used by the
// voice control handlers (see voice_broadcast.go / voice_controls.go).
// voiceLeaveRateLimit/Window are consumed by the voice_leave message dispatch
// in handlers_voice.go (same package).
const (
voiceJoinRateLimit = 5
voiceJoinWindow = time.Second
voiceLeaveRateLimit = 5
voiceLeaveWindow = time.Second
)
// validVoiceQuality returns true if q is an accepted voice quality preset.
// Uses voiceQualities (defined in voice_broadcast.go) as the single source of truth.
func validVoiceQuality(q string) bool {
_, ok := voiceQualities[q]
return ok
}
// voiceJoinPostTokenRaceHook, when non-nil, runs immediately after
// GenerateToken succeeds and before the minted token is checked for
// supersession / handed to the client. Test-only (always nil in production):
// GenerateToken is a local JWT mint with no I/O, so the window it pins (a
// concurrent eviction landing between token generation and delivery, OC-0008)
// is too narrow to land reliably by staggering real goroutines. Mirrors
// cleanupVoiceRaceClearHook (hub_sweep.go), used the same way for the
// analogous CleanupVoiceForChannel race.
var voiceJoinPostTokenRaceHook func(*Client)
// handleVoiceJoin processes a voice_join message.
// 1. Parses channel_id.
// 2. Checks CONNECT_VOICE permission.
// 3. If already in a different voice channel, leaves it first.
// 4. Checks channel capacity (voice_max_users).
// 5. Persists join in DB.
// 6. Generates LiveKit token and sends voice_token to the client.
// 7. Sends existing voice states to the joiner.
// 8. Broadcasts voice_state to all clients.
// 9. Sends voice_config to the joiner.
func (h *Hub) handleVoiceJoin(ctx context.Context, c *Client, payload json.RawMessage) {
channelID, ch, ok := h.voiceJoinPrecheck(ctx, c, payload)
if !ok {
return
}
wasServerMuted, wasServerDeafened, ok := h.voiceJoinLeaveCurrent(ctx, c, channelID)
if !ok {
return
}
state, ok := h.voiceJoinPersist(ctx, c, ch, channelID)
if !ok {
return
}
state = h.voiceJoinRestoreModFlags(ctx, c, channelID, state, wasServerMuted, wasServerDeafened)
if !h.voiceJoinGrantToken(ctx, c, channelID, state) {
return
}
h.voiceJoinComplete(ctx, c, ch, channelID, state)
}
// voiceJoinPrecheck runs every gate that must pass before handleVoiceJoin
// mutates any state: rate limit, payload parse, CONNECT_VOICE, channel
// existence, channel type, DM block, archive, authenticated user and LiveKit
// availability. It reports the target channel id and row when the join may
// proceed; on refusal it has already sent the error frame and returns false.
func (h *Hub) voiceJoinPrecheck(ctx context.Context, c *Client, payload json.RawMessage) (int64, *db.Channel, bool) {
// Rate limit: voice_join broadcasts a voice_state update to every connected
// client, so cap how often a single user can trigger the fan-out. Mirrors the
// Limiter.Allow(...) idiom used by the voice control handlers.
ratKey := auth.Key("voice_join", c.userID)
if h.limiter != nil && !h.limiter.Allow(ratKey, voiceJoinRateLimit, voiceJoinWindow) {
c.sendMsg(buildErrorMsg(ErrCodeRateLimited, "too many voice join attempts"))
return 0, nil, false
}
channelID, err := parseChannelID(payload)
if err != nil || channelID <= 0 {
c.sendMsg(buildErrorMsg(ErrCodeBadRequest, "channel_id must be a positive integer"))
return 0, nil, false
}
// channel_id is attacker-controlled, so the gate must be channel-TYPE aware:
// a role-only check passes for any DM channel id (DMs have no overrides), and
// the token minted below carries RoomJoin+CanSubscribe for that DM's room.
if !h.requireChannelAccess(ctx, c, channelID, permissions.ConnectVoice, "CONNECT_VOICE") {
return 0, nil, false
}
// Validate the target channel exists before any state changes (leaving
// the current voice channel, persisting join, etc.).
ch, err := h.db.GetChannel(ctx, channelID)
if err != nil || ch == nil {
c.sendMsg(buildErrorMsg(ErrCodeNotFound, "channel not found"))
return 0, nil, false
}
// channel_id is attacker-controlled and requireChannelAccess above only
// gates CONNECT_VOICE, which says nothing about channel type — a text or
// announcement channel would otherwise accept a join, persist a
// voice_states row, mint a LiveKit room and broadcast voice_state for a
// channel the UI can never render or moderate. 'dm' stays allowed: DM and
// group voice calls join through this same handler.
if ch.Type != "voice" && ch.Type != "dm" {
c.sendMsg(buildErrorMsg(ErrCodeBadRequest, "not a voice channel"))
return 0, nil, false
}
// A blocked user is still a DM participant — blocking never touches
// dm_participants (service/block.go), so the CONNECT_VOICE + IsDMParticipant
// gate above passes them straight through into the blocker's DM voice room.
// Every other 1:1-DM interaction sink (send, edit, react, pin, typing,
// call_ring) already routes through this same check
// (service.requireDMNotBlocked); voice was the one gap. Group DMs are
// exempt inside it, matching every other sink. h.db satisfies
// service.Store directly, so no MessageService wiring is needed here.
if ch.Type == "dm" {
if err := service.RequireDMNotBlocked(ctx, h.db, c.userID, channelID); err != nil {
c.sendMsg(buildErrorMsg(ErrCodeForbidden, "cannot join voice: blocked"))
return 0, nil, false
}
}
// Archived channels are hidden from every client and their voice states are
// dropped from `ready`, but `archived` was consulted only by the visibility
// predicate — so a caller still holding the id could join the room of a
// channel nobody can see or moderate. Refuse the join outright; the sibling
// archive transition also evicts whoever is already inside.
if ch.Archived {
c.sendMsg(buildErrorMsg(ErrCodeBadRequest, "channel is archived"))
return 0, nil, false
}
// Ensure authenticated user is present before any state changes.
// This guard covers all downstream paths (LiveKit configured or not)
// that dereference c.user (e.g. c.user.Username in the success log).
if c.user == nil {
slog.Error("handleVoiceJoin: nil user on client", "user_id", c.userID)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "not authenticated"))
return 0, nil, false
}
// Hard-fail when LiveKit is not configured — without an SFU the client
// cannot connect to voice, so persisting state would create a ghost.
if h.livekit == nil {
c.sendMsg(buildErrorMsg(ErrCodeVoiceError, "voice is not configured on this server"))
return 0, nil, false
}
// Guard: reject voice join if the companion LiveKit process is not running
// (e.g. crashed 10 times and gave up).
if h.lkProcess != nil && !h.lkProcess.IsRunning() {
slog.Warn("handleVoiceJoin: LiveKit process not running", "user_id", c.userID)
c.sendMsg(buildErrorMsg(ErrCodeVoiceError, "voice is temporarily unavailable — LiveKit is not running"))
return 0, nil, false
}
return channelID, ch, true
}
// voiceJoinLeaveCurrent handles the case where the client is already in a
// voice channel: it no-ops a re-join of the same channel, and for a switch it
// snapshots the moderator-imposed mute/deafen flags, leaves the old channel
// and verifies the old row is really gone. The two booleans are the
// snapshotted flags for voiceJoinRestoreModFlags; false in the third position
// means the join must not proceed (the error frame has already been sent).
func (h *Hub) voiceJoinLeaveCurrent(ctx context.Context, c *Client, channelID int64) (bool, bool, bool) {
currentChID := c.getVoiceChID()
// If user is already in the same voice channel, no-op.
if currentChID == channelID {
c.sendMsg(buildErrorMsg(ErrCodeAlreadyJoined, "already in this voice channel"))
return false, false, false
}
// A moderator-imposed mute/deafen must survive a channel switch.
// voice.sql's ON CONFLICT branch preserves server_muted/server_deafened
// across a plain re-join, but the switch below deletes the row via
// handleVoiceLeave and lets JoinVoiceChannel(IfCapacity) re-insert it, so
// that branch is never reached: the flags are snapshotted here and
// reapplied once the new row exists.
//
// This covers the self-switch only. voice_mod_move deletes the row on the
// moderator's goroutine (DisconnectFromVoice) before the target's client
// re-joins, so by the time this handler runs there is nothing left to read
// and currentChID is already 0 — preserving the flags across a move needs
// state that outlives the row (see the cross-batch note on v029).
var wasServerMuted, wasServerDeafened bool
if currentChID > 0 {
if prevState, prevErr := h.db.GetVoiceState(ctx, c.userID); prevErr == nil && prevState != nil {
wasServerMuted = prevState.ServerMuted
wasServerDeafened = prevState.ServerDeafened
}
}
// If user is already in a different voice channel, leave it first.
if currentChID > 0 {
h.handleVoiceLeave(ctx, c)
// BUG-088: Verify old voice state is actually cleared before joining
// the new channel. If the DB delete failed (retry still running in
// background), the old row persists and JoinVoiceChannelIfCapacity's
// COUNT(*) may produce an incorrect result. Fail the switch so the
// user can retry cleanly.
vs, err := h.db.GetVoiceState(ctx, c.userID)
if err != nil {
slog.Warn("handleVoiceJoin: could not verify voice state cleared",
"user_id", c.userID, "err", err)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "voice channel switch failed — please try again"))
return false, false, false
}
if vs != nil {
slog.Warn("handleVoiceJoin: stale voice state persists after leave, aborting switch",
"user_id", c.userID, "stale_channel", vs.ChannelID, "target_channel", channelID)
// OC-0034: do NOT restore the client's local voice state here.
// handleVoiceLeave above already broadcast voice_leave for the old
// channel to every client that can see it — including this one,
// since finishVoiceLeave always adds the leaver to the audience —
// so every client, this user's own session included, has already
// torn the old membership down (dispatcher.ts runs leaveVoice on a
// self voice_leave). Restoring c.voiceChID/the topic subscription
// would resurrect a session nobody else believes exists anymore,
// while the stale DB row (this branch's trigger) stays orphaned.
// Leaving the client cleared keeps it consistent with the
// voice_leave it just received: the row now disagrees with every
// connected client's voiceChID, so sweepStaleVoiceStates reaps it
// (re-broadcasting voice_leave, harmlessly) within one tick, and
// the user_id-PK upsert lets the user rejoin immediately.
c.sendMsg(buildErrorMsg(ErrCodeInternal, "voice channel switch failed — please try again"))
return false, false, false
}
}
return wasServerMuted, wasServerDeafened, true
}
// voiceJoinPersist commits the join to the DB under the channel's capacity
// limit, loads back the persisted row and publishes the client's in-memory
// voice state. Returns false once the error frame has been sent.
func (h *Hub) voiceJoinPersist(ctx context.Context, c *Client, ch *db.Channel, channelID int64) (*db.VoiceState, bool) {
// Check channel capacity and persist to DB atomically.
maxUsers := ch.VoiceMaxUsers
if maxUsers > 0 {
if err := h.db.JoinVoiceChannelIfCapacity(ctx, c.userID, channelID, maxUsers); err != nil {
if errors.Is(err, db.ErrChannelFull) {
c.sendMsg(buildErrorMsg(ErrCodeChannelFull, "voice channel is full"))
return nil, false
}
slog.Error("ws handleVoiceJoin JoinVoiceChannelIfCapacity", "err", err, "user_id", c.userID)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "failed to join voice channel"))
return nil, false
}
} else {
// No capacity limit — use standard join.
if err := h.db.JoinVoiceChannel(ctx, c.userID, channelID); err != nil {
slog.Error("ws handleVoiceJoin JoinVoiceChannel", "err", err, "user_id", c.userID)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "failed to join voice channel"))
return nil, false
}
}
// Load the persisted row immediately so later cleanup can target this exact
// join instance even if the user rejoins the same channel.
state, err := h.db.GetVoiceState(ctx, c.userID)
if err != nil || state == nil {
slog.Error("ws handleVoiceJoin GetVoiceState", "err", err, "user_id", c.userID)
h.rollbackVoiceJoin(ctx, c, channelID, "", false)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "failed to join voice channel"))
return nil, false
}
// BUG-088: set the client's voice channel as soon as the DB row is
// confirmed committed, before the permission checks and LiveKit token
// generation below (which can take several round trips). Leaving this
// until after those steps left a window where the concurrent stale-voice
// sweep sees c.getVoiceChID() still 0 while the row already exists,
// misclassifies the in-flight join as a ghost and deletes it — leaving
// the joiner live on the hub and in the SFU with no DB row. A failure
// further down still unwinds this via rollbackVoiceJoin's
// c.clearVoiceChID(), same as before.
c.setVoiceState(channelID, state.JoinedAt)
return state, true
}
// voiceJoinRestoreModFlags re-applies a moderator-imposed mute/deafen that
// predates a channel switch and returns the voice state the caller should
// broadcast — the re-read row when the restore ran, the original otherwise.
func (h *Hub) voiceJoinRestoreModFlags(ctx context.Context, c *Client, channelID int64, state *db.VoiceState, wasServerMuted, wasServerDeafened bool) *db.VoiceState {
// Restore a moderator-imposed mute/deafen that predates this switch (see
// the snapshot above). Best-effort: a failure here is logged but does not
// fail the join, matching every other SetVoiceServerMute/Deafen call site.
if wasServerMuted || wasServerDeafened {
if wasServerMuted {
if _, err := h.db.SetVoiceServerMute(ctx, c.userID, channelID, true); err != nil {
slog.Error("ws handleVoiceJoin SetVoiceServerMute (restore)", "err", err, "user_id", c.userID)
}
}
if wasServerDeafened {
if _, err := h.db.SetVoiceServerDeafen(ctx, c.userID, channelID, true); err != nil {
slog.Error("ws handleVoiceJoin SetVoiceServerDeafen (restore)", "err", err, "user_id", c.userID)
}
}
// Re-read so the voice_state broadcast below carries the restored
// flags rather than the plain-insert defaults — that broadcast is what
// makes the mute effective on the target's own client and visible to
// everyone else.
//
// No SFU mute is applied here: MuteParticipantAudio resolves the
// participant in the destination room first, and this join has not even
// minted its token yet, so the call could only fail (after a LiveKit
// round trip on the read pump). As everywhere else in the voice
// moderation path, the persisted server_muted is the authority — it
// blocks the target's own unmute and is re-applied at the SFU whenever
// the moderator next acts.
if refreshed, refErr := h.db.GetVoiceState(ctx, c.userID); refErr == nil && refreshed != nil {
state = refreshed
}
}
return state
}
// voiceJoinPublishPerms derives the SFU publish permissions from role —
// prevents SFU-level bypass when the client connects directly via direct_url
// (BUG-128). With a PermissionService the three bits come from the per-user
// cache; the bare-hub fallback answers them from one role fetch + one
// overrides fetch via HasChannelPermBatch instead of three hasChannelPerm
// round trips. Both branches fail closed: an unresolved role or override map
// yields no publish grants (admins bypass overrides, so an override fetch
// error cannot demote them).
func (h *Hub) voiceJoinPublishPerms(ctx context.Context, userID, channelID int64) (canPublish, canVideo, canScreenShare bool) {
if h.perms != nil {
// PermissionService answers all three bits from one cached
// role+overrides snapshot (populated by the CONNECT_VOICE gate
// above, so these are cache hits). Same fail-closed posture: an
// unresolved role or override map yields no publish grants.
canPublish = h.perms.HasChannelPerm(ctx, userID, channelID, permissions.SpeakVoice)
canVideo = h.perms.HasChannelPerm(ctx, userID, channelID, permissions.UseVideo)
canScreenShare = h.perms.HasChannelPerm(ctx, userID, channelID, permissions.ShareScreen)
} else if role, roleErr := h.db.GetRoleForUser(ctx, userID); roleErr == nil && role != nil {
// Admins bypass overrides, so skip the fetch for them (mirrors
// computeAllowedChannels); HasChannelPermBatch answers true from
// the role bits alone.
var overrides map[int64]db.ChannelOverride
var oErr error
if !permissions.HasAdmin(role.Permissions) {
overrides, oErr = h.db.GetChannelOverridesFor(ctx, role.ID, userID)
}
if oErr == nil {
po := permOverrides(overrides)
canPublish = h.permChecker.HasChannelPermBatch(role.Permissions, po, channelID, permissions.SpeakVoice)
canVideo = h.permChecker.HasChannelPermBatch(role.Permissions, po, channelID, permissions.UseVideo)
canScreenShare = h.permChecker.HasChannelPermBatch(role.Permissions, po, channelID, permissions.ShareScreen)
}
}
return canPublish, canVideo, canScreenShare
}
// voiceJoinGrantToken mints the LiveKit credential and delivers it, withholding
// it if the join was superseded in the meantime. Returns false once the join
// has been abandoned (rolled back, or superseded) and must not complete.
func (h *Hub) voiceJoinGrantToken(ctx context.Context, c *Client, channelID int64, state *db.VoiceState) bool {
// Generate LiveKit token if LiveKit client is available.
// Token generation failure is fatal — without a token the client cannot
// connect to the SFU, so we must roll back the DB join.
// NOTE: the joiner's own state was already set above (BUG-088), but
// nobody else has been told about the join yet — rollbackVoiceJoin below
// is still called with broadcast=false, so a failure here does not
// broadcast a spurious voice_leave for a join no other client ever saw.
if h.livekit != nil {
canPublish, canVideo, canScreenShare := h.voiceJoinPublishPerms(ctx, c.userID, channelID)
canSubscribe := true
token, tokenErr := h.livekit.GenerateToken(c.userID, c.user.Username, channelID, state.JoinedAt, canPublish, canSubscribe, canVideo, canScreenShare)
if tokenErr != nil {
slog.Error("ws handleVoiceJoin GenerateToken", "err", tokenErr, "user_id", c.userID)
h.rollbackVoiceJoin(ctx, c, channelID, state.JoinedAt, false)
c.sendMsg(buildErrorMsg(ErrCodeInternal, "failed to generate voice token"))
return false
}
if voiceJoinPostTokenRaceHook != nil {
voiceJoinPostTokenRaceHook(c)
}
// OC-0008: a concurrent eviction (voice_mod_kick/move via
// DisconnectFromVoiceInChannel, the CONNECT_VOICE revocation sweep, or
// CleanupVoiceForChannel) can land anywhere between c.setVoiceState
// (BUG-088, above) and here — all of them delete the voice_states row
// and clear the client's in-memory state, then call RemoveParticipant,
// which no-ops because this join has never reached the SFU yet
// (GenerateToken is a local JWT mint, no LiveKit round trip). The tail
// guard below used to be the only check, but by then the token had
// already been queued for delivery — the client ends up with a live
// 5-minute RoomJoin credential for a membership the server just decided
// does not exist, and connects to the SFU with it regardless of what
// happens after. Re-check here, immediately before the credential
// leaves the process, and withhold it if superseded.
if curChID, curToken := c.getVoiceState(); curChID != channelID || curToken != state.JoinedAt {
slog.Info("ws handleVoiceJoin: join superseded before token delivery",
"user_id", c.userID, "channel_id", channelID, "current_channel_id", curChID)
// Best-effort defense in depth: this join has not reached the SFU
// (see above), so this is normally a no-op, but it closes the
// sliver of time between this check and c.sendMsg below the same
// way every other eviction path's RemoveParticipant call does.
rbCtx := context.WithoutCancel(ctx)
if err := h.livekit.RemoveParticipant(rbCtx, channelID, c.userID, state.JoinedAt); err != nil {
slog.Warn("ws handleVoiceJoin: RemoveParticipant after supersession failed (may already be gone)",
"err", err, "user_id", c.userID, "channel_id", channelID)
}
return false
}
// Send both proxy path and direct URL. The client uses direct_url
// when on localhost (avoids self-signed TLS issues with WebView
// fetch) and falls back to the /livekit proxy for remote clients.
// NOTE: E2EE keys are no longer server-generated. Clients exchange
// keys via ECDH (voice_e2ee_announce / voice_e2ee_offer messages).
// C-2: Include is_key_holder so the client knows whether to initiate
// key distribution after connecting to the SFU.
isKeyHolder := h.computeIsKeyHolder(channelID, c.userID)
c.sendMsg(buildVoiceToken(channelID, token, "/livekit", h.livekit.URL(), isKeyHolder))
}
return true
}
// voiceJoinComplete finishes a join that survived every guard: voice topic
// subscription, key-holder election, the joiner's own voice_state fan-out, the
// existing participants' states and E2EE keys, and voice_config.
func (h *Hub) voiceJoinComplete(ctx context.Context, c *Client, ch *db.Channel, channelID int64, state *db.VoiceState) {
// Voice channel state itself was already set above (BUG-088), immediately
// after the DB row committed — which also means a concurrent eviction (the
// revocation sweep, a participant_left webhook, a moderator kick/move) can
// now land on THIS join instance while the token round trip above is in
// flight. The check inside the h.livekit block above (OC-0008) already
// withholds the token itself in that case; this is the tail guard for
// everything downstream of it (voice topic subscription, the joiner's own
// voice_state broadcast) when no token round trip ran at all (h.livekit ==
// nil is unreachable in practice — handleVoiceJoin returns earlier — but
// kept here as the single completion gate for both paths). Those evictors
// all clear the client's voice state and delete the row after deciding
// against it, so completing the join here would resurrect a membership
// that was deliberately torn down: subscribed to the voice topic and
// broadcast as present, with no row behind it. Their decision wins; a
// same-instance state is the only thing this join may finish.
if curChID, curToken := c.getVoiceState(); curChID != channelID || curToken != state.JoinedAt {
slog.Info("ws handleVoiceJoin: join superseded before completion",
"user_id", c.userID, "channel_id", channelID, "current_channel_id", curChID)
return
}
// Subscribe to voice topic for voice-scoped events.
h.pubsub.Subscribe(c, VoiceTopic(channelID))
// Update key holder map now that this client's voice state is set.
h.updateKeyHolder(channelID)
// Broadcast the joiner's state to the clients allowed to see this channel.
h.broadcastVoiceEvent(ctx, channelID, buildVoiceState(*state))
// Send existing channel voice states to the joiner.
existing, err := h.db.GetChannelVoiceStates(ctx, channelID)
if err != nil {
slog.Error("ws handleVoiceJoin GetChannelVoiceStates", "err", err)
return
}
for _, vs := range existing {
if vs.UserID == c.userID {
continue
}
c.sendMsg(buildVoiceState(vs))
// Send existing participant's ECDH public key (and its identity
// signature, F3 TOFU) so the joiner can participate in the
// client-side E2EE key exchange.
if pubKey, sig := h.getClientE2EEPubKey(vs.UserID); pubKey != "" {
c.sendMsg(buildVoiceE2EEAnnounce(vs.UserID, pubKey, sig))
}
}
// Send voice_config to the joiner.
quality := "medium"
if ch.VoiceQuality != nil && *ch.VoiceQuality != "" {
q := *ch.VoiceQuality
if validVoiceQuality(q) {
quality = q
} else {
slog.Warn("ws handleVoiceJoin invalid voice quality, using default",
"quality", q, "channel_id", channelID)
}
}
maxUsers := ch.VoiceMaxUsers
bitrate := qualityBitrate(quality)
c.sendMsg(buildVoiceConfig(channelID, quality, bitrate, maxUsers))
lkURL := ""
if h.livekit != nil {
lkURL = h.livekit.URL()
}
slog.Info("voice join",
"user_id", c.userID,
"username", c.user.Username,
"channel_id", channelID,
"remote", c.remoteAddr,
"livekit_url", lkURL,
"quality", quality,
"channel_users", len(existing),
"channel_max", maxUsers,
)
}
// handleVoiceTokenRefreshV2 is the V2 (pure) handler for voice_token_refresh.
// It generates a fresh LiveKit token for a client already in a voice channel.
func handleVoiceTokenRefreshV2(ctx context.Context, cmd Command, info ClientInfo, deps any) Result {
d := deps.(VoiceDeps)
userID := info.UserID
channelID := info.VoiceChannelID
ratKey := auth.Key("voice_token_refresh", userID)
if d.Limiter != nil && !d.Limiter.Allow(ratKey, 1, 60*time.Second) {
return Result{Error: ClientError{Code: ErrCodeRateLimited, Message: "token refresh rate limited"}}
}
if channelID == 0 {
return Result{Error: ClientError{Code: ErrCodeBadRequest, Message: "not in voice"}}
}
if d.TokenGen == nil {
return Result{Error: ClientError{Code: ErrCodeInternal, Message: "voice not configured"}}
}
// Re-check CONNECT_VOICE where the credential is minted. The channel comes
// from the client's own session state, and voice_join (voice_join.go:61) was
// the only place this bit was ever checked — so a user whose CONNECT_VOICE
// was revoked mid-session kept minting fresh SFU room-join grants. Refusing
// alone would leave the live session in place, so the refusal also evicts:
// LeaveVoice runs handleVoiceLeave, which clears the client's voice state,
// deletes the voice_states row and removes the LiveKit participant.
// Channel-type aware, like the voice_join gate: this mints the same
// RoomJoin+CanSubscribe credential, so a role-only check here would keep
// re-issuing one for a DM the user is not a participant of.
if !hasChannelAccess(ctx, d.DB, d.Permissions, d.PermSvc, userID, channelID, permissions.ConnectVoice) {
return Result{
Error: ClientError{Code: ErrCodeForbidden, Message: "missing CONNECT_VOICE permission"},
LeaveVoice: true,
}
}
// Same block gate as voice_join (voice_join.go, OC-0018): a block imposed
// mid-session must not let the refresh keep minting a fresh SFU credential
// for a DM the other participant has since blocked. RequireDMNotBlocked is
// a safe no-op for a non-DM channelID (no dm_participants row to match), so
// this needs no channel-type fetch of its own. d.DB satisfies service.Store
// directly.
if err := service.RequireDMNotBlocked(ctx, d.DB, userID, channelID); err != nil {
return Result{
Error: ClientError{Code: ErrCodeForbidden, Message: "cannot refresh voice token: blocked"},
LeaveVoice: true,
}
}
// With a PermissionService these three are cache hits after the gate above
// populated the user's entry — the refresh drops from ~9 DB reads to at
// most one channel-row lookup.
canPublish := hasPerm(ctx, d.DB, d.Permissions, d.PermSvc, userID, channelID, permissions.SpeakVoice)
canSubscribe := true
canVideo := hasPerm(ctx, d.DB, d.Permissions, d.PermSvc, userID, channelID, permissions.UseVideo)
canScreenShare := hasPerm(ctx, d.DB, d.Permissions, d.PermSvc, userID, channelID, permissions.ShareScreen)
joinToken := info.VoiceJoinToken
var result Result
if joinToken == "" {
state, stateErr := d.DB.GetVoiceState(ctx, userID)
if stateErr != nil || state == nil {
slog.Error("ws handleVoiceTokenRefreshV2 GetVoiceState", "err", stateErr, "user_id", userID)
return Result{Error: ClientError{Code: ErrCodeInternal, Message: "failed to refresh voice token"}}
}
joinToken = state.JoinedAt
result.SetVoiceJoinToken = &joinToken
}
token, err := d.TokenGen.GenerateToken(userID, info.Username, channelID, joinToken, canPublish, canSubscribe, canVideo, canScreenShare)
if err != nil {
slog.Error("ws handleVoiceTokenRefreshV2 GenerateToken", "err", err, "user_id", userID)
return Result{Error: ClientError{Code: ErrCodeInternal, Message: "failed to generate voice token"}}
}
isKeyHolder := false
if d.KeyHolder != nil {
isKeyHolder = d.KeyHolder.IsVoiceKeyHolder(channelID, userID)
}
result.Reply = buildVoiceToken(channelID, token, "/livekit", d.TokenGen.URL(), isKeyHolder)
slog.Info("voice token refreshed (v2)", "user_id", userID, "channel_id", channelID)
return result
}
// rollbackVoiceJoin undoes a partially-completed voice join: clears the
// client's voice channel ID, removes the DB voice state row, and broadcasts
// voice_leave so other clients don't see a ghost participant.
//
// joinedAt scopes the compensating delete to the join instance being undone
// (mirrors LeaveVoiceChannelIfMatch, used for the same reason by every
// sibling leave path). A rollback fires most often because the connection
// that started the join just died, and that same cancellation is exactly
// what lets a second connection for this user race ahead and establish a
// newer, legitimate voice_states row before this rollback runs — an
// unconditional "DELETE ... WHERE user_id = ?" would destroy that newer row
// instead of the failed one. When joinedAt is empty (the caller never read
// the row back far enough to learn it), the row is re-read here and the
// delete is skipped unless it still names channelID.
func (h *Hub) rollbackVoiceJoin(ctx context.Context, c *Client, channelID int64, joinedAt string, broadcast bool) {
c.clearVoiceChID()
// The client's voice state is now set before token generation (BUG-088),
// so a concurrent join/leave in the same channel can have elected this
// half-joined client key holder. Re-run the election after taking it back
// out, or the map keeps naming a user who never reached the SFU and the
// real lowest-uid participant's rekey offers are rejected with
// NOT_KEY_HOLDER until the next join or leave.
h.updateKeyHolder(channelID)
// The compensating delete must run even when the join failed BECAUSE the
// connection died — that cancellation is the most common rollback trigger.
rbCtx := context.WithoutCancel(ctx)
if joinedAt == "" {
if state, err := h.db.GetVoiceState(rbCtx, c.userID); err == nil && state != nil && state.ChannelID == channelID {
joinedAt = state.JoinedAt
}
}
if joinedAt != "" {
if _, err := h.db.LeaveVoiceChannelIfMatch(rbCtx, c.userID, channelID, joinedAt); err != nil {
slog.Error("ws rollbackVoiceJoin LeaveVoiceChannelIfMatch", "err", err,
"user_id", c.userID, "channel_id", channelID)
}
}
if broadcast {
h.broadcastVoiceEvent(ctx, channelID, buildVoiceLeave(channelID, c.userID))
}
}