Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(events): filter WebSocket streams by chat (#1778)

Yudhi Armyndharisa91c0f0e531d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2dad77ccd..626f64439 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Allow chat-restricted API keys to subscribe to chat WebSocket events.
- Allow chat-restricted MCP keys to read and send within their chat allowlist using the REST authorization rules.
- Carry `chatId` in `message.ack` and `message.failed` payloads so a webhook `chatId` filter scopes delivery events per chat.
- Filter stored messages by time, direction, type or message reference, with stable message-time pagination.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 0af4d5105..fdb1eac42 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -7108,7 +7108,7 @@ Live events are pushed as a **nested** envelope (note: `data` is under `payload`
}
```
-Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `TOO_MANY_SUBSCRIPTIONS`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty or not a string. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms (one per session and event subscribed); unsubscribe before subscribing to more.
+Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `FORBIDDEN_EVENTS`, `TOO_MANY_SUBSCRIPTIONS`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty or not a string. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms; chat-restricted subscriptions count every literal chat address form for each session and event. Unsubscribe before subscribing to more.
### Subscribable events
@@ -7144,6 +7144,7 @@ A subscribe request whose `events` array contains no recognized name (after filt
### Wildcards and scoping
+- **Chat-restricted keys receive only events for `allowedChats`.** Message and presence events require `data.chatId`; group events require `data.groupId`. Persisted phone/LID aliases are matched at delivery time, including mappings learned after subscribing. An event without a resolvable chat is omitted. Account events, calls, statuses, and QR codes are omitted even with `events: ["*"]`; a request containing only account events answers `FORBIDDEN_EVENTS`. These filters apply across Redis replicas. A changed chat authorization disconnects the socket on its next subscribe.
- **`sessionId: "*"`** subscribes to every session; **`events: ["*"]`** subscribes to every subscribable event. They combine (e.g. `"*"` + `["*"]` = every event of every session).
- The API key is **re-validated on every `subscribe`** (not just at connect), so a key revoked or expired mid-connection is caught — the server replies `UNAUTHORIZED` and disconnects.
- **Per-key session scope is enforced** against the fresh key: a key restricted via `allowedSessions` may NOT subscribe to `"*"` and may NOT subscribe to a session outside its allowlist — either is rejected with `FORBIDDEN_SESSION`. An unrestricted key (no `allowedSessions`) may subscribe to anything, including `"*"`.
diff --git a/src/modules/events/events.gateway.chat-scope.spec.ts b/src/modules/events/events.gateway.chat-scope.spec.ts
new file mode 100644
index 000000000..5af3b9886
--- /dev/null
+++ b/src/modules/events/events.gateway.chat-scope.spec.ts
@@ -0,0 +1,234 @@
+import type { ConfigService } from '@nestjs/config';
+import type { Server, Socket } from 'socket.io';
+import { EventsGateway } from './events.gateway';
+import { ChatScopeService } from '../auth/chat-scope.service';
+import type { AuthService } from '../auth/auth.service';
+import type { AuditService } from '../audit/audit.service';
+import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';
+import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+
+const PHONE = '[email protected]';
+const OTHER = '[email protected]';
+const key = (id: string, allowedChats: string[] | null, allowedSessions: string[] | null = ['s1']): ApiKey =>
+ ({ id, name: id, role: ApiKeyRole.VIEWER, allowedSessions, allowedChats }) as ApiKey;
+
+function socket(id: string) {
+ const rooms = new Set([id]);
+ const client = {
+ id,
+ rooms,
+ data: {},
+ disconnected: false,
+ handshake: { auth: { apiKey: id }, headers: {}, address: '127.0.0.1' },
+ emit: jest.fn(),
+ join: jest.fn((room: string) => {
+ rooms.add(room);
+ }),
+ leave: jest.fn((room: string) => {
+ rooms.delete(room);
+ }),
+ disconnect: jest.fn(() => {
+ client.disconnected = true;
+ rooms.clear();
+ }),
+ };
+ return client;
+}
+
+describe('chat-scoped WebSocket rooms', () => {
+ let gateway: EventsGateway;
+ let current: Record<string, ApiKey>;
+ let clients: ReturnType<typeof socket>[];
+ let lidPhone: string | null;
+ let mappingFails: boolean;
+ let resolveIds: jest.SpyInstance;
+ const subscribe = (client: ReturnType<typeof socket>, events = ['*'], sessionId = 's1') =>
+ gateway.handleMessage(client as unknown as Socket, { type: 'subscribe', sessionId, events });
+ const events = (client: ReturnType<typeof socket>) =>
+ client.emit.mock.calls
+ .map(([, frame]) => frame as { type: string; payload: { event: string } })
+ .filter(frame => frame.type === 'event');
+ const flush = () => new Promise<void>(resolve => setImmediate(resolve));
+ const connect = async (id: string, chats: string[] | null, sessions: string[] | null = ['s1'], sessionId = 's1') => {
+ current[id] = key(id, chats, sessions);
+ const client = socket(id);
+ clients.push(client);
+ await gateway.handleConnection(client as unknown as Socket);
+ await subscribe(client, ['*'], sessionId);
+ return client;
+ };
+
+ beforeEach(() => {
+ current = {};
+ clients = [];
+ lidPhone = null;
+ mappingFails = false;
+ const scope = new ChatScopeService({
+ phonesForLidsPersisted: jest.fn((lids: string[]) => {
+ if (mappingFails) return Promise.reject(new Error('Mapping lookup unavailable'));
+ return Promise.resolve(lids.includes('123456') ? { '123456': lidPhone } : {});
+ }),
+ lidsForPhonesPersisted: jest.fn().mockResolvedValue({}),
+ } as unknown as LidMappingStoreService);
+ resolveIds = jest.spyOn(scope, 'idsForFilter');
+ gateway = new EventsGateway(
+ { validateApiKey: jest.fn((id: string) => Promise.resolve(current[id])) } as unknown as AuthService,
+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,
+ { get: jest.fn((_name: string, fallback: unknown) => fallback) } as unknown as ConfigService,
+ scope,
+ );
+ // Room unions model the adapter's recipient deduplication, including remote recipients.
+ gateway.server = {
+ to: (room: string | string[]) => {
+ const target = new Set(Array.isArray(room) ? room : [room]);
+ const excluded = new Set<string>();
+ const broadcast = {
+ to: (next: string) => {
+ target.add(next);
+ return broadcast;
+ },
+ except: (next: string) => {
+ excluded.add(next);
+ return broadcast;
+ },
+ emit: (name: string, frame: unknown) => {
+ for (const client of clients) {
+ if ([...target].some(r => client.rooms.has(r)) && ![...excluded].some(r => client.rooms.has(r))) {
+ client.emit(name, frame);
+ }
+ }
+ },
+ };
+ return broadcast;
+ },
+ } as unknown as Server;
+ });
+
+ it('keeps restricted subscriptions out of the global stream and deduplicates overlapping rooms', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ const outside = await connect('outside', [OTHER]);
+ const unrestricted = await connect('unrestricted', null);
+ await subscribe(allowed, ['message.received', '*']);
+ expect(allowed.disconnected).toBe(false);
+ const held = [...allowed.rooms].filter(room => room.startsWith('session:'));
+ expect(held.length).toBeGreaterThan(0);
+ expect(held.every(room => room.includes(':chat:'))).toBe(true);
+ gateway.emitMessage('s1', { chatId: PHONE, body: 'allowed' });
+ await flush();
+ expect(events(allowed)).toHaveLength(1);
+ expect(events(outside)).toHaveLength(0);
+ expect(events(unrestricted)).toHaveLength(1);
+ });
+
+ it('performs no chat lookups for a local stream without restricted subscribers', async () => {
+ const previous = process.env.REDIS_ENABLED;
+ process.env.REDIS_ENABLED = 'false';
+ try {
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ await flush();
+ expect(events(unrestricted)).toHaveLength(1);
+ expect(resolveIds).not.toHaveBeenCalled();
+ } finally {
+ if (previous === undefined) delete process.env.REDIS_ENABLED;
+ else process.env.REDIS_ENABLED = previous;
+ }
+ });
+
+ it('resolves a phone/LID mapping learned after subscription', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(allowed)).toHaveLength(0);
+ lidPhone = '628111000111';
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(allowed)).toHaveLength(1);
+ });
+
+ it('keeps equal phone and LID digits separate without a persisted mapping', async () => {
+ const phone = await connect('phone', ['[email protected]']);
+ const lid = await connect('lid', ['123456@lid']);
+ gateway.emitMessage('s1', { chatId: '123456@lid' });
+ await flush();
+ expect(events(phone)).toHaveLength(0);
+ expect(events(lid)).toHaveLength(1);
+ gateway.emitMessage('s1', { chatId: '[email protected]' });
+ await flush();
+ expect(events(phone)).toHaveLength(1);
+ expect(events(lid)).toHaveLength(1);
+ });
+
+ it('fails closed on a mapping lookup failure while retaining unrestricted delivery', async () => {
+ const allowed = await connect('allowed', [PHONE]);
+ const unrestricted = await connect('unrestricted', null);
+ mappingFails = true;
+ gateway.emitMessage('s1', { chatId: PHONE });
+ await flush();
+ expect(events(allowed)).toHaveLength(0);
+ expect(events(unrestricted)).toHaveLength(1);
+ });
+
+ it('deduplicates chat rooms across wildcard and specific sessions', async () => {
+ const allowed = await connect('allowed', [PHONE], null, '*');
+ await subscribe(allowed, ['*', 'message.received']);
+ gateway.emitMessage('s1', { chatId: PHONE });
+ gateway.emitMessage('s2', { chatId: PHONE });
+ await flush();
+ expect(events(allowed)).toHaveLength(2);
+ });
+
+ it('grants no stream rooms to an allowlist with no chattable identities', async () => {
+ const client = await connect('invalid', ['status@broadcast', '']);
+ expect(await subscribe(client)).toMatchObject({ code: 'FORBIDDEN_EVENTS' });
+ expect([...client.rooms].filter(room => room.startsWith('session:'))).toEqual([]);
+ });
+
+ it('omits account-wide events and receipts without a chat while admitting group events', async () => {
+ const allowed = await connect('allowed', ['[email protected]']);
+ const unrestricted = await connect('unrestricted', null);
+ gateway.emitQRCode('s1', 'private-qr');
+ gateway.emitSessionStatus('s1', 'ready');
+ gateway.emitCallReceived('s1', { from: PHONE });
+ gateway.emitStatusReceived('s1', { chatId: '[email protected]' });
+ gateway.emitMessageAck('s1', { id: 'm1', messageId: 'm1', status: 'delivered', ack: 2 });
+ gateway.emitGroupJoin('s1', { groupId: '[email protected]', participantIds: [PHONE] });
+ await flush();
+ expect(events(allowed).map(frame => frame.payload.event)).toEqual(['group.join']);
+ expect(events(unrestricted)).toHaveLength(5);
+ });
+
+ it('rejects explicit account events and retains the session fence', async () => {
+ const client = await connect('allowed', [PHONE]);
+ const session = await subscribe(client, ['*'], '*');
+ expect(session).toMatchObject({ code: 'FORBIDDEN_SESSION' });
+ const account = await subscribe(client, ['session.qr']);
+ expect(account).toMatchObject({ code: 'FORBIDDEN_EVENTS' });
+ });
+
+ it('disconnects a changed chat authorization before granting more rooms', async () => {
+ const client = await connect('allowed', [PHONE]);
+ current.allowed = key('allowed', [OTHER]);
+ expect(await subscribe(client)).toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(client.disconnected).toBe(true);
+ });
+
+ it('removes chat rooms on unsubscribe and counts them against the subscription cap', async () => {
+ const client = await connect('allowed', [PHONE]);
+ await gateway.handleMessage(client as unknown as Socket, { type: 'unsubscribe', sessionId: 's1' });
+ expect([...client.rooms].filter(room => room.startsWith('session:'))).toEqual([]);
+ const many = await connect(
+ 'many',
+ Array.from({ length: 400 }, (_, i) => `${628100000000 + i}@c.us`),
+ );
+ const response = await subscribe(many, [
+ 'message.received',
+ 'message.sent',
+ 'message.ack',
+ 'message.revoked',
+ 'message.reaction',
+ 'message.edited',
+ ]);
+ expect(response).toMatchObject({ code: 'TOO_MANY_SUBSCRIPTIONS' });
+ });
+});
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index f7bbe2f82..9beb5bbd7 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -135,20 +135,13 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
expect(sock.data.rawApiKey).toBe('good');
});
- it('refuses a chat-restricted key at the handshake (event filtering is a later slice)', async () => {
+ it('accepts a chat-restricted key without granting global event rooms at the handshake', async () => {
authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null, allowedChats: ['[email protected]'] });
const sock = makeSocket({ apiKey: 'good' });
await gateway.handleConnection(asSocket(sock));
- expect(sock.disconnect).toHaveBeenCalled();
- expect(sock.emit).toHaveBeenCalled();
- expect(auditService.logWarn).toHaveBeenCalledWith(
- AuditAction.API_KEY_AUTH_FAILED,
- expect.objectContaining({
- apiKey: expect.objectContaining({ allowedChats: ['[email protected]'] }) as unknown,
- ipAddress: '203.0.113.5',
- metadata: { surface: 'websocket' },
- }),
- );
+ expect(sock.disconnect).not.toHaveBeenCalled();
+ expect(sessionRoomJoins(sock)).toEqual([]);
+ expect(auditService.logWarn).not.toHaveBeenCalled();
});
it('refuses a subscribe once the key has gained allowedChats after connect', async () => {
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 0a62c148b..7293f3b06 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -13,6 +13,8 @@ import { OnModuleDestroy } from '@nestjs/common';
import { createLogger } from '../../common/services/logger.service';
import { ConfigService } from '@nestjs/config';
import { AuthService } from '../auth/auth.service';
+import { ChatScopeService } from '../auth/chat-scope.service';
+import { isWsRedisEnabled } from './redis-io.adapter';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { resolveCorsPolicy } from '../../config/bootstrap-security';
@@ -61,6 +63,24 @@ import type {
import { SUBSCRIBABLE_EVENTS, buildRoomName } from './dto/ws-messages.dto';
import type { DeliveryStatus } from '../../engine/interfaces/whatsapp-engine.interface';
+const CHAT_EVENTS = new Set([
+ 'message.received',
+ 'message.sent',
+ 'message.ack',
+ 'message.revoked',
+ 'message.reaction',
+ 'message.edited',
+ 'group.join',
+ 'group.leave',
+ 'group.update',
+ 'group.join_request',
+ 'presence.update',
+]);
+
+function chatRoom(sessionId: string, event: string, chatId: string): string {
+ return `${buildRoomName(sessionId, event)}:chat:${encodeURIComponent(chatId)}`;
+}
+
/**
* Whether an API key may subscribe to a session's WebSocket event rooms.
* An unrestricted key (no `allowedSessions`) may subscribe to anything, including
@@ -155,6 +175,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
private readonly authService: AuthService,
private readonly auditService: AuditService,
private readonly configService: ConfigService,
+ private readonly chatScope: ChatScopeService = new ChatScopeService(),
) {
this.rateLimits = readWsRateLimitConfig();
this.frameLimiter = new TokenBucketLimiter(this.rateLimits.framePerSecond, this.rateLimits.frameBurst);
@@ -367,20 +388,6 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// for "Client IP could not be determined".
const validKey = await this.authService.validateApiKey(apiKey, clientIp);
- // A chat-restricted key cannot yet be filtered on a live event stream (chat scoping of the
- // event surface is the follow-up slice), so refuse the handshake rather than stream every
- // chat's events to it. Mirrors the REST guard's default-deny for unmarked routes.
- if ((validKey.allowedChats?.length ?? 0) > 0) {
- this.logger.warn(`Client ${client.id} rejected: chat-scoped key ${validKey.id} cannot subscribe to events`);
- this.auditChatScopedRefusal(validKey, clientIp);
- client.emit(
- 'message',
- this.createError('UNAUTHORIZED', 'API keys restricted to selected chats cannot subscribe to events'),
- );
- client.disconnect();
- return;
- }
-
// Cap simultaneous sockets per key: each socket holds rooms, engine fan-out, and memory,
// so one key must not open connections without bound. Enough for multi-tab dashboards;
// excess connections get a clear error, not a silent drop.
@@ -441,15 +448,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
/**
- * A refused chat-scoped key is a stored key turned away, which the REST guard, the MCP surface and
- * Bull Board all record; the socket refusal returns before the handshake's catch, so it audits here.
+ * Record a stored key refused after its authorization changed while the socket was connected.
*/
- private auditChatScopedRefusal(apiKey: ApiKey, clientIp: string): void {
+ private auditAuthorizationRefusal(apiKey: ApiKey, clientIp: string, message: string): void {
void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {
apiKey,
ipAddress: clientIp,
metadata: { surface: 'websocket' },
- errorMessage: 'API keys restricted to selected chats cannot subscribe to events',
+ errorMessage: message,
});
}
@@ -571,17 +577,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
return this.createError('UNAUTHORIZED', 'Connection is closed', requestId);
}
- // The connect handshake refuses a chat-restricted key, but the key can gain allowedChats after
- // connect (a direct write to this node's main database, or an operator update that committed
- // between this socket's validation and its registration), so the fresh key is held to the same
- // rule here.
- if ((subscriberKey.allowedChats?.length ?? 0) > 0) {
- const refusal = this.createError(
- 'UNAUTHORIZED',
- 'API keys restricted to selected chats cannot subscribe to events',
- requestId,
- );
- this.auditChatScopedRefusal(subscriberKey, clientIp);
+ const snapshot = (client.data as { apiKey?: ApiKey }).apiKey;
+ const chatRestricted = this.chatScope.isRestricted(subscriberKey);
+ // A changed chat fence cannot reuse rooms granted under the previous authorization.
+ if (
+ (chatRestricted || this.chatScope.isRestricted(snapshot)) &&
+ apiKeyAuthorizationFingerprint(subscriberKey) !== this.snapshotFingerprint(client)
+ ) {
+ const refusal = this.createError('UNAUTHORIZED', EVICTION_MESSAGES.authorization_changed, requestId);
+ this.auditAuthorizationRefusal(subscriberKey, clientIp, refusal.message);
client.emit('message', refusal);
client.disconnect();
return refusal;
@@ -609,9 +613,11 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
// Validate each event type
- const validEvents = events.filter(
- e => e === '*' || SUBSCRIBABLE_EVENTS.includes(e as (typeof SUBSCRIBABLE_EVENTS)[number]),
- );
+ const validEvents = [
+ ...new Set(
+ events.filter(e => e === '*' || SUBSCRIBABLE_EVENTS.includes(e as (typeof SUBSCRIBABLE_EVENTS)[number])),
+ ),
+ ];
if (validEvents.length === 0) {
return this.createError(
'INVALID_EVENTS',
@@ -620,9 +626,22 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
);
}
+ const permittedEvents = chatRestricted
+ ? validEvents.filter(event => event === '*' || CHAT_EVENTS.has(event))
+ : validEvents;
+ if (permittedEvents.length === 0) {
+ return this.createError('FORBIDDEN_EVENTS', 'API key may subscribe only to chat events', requestId);
+ }
+ const chats = chatRestricted ? [...this.chatScope.scopeFor(subscriberKey)!.allowed] : undefined;
+ const rooms = permittedEvents.flatMap(event =>
+ chats ? chats.map(chatId => chatRoom(sessionId, event, chatId)) : [buildRoomName(sessionId, event)],
+ );
+ if (rooms.length === 0) {
+ return this.createError('FORBIDDEN_EVENTS', 'API key has no valid chats to subscribe to', requestId);
+ }
// Only subscription rooms count: the socket also sits in its own id room and may hold a role room.
const held = [...client.rooms].filter(room => room.startsWith('session:')).length;
- const newRooms = validEvents.filter(event => !client.rooms.has(buildRoomName(sessionId, event))).length;
+ const newRooms = rooms.filter(room => !client.rooms.has(room)).length;
if (held + newRooms > MAX_ROOMS_PER_SOCKET) {
return this.createError(
'TOO_MANY_SUBSCRIPTIONS',
@@ -632,11 +651,8 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
// Join rooms for each session/event combination
- const rooms: string[] = [];
- for (const event of validEvents) {
- const room = buildRoomName(sessionId, event);
+ for (const room of rooms) {
void client.join(room);
- rooms.push(room);
}
this.logger.debug(`Client ${client.id} subscribed to: ${rooms.join(', ')}`);
@@ -644,7 +660,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
return {
type: 'subscribed',
sessionId,
- events: validEvents,
+ events: permittedEvents,
requestId,
timestamp: new Date().toISOString(),
};
@@ -763,6 +779,37 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
.to(buildRoomName('*', event))
.to(buildRoomName('*', '*'));
(exceptRoom ? broadcast.except(exceptRoom) : broadcast).emit('message', eventMessage);
+ if (!CHAT_EVENTS.has(event) || data === null || typeof data !== 'object') return;
+ const value = data as Record<string, unknown>;
+ const chatId = event.startsWith('group.') ? value.groupId : value.chatId;
+ if (typeof chatId !== 'string' || !chatId.trim()) return;
+ if (
+ !isWsRedisEnabled() &&
+ !Array.from(this.socketsByKeyId.values()).some(sockets =>
+ Array.from(sockets).some(client => this.chatScope.isRestricted((client.data as { apiKey?: ApiKey }).apiKey)),
+ )
+ ) {
+ return;
+ }
+ // Expand the emitted identity using current persisted mappings, so new LID mappings work
+ // without rejoining rooms. Literal allowlist rooms also enforce the fence across Redis nodes.
+ void this.chatScope
+ .idsForFilter({ allowedChats: [chatId] })
+ .then(ids => {
+ if (!ids?.length) return;
+ const rooms = ids.flatMap(id => [
+ chatRoom(sessionId, event, id),
+ chatRoom(sessionId, '*', id),
+ chatRoom('*', event, id),
+ chatRoom('*', '*', id),
+ ]);
+ this.server.to(rooms).emit('message', eventMessage);
+ })
+ .catch(error =>
+ this.logger.warn('Could not resolve chat identity for WebSocket delivery', {
+ error: error instanceof Error ? error.message : String(error),
+ }),
+ );
}
/**