import { Logger, UnauthorizedException, ForbiddenException, } from "@nestjs/common"; import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, ConnectedSocket, OnGatewayConnection, OnGatewayDisconnect, } from "@nestjs/websockets"; import { Server, Socket } from "socket.io"; import { AdminPermission, AdminRole, resolveAdminPermissions } from "@micprotocol/shared-types"; import { BetterAuthService } from "../auth/better-auth-identity.service"; import { PrismaService } from "../prisma/prisma.service"; import { deriveAdminRole } from "../common/platform-admin"; import { isOriginAllowed } from "../common/origin-policy"; // The /events namespace only carries small JSON ids (join/leave) — never // large blobs (chat lives in mic-realtime). Cap incoming message payloads // well below Socket.io's 1MB default. const MAX_MESSAGE_BUFFER_BYTES = 64 * 1024; interface AuthenticatedSocket extends Socket { data: { userId?: string; isAdmin?: boolean; adminRole?: AdminRole | null; adminPermissions?: Set; }; } interface RoomSubscription { podcastId: string; } interface AdminBroadcast { event: string; data: Record; } interface AdminDisconnectUser { userId: string; reason?: string; } @WebSocketGateway({ cors: { // Shared policy with the HTTP layer (common/origin-policy.ts): // explicit origins + any `.ROOT_DOMAIN` workspace subdomain. origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => callback(null, isOriginAllowed(origin)), credentials: true, }, namespace: "/events", maxHttpBufferSize: MAX_MESSAGE_BUFFER_BYTES, }) export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect { private readonly logger = new Logger(EventsGateway.name); @WebSocketServer() server!: Server; constructor( private readonly betterAuthService: BetterAuthService, private readonly prisma: PrismaService, ) {} // ─── Per-socket rate limiting ───────────────────── // The global ThrottlerGuard only applies to HTTP; socket handlers are // otherwise unlimited. Bound every mutating/room-joining handler, not just // join:podcast, to prevent connection-based DoS. private readonly maxJoinsPerWindow = 30; private readonly joinWindowMs = 60_000; private readonly maxEventsPerWindow = 120; private readonly eventWindowMs = 60_000; private readonly joinTimestamps = new Map(); private readonly eventTimestamps = new Map(); private isRateLimited( map: Map, socketId: string, max: number, windowMs: number, ): boolean { const now = Date.now(); const cutoff = now - windowMs; const recent = (map.get(socketId) || []).filter((t) => t > cutoff); if (recent.length >= max) { map.set(socketId, recent); return true; } recent.push(now); map.set(socketId, recent); return false; } private isJoinRateLimited(socketId: string): boolean { return this.isRateLimited( this.joinTimestamps, socketId, this.maxJoinsPerWindow, this.joinWindowMs, ); } private isEventRateLimited(socketId: string): boolean { return this.isRateLimited( this.eventTimestamps, socketId, this.maxEventsPerWindow, this.eventWindowMs, ); } private isValidId(value: unknown, maxLength = 64): value is string { return ( typeof value === "string" && value.length > 0 && value.length <= maxLength ); } // ─── Admin context resolution ───────────────────── // Mirrors adminPermissionProcedure (trpc.init.ts): explicit adminRole wins, // legacy isAdmin-only keeps SUPER_ADMIN, neither → not an admin. Never fall // back to READ_ONLY for role-less callers. private async resolveAdminContext( userId: string, ): Promise<{ isAdmin: boolean; adminRole: AdminRole | null; permissions: Set; } | null> { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { isAdmin: true, adminRole: true, adminPermissions: true, suspendedAt: true, }, }); if (!user || user.suspendedAt) return null; const role = deriveAdminRole({ isAdmin: user.isAdmin, adminRole: user.adminRole }); if (!role) return null; const permissions = resolveAdminPermissions( role, user.adminPermissions as Record | null, ); return { isAdmin: !!user.isAdmin, adminRole: role, permissions, }; } private hasAdminPermission( socket: AuthenticatedSocket, permission: AdminPermission, ): boolean { return socket.data.adminPermissions?.has(permission) ?? false; } async handleConnection(client: AuthenticatedSocket) { try { // Extract token from handshake auth or query const token = (client.handshake.auth?.token as string) || (client.handshake.query?.token as string); if (!token) { this.logger.warn(`Connection rejected: no token provided (${client.id})`); client.emit("auth:error", { message: "Authentication required" }); client.disconnect(true); return; } // Verify session via Better Auth const identity = await this.betterAuthService.getSessionFromBearer( `Bearer ${token}`, ); if (!identity) { this.logger.warn(`Connection rejected: invalid token (${client.id})`); client.emit("auth:error", { message: "Invalid token" }); client.disconnect(true); return; } // Resolve admin context for this user (defense in depth; admin-only // socket events check permissions on each call too). const adminCtx = await this.resolveAdminContext(identity.userId); // Store identity on socket client.data.userId = identity.userId; if (adminCtx) { client.data.isAdmin = adminCtx.isAdmin; client.data.adminRole = adminCtx.adminRole; client.data.adminPermissions = adminCtx.permissions; this.logger.log( `Client connected: ${client.id} (user: ${identity.userId}, admin: ${adminCtx.adminRole ?? "none"})`, ); } else { this.logger.log( `Client connected: ${client.id} (user: ${identity.userId})`, ); } // Auto-join user room for direct events client.join(`user:${identity.userId}`); } catch (error) { this.logger.warn( `Connection rejected: auth failed (${client.id}): ${ error instanceof Error ? error.message : String(error) }`, ); client.emit("auth:error", { message: "Authentication failed" }); client.disconnect(true); } } handleDisconnect(client: AuthenticatedSocket) { const userId = client.data?.userId || "unknown"; this.joinTimestamps.delete(client.id); this.eventTimestamps.delete(client.id); this.logger.log(`Client disconnected: ${client.id} (user: ${userId})`); } // ─── Client-facing socket events ────────────────── @SubscribeMessage("join:podcast") async handleJoinPodcast( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: RoomSubscription, ) { const userId = client.data?.userId; if (!userId) { return { event: "error", message: "Not authenticated" }; } if (this.isJoinRateLimited(client.id)) { return { event: "error", message: "Too many room joins — try again shortly" }; } // Validate input shape before touching the DB const podcastId = data?.podcastId; if (!this.isValidId(podcastId)) { return { event: "error", message: "Invalid podcastId" }; } // Verify user is a member of this podcast's workspace const podcast = await this.prisma.podcast.findUnique({ where: { id: podcastId }, select: { workspace: { select: { members: { select: { userId: true }, }, }, }, }, }); const isMember = podcast?.workspace?.members?.some( (m) => m.userId === userId, ); if (!isMember) { this.logger.warn( `User ${userId} denied access to podcast room ${podcastId}`, ); return { event: "error", message: "Not a member of this podcast" }; } const room = `podcast:${podcastId}`; client.join(room); this.logger.log(`Client ${client.id} joined room ${room}`); return { event: "joined", room }; } @SubscribeMessage("leave:podcast") handleLeavePodcast( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: { podcastId: string }, ) { const podcastId = data?.podcastId; if (!this.isValidId(podcastId)) { return { event: "error", message: "Invalid podcastId" }; } const room = `podcast:${podcastId}`; client.leave(room); this.logger.log(`Client ${client.id} left room ${room}`); return { event: "left", room }; } @SubscribeMessage("join:user") handleJoinUserRoom( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: { userId: string }, ) { const targetUserId = data?.userId; if (!this.isValidId(targetUserId, 128)) { return { event: "error", message: "Invalid userId" }; } // Users can only join their own user room if (client.data?.userId !== targetUserId) { return { event: "error", message: "Cannot join another user's room" }; } const room = `user:${targetUserId}`; client.join(room); this.logger.log(`Client ${client.id} joined user room ${room}`); return { event: "joined", room }; } @SubscribeMessage("leave:user") handleLeaveUserRoom( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: { userId: string }, ) { const targetUserId = data?.userId; if (!this.isValidId(targetUserId, 128)) { return { event: "error", message: "Invalid userId" }; } const room = `user:${targetUserId}`; client.leave(room); this.logger.log(`Client ${client.id} left user room ${room}`); return { event: "left", room }; } @SubscribeMessage("join:workspace") async handleJoinWorkspace( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: { workspaceId: string }, ) { const userId = client.data?.userId; if (!userId) { return { event: "error", message: "Not authenticated" }; } const workspaceId = data?.workspaceId; if (!this.isValidId(workspaceId)) { return { event: "error", message: "Invalid workspaceId" }; } // Verify user is a member of this workspace const workspace = await this.prisma.workspace.findUnique({ where: { id: workspaceId }, select: { members: { where: { userId }, select: { userId: true }, }, }, }); const isMember = workspace?.members?.some((m) => m.userId === userId); if (!isMember) { this.logger.warn( `User ${userId} denied access to workspace room ${workspaceId}`, ); return { event: "error", message: "Not a member of this workspace" }; } const room = `workspace:${workspaceId}`; client.join(room); this.logger.log(`Client ${client.id} joined workspace room ${room}`); return { event: "joined", room }; } @SubscribeMessage("leave:workspace") handleLeaveWorkspace( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: { workspaceId: string }, ) { const workspaceId = data?.workspaceId; if (!this.isValidId(workspaceId)) { return { event: "error", message: "Invalid workspaceId" }; } const room = `workspace:${workspaceId}`; client.leave(room); this.logger.log(`Client ${client.id} left workspace room ${room}`); return { event: "left", room }; } // ─── Admin-only socket events ───────────────────── // Require platform-admin permission on every call (defense in depth; // admin context is also resolved at connection time). @SubscribeMessage("admin:broadcast") async handleAdminBroadcast( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: AdminBroadcast, ) { const userId = client.data?.userId; if (!userId) { return { event: "error", message: "Not authenticated" }; } if (this.isEventRateLimited(client.id)) { return { event: "error", message: "Too many requests — try again shortly" }; } if (!this.hasAdminPermission(client, AdminPermission.ANNOUNCEMENTS_WRITE)) { this.logger.warn( `User ${userId} attempted admin:broadcast without ANNOUNCEMENTS_WRITE`, ); return { event: "error", message: "Insufficient permissions" }; } if (!data?.event || typeof data.event !== "string") { return { event: "error", message: "Invalid event name" }; } this.server.emit(data.event, { ...data.data, timestamp: new Date().toISOString(), source: "admin", actor: userId, }); this.logger.log( `Admin ${userId} broadcast event ${data.event} to all clients`, ); return { event: "broadcast-sent", broadcastEvent: data.event }; } @SubscribeMessage("admin:disconnect-user") async handleAdminDisconnectUser( @ConnectedSocket() client: AuthenticatedSocket, @MessageBody() data: AdminDisconnectUser, ) { const userId = client.data?.userId; if (!userId) { return { event: "error", message: "Not authenticated" }; } if (this.isEventRateLimited(client.id)) { return { event: "error", message: "Too many requests — try again shortly" }; } if (!this.hasAdminPermission(client, AdminPermission.USERS_SUSPEND)) { this.logger.warn( `User ${userId} attempted admin:disconnect-user without USERS_SUSPEND`, ); return { event: "error", message: "Insufficient permissions" }; } const targetUserId = data?.userId; if (!this.isValidId(targetUserId, 128)) { return { event: "error", message: "Invalid userId" }; } if (targetUserId === userId) { return { event: "error", message: "Cannot disconnect yourself" }; } // Disconnect all sockets belonging to the target user const sockets = this.server.sockets.sockets; let disconnected = 0; for (const [id, socket] of sockets) { const authenticated = socket as AuthenticatedSocket; if (authenticated.data?.userId === targetUserId) { authenticated.disconnect(true); disconnected++; } } this.logger.log( `Admin ${userId} force-disconnected ${disconnected} socket(s) for user ${targetUserId}`, ); return { event: "user-disconnected", targetUserId, disconnected, reason: data.reason ?? undefined, }; } @SubscribeMessage("admin:rooms") async handleAdminRooms( @ConnectedSocket() client: AuthenticatedSocket, ) { const userId = client.data?.userId; if (!userId) { return { event: "error", message: "Not authenticated" }; } if (this.isEventRateLimited(client.id)) { return { event: "error", message: "Too many requests — try again shortly" }; } if ( !this.hasAdminPermission(client, AdminPermission.OPS_READ) && !client.data.isAdmin ) { this.logger.warn( `User ${userId} attempted admin:rooms without OPS_READ`, ); return { event: "error", message: "Insufficient permissions" }; } // Build a snapshot of active rooms and their occupant counts const rooms: Record = {}; for (const [room, clients] of this.server.sockets.adapter.rooms) { // Skip the socket's own id entries (adapter rooms include socket ids) if (clients.size === 0) continue; // Only include named rooms (not socket.id rooms) if (!this.server.sockets.sockets.has(room)) { rooms[room] = clients.size; } } const adminCtx = client.data.adminRole ?? "none"; this.logger.log( `Admin ${userId} (${adminCtx}) listed ${Object.keys(rooms).length} active rooms`, ); return { event: "rooms", rooms, connectedClients: this.server.sockets.sockets.size, timestamp: new Date().toISOString(), }; } // ─── Server-side event emitters ──────────────────── notifyGuestStatusChange(podcastId: string, guestId: string, status: string) { this.server.to(`podcast:${podcastId}`).emit("guest:status-changed", { guestId, status, timestamp: new Date().toISOString(), }); } notifyNewBooking(podcastId: string, booking: Record) { this.server.to(`podcast:${podcastId}`).emit("booking:created", { booking, timestamp: new Date().toISOString(), }); } notifyAssetSubmitted(podcastId: string, submission: Record) { this.server.to(`podcast:${podcastId}`).emit("asset:submitted", { submission, timestamp: new Date().toISOString(), }); } notifyOutreachEvent( podcastId: string, event: string, data: Record, ) { this.server.to(`podcast:${podcastId}`).emit(`outreach:${event}`, { ...data, timestamp: new Date().toISOString(), }); } notifyEpisodeUpdate(podcastId: string, episode: Record) { this.server.to(`podcast:${podcastId}`).emit("episode:updated", { episode, timestamp: new Date().toISOString(), }); } // ─── Network / Trust Score Events ───────────────── notifyTrustScoreChanged( podcastId: string, profileId: string, oldScore: number, newScore: number, ) { this.server.to(`podcast:${podcastId}`).emit("network:trust-score-changed", { profileId, oldScore, newScore, delta: newScore - oldScore, timestamp: new Date().toISOString(), }); } notifyBadgeGranted( podcastId: string, profileId: string, badgeType: string, trustScoreImpact: number, ) { this.server.to(`podcast:${podcastId}`).emit("network:badge-granted", { profileId, badgeType, trustScoreImpact, timestamp: new Date().toISOString(), }); } notifyBadgeRevoked( podcastId: string, profileId: string, badgeType: string, trustScoreImpact: number, ) { this.server.to(`podcast:${podcastId}`).emit("network:badge-revoked", { profileId, badgeType, trustScoreImpact, timestamp: new Date().toISOString(), }); } notifyVerificationStatusChanged( podcastId: string, profileId: string, oldStatus: string, newStatus: string, ) { this.server.to(`podcast:${podcastId}`).emit("network:verification-status-changed", { profileId, oldStatus, newStatus, timestamp: new Date().toISOString(), }); } notifyNetworkBookingUpdate( podcastId: string, bookingId: string, status: string, ) { this.server.to(`podcast:${podcastId}`).emit("network:booking-status-changed", { bookingId, status, timestamp: new Date().toISOString(), }); } // ─── In-app Notification broadcast ────────────────── notifyInAppNotification(podcastId: string, data: Record) { this.server.to(`podcast:${podcastId}`).emit("notification:in-app", { ...data, timestamp: new Date().toISOString(), }); } // ─── Export progress events ───────────────────────── notifyExportProgress( userId: string, exportJobId: string, clipId: string, platform: string, progress: number, ) { this.server.to(`user:${userId}`).emit("export:progress", { exportJobId, clipId, platform, progress, timestamp: new Date().toISOString(), }); } notifyExportCompleted( userId: string, exportJobId: string, clipId: string, platform: string, cdnUrl: string, ) { this.server.to(`user:${userId}`).emit("export:completed", { exportJobId, clipId, platform, cdnUrl, timestamp: new Date().toISOString(), }); } notifyExportFailed( userId: string, exportJobId: string, clipId: string, platform: string, error: string, ) { this.server.to(`user:${userId}`).emit("export:failed", { exportJobId, clipId, platform, error, timestamp: new Date().toISOString(), }); } // ─── User-targeted events (direct to a user's socket) ─── emitToUser(userId: string, event: string, data: Record) { this.server.to(`user:${userId}`).emit(event, { ...data, timestamp: new Date().toISOString(), }); } // ─── Recording Pipeline Events ────────────────────────── notifyRecordingSessionStarted( podcastId: string, sessionId: string, episodeId: string, ) { this.server.to(`podcast:${podcastId}`).emit("recording:session-started", { sessionId, episodeId, timestamp: new Date().toISOString(), }); } notifyRecordingSessionCompleted( podcastId: string, sessionId: string, episodeId: string, ) { this.server.to(`podcast:${podcastId}`).emit("recording:session-completed", { sessionId, episodeId, timestamp: new Date().toISOString(), }); } notifyRecordingTrackCreated( podcastId: string, sessionId: string, trackId: string, guestId: string | null, isHost: boolean, ) { this.server.to(`podcast:${podcastId}`).emit("recording:track-created", { sessionId, trackId, guestId, isHost, timestamp: new Date().toISOString(), }); } // ─── Live Stream Events ───────────────────────────────── notifyStreamStarted( podcastId: string, room: string, episodeId: string, ) { this.server.to(`podcast:${podcastId}`).emit("stream:started", { room, episodeId, timestamp: new Date().toISOString(), }); } notifyStreamEnded( podcastId: string, room: string, episodeId: string, ) { this.server.to(`podcast:${podcastId}`).emit("stream:ended", { room, episodeId, timestamp: new Date().toISOString(), }); } notifyParticipantJoined( podcastId: string, room: string, identity: string, ) { this.server.to(`podcast:${podcastId}`).emit("stream:participant-joined", { room, identity, timestamp: new Date().toISOString(), }); } notifyParticipantLeft( podcastId: string, room: string, identity: string, ) { this.server.to(`podcast:${podcastId}`).emit("stream:participant-left", { room, identity, timestamp: new Date().toISOString(), }); } // ─── Support Ticket Events ─────────────────────────── notifyTicketCreated( workspaceId: string, ticket: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("ticket:created", { ticket, timestamp: new Date().toISOString(), }); } notifyTicketAssigned( workspaceId: string, ticketId: string, agentId: string, ) { this.server.to(`workspace:${workspaceId}`).emit("ticket:assigned", { ticketId, agentId, timestamp: new Date().toISOString(), }); this.server.to(`user:${agentId}`).emit("ticket:assigned", { ticketId, agentId, timestamp: new Date().toISOString(), }); } notifyNewMessage( workspaceId: string, ticketId: string, message: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("ticket:new-message", { ticketId, message, timestamp: new Date().toISOString(), }); } notifyTicketStatusChanged( workspaceId: string, ticketId: string, status: string, ) { this.server.to(`workspace:${workspaceId}`).emit("ticket:status-changed", { ticketId, status, timestamp: new Date().toISOString(), }); } notifyCsatRequested( userId: string, ticketId: string, rating: number, ) { this.server.to(`user:${userId}`).emit("ticket:csat-requested", { ticketId, rating, timestamp: new Date().toISOString(), }); } // ─── Cal.com Booking Events ────────────────────────── notifyCalComBookingCreated( workspaceId: string, booking: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:created", { booking, timestamp: new Date().toISOString(), }); } notifyCalComBookingCancelled( workspaceId: string, bookingId: string, ) { this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:cancelled", { bookingId, timestamp: new Date().toISOString(), }); } notifyCalComBookingRescheduled( workspaceId: string, bookingId: string, ) { this.server.to(`workspace:${workspaceId}`).emit("calcom:booking:rescheduled", { bookingId, timestamp: new Date().toISOString(), }); } // ─── Documenso Document Events ───────────────────────── notifyDocumensoDocumentSent( workspaceId: string, document: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("documenso:document:sent", { document, timestamp: new Date().toISOString(), }); } notifyDocumensoDocumentStatusChanged( workspaceId: string, documentId: string | number, status: string, ) { this.server.to(`workspace:${workspaceId}`).emit("documenso:document:status-changed", { documentId, status, timestamp: new Date().toISOString(), }); } // ─── Document Management Events ───────────────────────── notifyDocumentUploaded( workspaceId: string, document: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("document:uploaded", { document, timestamp: new Date().toISOString(), }); } notifyDocumentShared( workspaceId: string, share: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("document:shared", { share, timestamp: new Date().toISOString(), }); } notifyDocumentRevoked( workspaceId: string, shareId: string, ) { this.server.to(`workspace:${workspaceId}`).emit("document:revoked", { shareId, timestamp: new Date().toISOString(), }); } notifyDocumentTamperingDetected( workspaceId: string, documentId: string, ) { this.server.to(`workspace:${workspaceId}`).emit("document:tampering-detected", { documentId, timestamp: new Date().toISOString(), }); } // ─── Listmonk Newsletter Events ──────────────────────── notifyListmonkSubscriberAdded( workspaceId: string, subscriber: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("listmonk:subscriber:added", { subscriber, timestamp: new Date().toISOString(), }); } notifyListmonkCampaignSent( workspaceId: string, campaign: Record, ) { this.server.to(`workspace:${workspaceId}`).emit("listmonk:campaign:sent", { campaign, timestamp: new Date().toISOString(), }); } }