Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(events): withhold session.qr from keys below OPERATOR

Yudhi Armyndharisb9d9ea1c57bd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ce9b6e97..f0af8499e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- The `session.qr` WebSocket event reaches only OPERATOR and ADMIN keys, matching `GET /api/sessions/{sessionId}/qr`; a VIEWER key subscribed by name or through a wildcard no longer receives the pairing QR.
+
### Added
- `GET /api/sessions` accepts a `name` query parameter that returns only the session with that exact name, also on the MCP `SessionFindAll` tool and the JavaScript, Python, Go, Java and PHP SDKs ([#1594](https://github.com/rmyndharis/OpenWA/issues/1594)). Thanks @rivenash.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 2f1f435ac..1105a0c44 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -6765,6 +6765,7 @@ A subscribe request whose `events` array contains no recognized name (after filt
- **`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 `"*"`.
+- **`session.qr` requires the OPERATOR role**, matching `GET /api/sessions/{sessionId}/qr`. A VIEWER key may still subscribe to it, by name or through a wildcard, but the QR is never delivered to its sockets; every other event is. The role is read from the key re-validated on each `subscribe`, so a key narrowed to VIEWER stops receiving the QR from its next `subscribe` (a role change also disconnects the key's sockets).
### Example (socket.io-client)
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index 47a247bb7..72247018d 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -4,7 +4,7 @@ import type { ConfigService } from '@nestjs/config';
// ConfigService stub for the media-shed knob: no override means the default cap applies.
const asConfig = (): { get: jest.Mock } => ({ get: jest.fn((_key: string, defaultValue?: unknown) => defaultValue) });
import { Socket } from 'socket.io';
-import { EventsGateway, isSessionSubscriptionAllowed } from './events.gateway';
+import { EventsGateway, QR_DENIED_ROOM, isSessionSubscriptionAllowed } from './events.gateway';
import { AuthService } from '../auth/auth.service';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
@@ -47,6 +47,7 @@ interface MockSocket {
emit: jest.Mock;
disconnect: jest.Mock;
join: jest.Mock;
+ leave: jest.Mock;
rooms: Set<string>;
}
@@ -61,8 +62,12 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
emit: jest.fn(),
disconnect: jest.fn(),
join: jest.fn(),
+ leave: jest.fn(),
rooms: new Set<string>(),
});
+ // Subscription rooms joined by the socket; the QR-denied role room is not a subscription.
+ const sessionRoomJoins = (s: MockSocket): string[] =>
+ s.join.mock.calls.map(([room]) => room as string).filter(room => room.startsWith('session:'));
const asSocket = (s: MockSocket): Socket => s as unknown as Socket;
const subscribeMsg = (sessionId: string, events: string[]): WSClientMessage =>
({ type: 'subscribe', sessionId, events, requestId: 'r1' }) as unknown as WSClientMessage;
@@ -172,7 +177,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
expect(res.type).toBe('error');
expect(res.code).toBe('INVALID_EVENTS');
- expect(sock.join).not.toHaveBeenCalled();
+ expect(sessionRoomJoins(sock)).toEqual([]);
});
it('keeps the valid events when a subscription mixes a valid and an unknown event', async () => {
@@ -202,7 +207,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
expect(res.type).toBe('error');
expect(res.code).toBe('FORBIDDEN_SESSION');
- expect(sock.join).not.toHaveBeenCalled();
+ expect(sessionRoomJoins(sock)).toEqual([]);
});
it('forbids a session-scoped key from subscribing to the * wildcard', async () => {
@@ -216,7 +221,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
)) as WSErrorResponse;
expect(res.code).toBe('FORBIDDEN_SESSION');
- expect(sock.join).not.toHaveBeenCalled();
+ expect(sessionRoomJoins(sock)).toEqual([]);
});
it('allows a session-scoped key to subscribe to a session in its allowlist', async () => {
@@ -246,7 +251,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
)) as WSErrorResponse;
expect(res.code).toBe('FORBIDDEN_SESSION');
- expect(sock.join).not.toHaveBeenCalled();
+ expect(sessionRoomJoins(sock)).toEqual([]);
});
// Client-IP resolution: an IP-restricted key (allowedIps set) must be ENFORCED at the WS surface,
@@ -378,11 +383,12 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
const makeCapturingServer = () => {
const rooms: string[] = [];
const emit = jest.fn();
- const op: { to: jest.Mock; emit: jest.Mock } = { to: jest.fn(), emit };
+ const op: { to: jest.Mock; except: jest.Mock; emit: jest.Mock } = { to: jest.fn(), except: jest.fn(), emit };
op.to.mockImplementation((r: string) => {
rooms.push(r);
return op;
});
+ op.except.mockImplementation(() => op);
const server = { to: jest.fn((r: string) => (rooms.push(r), op)) };
return { server, emit, rooms };
};
@@ -493,6 +499,148 @@ describe('EventsGateway.emitToRooms fan-out', () => {
});
});
+// session.qr is a pairing credential: GET /sessions/:sessionId/qr requires OPERATOR, so the socket push
+// must not hand it to a VIEWER key under any subscribe form. The stub below stands in for the Socket.IO
+// adapter: it tracks each socket's rooms and resolves to()/except() like a real broadcast (union of the
+// target rooms, minus sockets in an excluded room, one copy per socket).
+describe('EventsGateway session.qr role gate', () => {
+ interface RoomSocket {
+ id: string;
+ handshake: { headers: Record<string, string>; auth: { apiKey: string }; address: string };
+ data: Record<string, unknown>;
+ rooms: Set<string>;
+ received: WSEventMessage[];
+ emit: jest.Mock;
+ disconnect: jest.Mock;
+ join: (room: string) => void;
+ leave: (room: string) => void;
+ }
+ type Broadcast = {
+ to: (room: string) => Broadcast;
+ except: (room: string) => Broadcast;
+ emit: (channel: string, msg: WSEventMessage) => boolean;
+ };
+
+ let keys: Record<string, { id: string; name: string; role: string; allowedSessions: string[] | null }>;
+ let gateway: EventsGateway;
+ let sockets: RoomSocket[];
+
+ const broadcast = (to: string[], except: string[]): Broadcast => ({
+ to: room => broadcast([...to, room], except),
+ except: room => broadcast(to, [...except, room]),
+ emit: (_channel, msg) => {
+ for (const s of sockets) {
+ if (to.some(r => s.rooms.has(r)) && !except.some(r => s.rooms.has(r))) s.received.push(msg);
+ }
+ return true;
+ },
+ });
+
+ const connect = async (apiKey: string): Promise<RoomSocket> => {
+ const rooms = new Set<string>();
+ const sock: RoomSocket = {
+ id: `sock-${sockets.length}`,
+ handshake: { headers: {}, auth: { apiKey }, address: '203.0.113.5' },
+ data: {},
+ rooms,
+ received: [],
+ emit: jest.fn(),
+ disconnect: jest.fn(),
+ join: room => void rooms.add(room),
+ leave: room => void rooms.delete(room),
+ };
+ sockets.push(sock);
+ await gateway.handleConnection(sock as unknown as Socket);
+ return sock;
+ };
+ const subscribe = (sock: RoomSocket, sessionId: string, events: string[]) =>
+ gateway.handleMessage(
+ sock as unknown as Socket,
+ {
+ type: 'subscribe',
+ sessionId,
+ events,
+ requestId: 'r1',
+ } as unknown as WSClientMessage,
+ );
+ const qrEvents = (sock: RoomSocket) => sock.received.filter(m => m.payload.event === 'session.qr');
+
+ beforeEach(() => {
+ sockets = [];
+ keys = {
+ viewer: { id: 'k-viewer', name: 'viewer', role: 'viewer', allowedSessions: null },
+ operator: { id: 'k-operator', name: 'operator', role: 'operator', allowedSessions: null },
+ admin: { id: 'k-admin', name: 'admin', role: 'admin', allowedSessions: null },
+ };
+ gateway = new EventsGateway(
+ { validateApiKey: jest.fn((raw: string) => Promise.resolve({ ...keys[raw] })) } as unknown as AuthService,
+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,
+ asConfig() as unknown as ConfigService,
+ );
+ (gateway as unknown as { server: unknown }).server = { to: (room: string) => broadcast([room], []) };
+ });
+
+ it('never delivers the QR to a VIEWER socket, whatever it subscribed to, while OPERATOR and ADMIN get it', async () => {
+ const viewerByName = await connect('viewer');
+ const viewerSessionWildcard = await connect('viewer');
+ const viewerGlobalWildcard = await connect('viewer');
+ const viewerEventWildcard = await connect('viewer');
+ const operator = await connect('operator');
+ const admin = await connect('admin');
+ await subscribe(viewerByName, 'sess-1', ['session.qr']);
+ await subscribe(viewerSessionWildcard, 'sess-1', ['*']);
+ await subscribe(viewerGlobalWildcard, '*', ['*']);
+ await subscribe(viewerEventWildcard, '*', ['session.qr']);
+ await subscribe(operator, '*', ['*']);
+ await subscribe(admin, 'sess-1', ['session.qr']);
+
+ gateway.emitQRCode('sess-1', 'data:image/png;base64,QR');
+
+ for (const viewer of [viewerByName, viewerSessionWildcard, viewerGlobalWildcard, viewerEventWildcard]) {
+ expect(qrEvents(viewer)).toEqual([]);
+ }
+ expect(qrEvents(operator)).toHaveLength(1);
+ expect(qrEvents(operator)[0].payload.data).toEqual({ qrCode: 'data:image/png;base64,QR' });
+ expect(qrEvents(admin)).toHaveLength(1);
+ });
+
+ it('keeps delivering every other event to a VIEWER wildcard subscription', async () => {
+ const viewer = await connect('viewer');
+ await subscribe(viewer, '*', ['*']);
+
+ gateway.emitSessionStatus('sess-1', 'qr_ready');
+
+ expect(viewer.received.map(m => m.payload.event)).toEqual(['session.status']);
+ });
+
+ it('follows the role re-validated on subscribe: a narrowed key stops receiving the QR, a widened one starts', async () => {
+ const narrowed = await connect('operator');
+ const widened = await connect('viewer');
+ await subscribe(widened, 'sess-1', ['*']);
+ expect(widened.rooms.has(QR_DENIED_ROOM)).toBe(true);
+ keys.operator.role = 'viewer';
+ keys.viewer.role = 'operator';
+ await subscribe(narrowed, 'sess-1', ['*']);
+ await subscribe(widened, 'sess-1', ['*']);
+
+ gateway.emitQRCode('sess-1', 'data:image/png;base64,QR');
+
+ expect(qrEvents(narrowed)).toEqual([]);
+ expect(qrEvents(widened)).toHaveLength(1);
+ });
+
+ it('denies the QR to a key with an unrecognised role', async () => {
+ keys.viewer.role = 'unknown';
+ const sock = await connect('viewer');
+ await subscribe(sock, 'sess-1', ['session.qr']);
+
+ gateway.emitQRCode('sess-1', 'data:image/png;base64,QR');
+
+ expect(sock.rooms.has(QR_DENIED_ROOM)).toBe(true);
+ expect(qrEvents(sock)).toEqual([]);
+ });
+});
+
describe('event catalog ⇔ emitter invariants (drift guard)', () => {
// Derive the events the gateway ACTUALLY emits by invoking every public emit* room
// method against a capturing server. Reflection-based so it cannot rot: a new emit*
@@ -504,8 +652,9 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {
asConfig() as unknown as ConfigService,
);
const captured: string[] = [];
- const op: { to: () => unknown; emit: (ch: string, msg: WSEventMessage) => boolean } = {
+ const op: { to: () => unknown; except: () => unknown; emit: (ch: string, msg: WSEventMessage) => boolean } = {
to: () => op,
+ except: () => op,
emit: (_ch, msg) => (captured.push(msg.payload.event), true),
};
(gateway as unknown as { server: unknown }).server = { to: () => op };
@@ -559,6 +708,7 @@ describe('EventsGateway rate limiting', () => {
emit: jest.fn(),
disconnect: jest.fn(),
join: jest.fn(),
+ leave: jest.fn(),
rooms: new Set<string>(),
});
const asSocket = (s: MockSocket): Socket => s as unknown as Socket;
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 348dd76fd..2cf7667a4 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -17,7 +17,7 @@ import { AuditAction } from '../audit/entities/audit-log.entity';
import { resolveCorsPolicy } from '../../config/bootstrap-security';
import { resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';
import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';
-import type { ApiKey } from '../auth/entities/api-key.entity';
+import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';
import {
readWsRateLimitConfig,
TokenBucketLimiter,
@@ -75,6 +75,18 @@ export function isSessionSubscriptionAllowed(allowedSessions: string[] | null |
return allowedSessions.includes(sessionId);
}
+/**
+ * Room holding every socket whose key may NOT read a session's pairing QR over REST
+ * (`GET /sessions/:sessionId/qr` requires OPERATOR). `session.qr` is broadcast with this room
+ * excluded, which covers the explicit event name and both wildcard subscribe forms. Membership is
+ * set from the re-validated key on every subscribe, before any subscription room is joined, so a
+ * socket can never hold a subscription room without it.
+ */
+export const QR_DENIED_ROOM = 'role:qr-denied';
+
+/** Roles allowed to receive `session.qr`. Anything else, including an unknown role, is denied. */
+const QR_ALLOWED_ROLES: ReadonlySet<string> = new Set([ApiKeyRole.OPERATOR, ApiKeyRole.ADMIN]);
+
/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */
export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed' | 'expired';
@@ -367,7 +379,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// here too, not just at connect.
const rawApiKey = (client.data as { rawApiKey?: string }).rawApiKey;
const clientIp = this.resolveClientIp(client);
- let subscriberKey: { allowedSessions?: string[] | null } | null;
+ let subscriberKey: { allowedSessions?: string[] | null; role?: ApiKeyRole } | null;
try {
subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey, clientIp) : null;
} catch {
@@ -378,6 +390,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
client.disconnect();
return this.createError('UNAUTHORIZED', 'API key is no longer valid', requestId);
}
+ this.syncQrAccess(client, subscriberKey.role);
// Enforce per-key session scope against the FRESH key: a key restricted to specific
// sessions must not subscribe to '*' or a session outside its allowlist (#221).
@@ -421,6 +434,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
};
}
+ /** Put the socket in or out of the QR-denied room for its key's current role. */
+ private syncQrAccess(client: Socket, role: ApiKeyRole | undefined): void {
+ if (role && QR_ALLOWED_ROLES.has(role)) {
+ void client.leave(QR_DENIED_ROOM);
+ } else {
+ void client.join(QR_DENIED_ROOM);
+ }
+ }
+
private handleUnsubscribe(client: Socket, message: WSUnsubscribeRequest): WSUnsubscribedResponse {
const { sessionId, requestId } = message;
@@ -502,7 +524,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
/**
* Emit event to specific rooms based on sessionId and event type
*/
- private emitToRooms(sessionId: string, event: string, data: unknown): void {
+ private emitToRooms(sessionId: string, event: string, data: unknown, exceptRoom?: string): void {
const eventMessage: WSEventMessage = {
type: 'event',
payload: { event, sessionId, data },
@@ -513,12 +535,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// unions the rooms into a single broadcast, so a socket joined to several of
// them receives the event exactly once (Socket.IO dedups recipients per
// broadcast). Four separate .emit() calls would deliver one copy per room.
- this.server
+ // `except` is resolved by the adapter, so the exclusion also holds across nodes with Redis.
+ const broadcast = this.server
.to(buildRoomName(sessionId, event))
.to(buildRoomName(sessionId, '*'))
.to(buildRoomName('*', event))
- .to(buildRoomName('*', '*'))
- .emit('message', eventMessage);
+ .to(buildRoomName('*', '*'));
+ (exceptRoom ? broadcast.except(exceptRoom) : broadcast).emit('message', eventMessage);
}
/**
@@ -581,10 +604,11 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
/**
- * Emit QR code update for a session
+ * Emit QR code update for a session. Scanning the QR links a device to the account, so it only
+ * reaches keys that may read it over REST (OPERATOR and above).
*/
emitQRCode(sessionId: string, qrCode: string) {
- this.emitToRooms(sessionId, 'session.qr', { qrCode });
+ this.emitToRooms(sessionId, 'session.qr', { qrCode }, QR_DENIED_ROOM);
}
/**