games_app/backend/src/realtime/ws/supportHub.ts
2026-06-29 15:01:23 +02:00

169 lines
4.9 KiB
TypeScript

import type WebSocket from 'ws';
import { config } from '../../config';
import { connectRedis, getRedisSubscriber } from '../redis/client';
import { supportRedisKeys } from '../redis/supportKeys';
import { assertConversationAccess, isStaffRole } from '../../services/supportService';
import type { SupportRealtimeEvent } from '../../services/supportRealtimeService';
import { authenticateWsToken, extractBearerToken } from './auth';
type SupportClientState = {
socket: WebSocket;
userId?: string;
role?: string;
visitorToken?: string;
conversations: Set<string>;
inbox: boolean;
};
const STAFF_CHANNEL = supportRedisKeys.pubsubStaffInbox();
const CONV_CHANNEL_PREFIX = 'prediqo:pubsub:support:conv:';
function parseSupportEvent(raw: string): (SupportRealtimeEvent & { ts?: number }) | null {
try {
const parsed = JSON.parse(raw) as SupportRealtimeEvent;
if (!parsed?.type) return null;
return parsed;
} catch {
return null;
}
}
function serialize(msg: Record<string, unknown>): string {
return JSON.stringify(msg);
}
export class SupportWsHub {
private clients = new Set<SupportClientState>();
async start(): Promise<void> {
if (!config.redis.enabled) {
console.warn('[support-ws] Redis disabled — support push unavailable');
return;
}
await connectRedis();
const sub = getRedisSubscriber();
if (!sub) return;
sub.on('pmessage', (_pattern, channel, message) => {
const event = parseSupportEvent(message);
if (!event) return;
this.dispatch(channel, event);
});
await sub.psubscribe('prediqo:pubsub:support:*');
console.log('[support-ws] subscribed to prediqo:pubsub:support:*');
}
register(socket: WebSocket, reqUrl: string, authHeader?: string): void {
const url = new URL(reqUrl, 'http://localhost');
const queryToken = url.searchParams.get('token') ?? undefined;
const visitorToken = url.searchParams.get('visitorToken')?.trim() || undefined;
const auth = authenticateWsToken(extractBearerToken(authHeader) ?? queryToken);
const state: SupportClientState = {
socket,
userId: auth?.userId,
role: auth?.role,
visitorToken: visitorToken && visitorToken.length >= 16 ? visitorToken : undefined,
conversations: new Set(),
inbox: false,
};
this.clients.add(state);
if (auth && isStaffRole(auth.role)) {
state.inbox = true;
}
socket.on('message', (data) => {
void this.handleClientMessage(state, String(data));
});
socket.on('close', () => {
this.clients.delete(state);
});
socket.send(
serialize({
type: 'connected',
authenticated: !!auth,
role: auth?.role ?? null,
path: config.ws.supportPath,
})
);
}
private async handleClientMessage(state: SupportClientState, raw: string): Promise<void> {
let msg: { type?: string; conversationId?: string; active?: boolean };
try {
msg = JSON.parse(raw) as { type?: string; conversationId?: string; active?: boolean };
} catch {
return;
}
if (msg.type === 'ping') {
this.send(state, { type: 'pong', ts: Date.now() });
return;
}
if (msg.type === 'subscribe' && msg.conversationId) {
try {
await assertConversationAccess(msg.conversationId, {
userId: state.userId,
role: state.role,
visitorToken: state.visitorToken,
});
state.conversations.add(msg.conversationId);
this.send(state, { type: 'subscribed', conversationId: msg.conversationId });
} catch {
this.send(state, { type: 'error', code: 'forbidden', message: 'Cannot subscribe to conversation' });
}
return;
}
if (msg.type === 'unsubscribe' && msg.conversationId) {
state.conversations.delete(msg.conversationId);
return;
}
if (msg.type === 'subscribe_inbox' && isStaffRole(state.role)) {
state.inbox = true;
this.send(state, { type: 'subscribed_inbox' });
}
}
private dispatch(channel: string, event: SupportRealtimeEvent & { ts?: number }): void {
const payload = { ...event, ts: event.ts ?? Date.now() };
if (channel === STAFF_CHANNEL) {
for (const client of this.clients) {
if (!client.inbox) continue;
this.send(client, payload);
}
return;
}
if (!channel.startsWith(CONV_CHANNEL_PREFIX)) return;
const conversationId = channel.slice(CONV_CHANNEL_PREFIX.length);
for (const client of this.clients) {
const watchesConv = client.conversations.has(conversationId);
const staffInbox = client.inbox && isStaffRole(client.role);
if (!watchesConv && !staffInbox) continue;
this.send(client, payload);
}
}
private send(client: SupportClientState, msg: Record<string, unknown>): void {
if (client.socket.readyState !== 1) return;
try {
client.socket.send(serialize(msg));
} catch {
/* ignore */
}
}
}
export const supportWsHub = new SupportWsHub();