Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): refuse Socket.IO connections to the root namespace
Yudhi Armyndharisc2d996b30c80
diff --git a/src/modules/events/redis-io.adapter.spec.ts b/src/modules/events/redis-io.adapter.spec.tsindex 1078104b2..9431c8cc9 100644--- a/src/modules/events/redis-io.adapter.spec.ts+++ b/src/modules/events/redis-io.adapter.spec.ts@@ -54,9 +54,18 @@ describe('RedisIoAdapter', () => {process.env = { ...prevEnv };});- const fakeServer = (): { server: Server; adapterFn: jest.Mock } => {+ type NamespaceMiddleware = (socket: unknown, next: (error?: Error) => void) => void;++ const fakeServer = (): {+ server: Server;+ adapterFn: jest.Mock;+ namespaceOf: jest.Mock;+ rootUse: jest.Mock<void, [NamespaceMiddleware]>;+ } => {const adapterFn = jest.fn();- return { server: { adapter: adapterFn } as unknown as Server, adapterFn };+ const rootUse = jest.fn<void, [NamespaceMiddleware]>();+ const namespaceOf = jest.fn(() => ({ use: rootUse }));+ return { server: { adapter: adapterFn, of: namespaceOf } as unknown as Server, adapterFn, namespaceOf, rootUse };};/** Stub the base createIOServer so no real socket.io server is spun up. */@@ -116,6 +125,23 @@ describe('RedisIoAdapter', () => {}});+ it.each(['true', undefined])('refuses the root namespace whether or not Redis is enabled (%s)', enabled => {+ if (enabled === undefined) delete process.env.REDIS_ENABLED;+ else process.env.REDIS_ENABLED = enabled;+ const { server, namespaceOf, rootUse } = fakeServer();+ const spy = withBaseServer(server);+ try {+ new RedisIoAdapter({} as never).createIOServer(2785);+ expect(namespaceOf).toHaveBeenCalledWith('/');+ const [middleware] = rootUse.mock.calls[0];+ const next = jest.fn();+ middleware({}, next);+ expect(next).toHaveBeenCalledWith(expect.objectContaining({ message: 'Invalid namespace' }));+ } finally {+ spy.mockRestore();+ }+ });+it('attaches the Redis adapter with a pub/sub pair when Redis is enabled', () => {process.env.REDIS_ENABLED = 'true';const { server, adapterFn } = fakeServer();diff --git a/src/modules/events/redis-io.adapter.ts b/src/modules/events/redis-io.adapter.tsindex 887278db0..fe828d5b0 100644--- a/src/modules/events/redis-io.adapter.ts+++ b/src/modules/events/redis-io.adapter.ts@@ -31,6 +31,17 @@ export function wsRedisOptions(): RedisOptions {};}+/**+ * Socket.IO always creates the root namespace `/` and accepts a CONNECT to it with no middleware, while+ * everything this gateway enforces (the handshake limit, the per-key socket cap, the audit rows) lives on+ * `/events`. The 45 s connect timeout only closes a peer that joined no namespace at all, so a peer that+ * joins `/` and answers pings would stay connected for ever, outside every limit. Refusing `/` leaves such a+ * peer unjoined, and the timeout reaps it. No client of this gateway uses the root namespace.+ */+export function rejectRootNamespace(server: Server): void {+ server.of('/').use((_socket, next) => next(new Error('Invalid namespace')));+}+/*** A Socket.IO server whose broadcasts reach clients connected to OTHER replicas, via the Redis* pub/sub adapter.@@ -60,6 +71,7 @@ export class RedisIoAdapter extends IoAdapter {createIOServer(port: number, options?: ServerOptions): Server {const server = super.createIOServer(port, options) as Server;+ rejectRootNamespace(server);if (!isWsRedisEnabled()) return server;try {diff --git a/src/modules/events/root-namespace.spec.ts b/src/modules/events/root-namespace.spec.tsnew file mode 100644index 000000000..64eac0b3c--- /dev/null+++ b/src/modules/events/root-namespace.spec.ts@@ -0,0 +1,70 @@+import { createServer, type Server as HttpServer } from 'node:http';+import type { AddressInfo } from 'node:net';+import { Server } from 'socket.io';+import WebSocket from 'ws';+import { rejectRootNamespace } from './redis-io.adapter';++/**+ * What matters here is which peers Socket.IO's connect timeout reaps, so this runs a real server and raw+ * Engine.IO frames instead of mocks. The timers are short; the behaviour is the same at the 45 s default.+ */+describe('rejectRootNamespace', () => {+ let httpServer: HttpServer;+ let io: Server;+ let peers: WebSocket[];++ beforeEach(async () => {+ peers = [];+ httpServer = createServer();+ io = new Server(httpServer, { connectTimeout: 400, pingInterval: 150, pingTimeout: 150 });+ rejectRootNamespace(io);+ io.of('/events');+ await new Promise<void>(resolve => httpServer.listen(0, '127.0.0.1', resolve));+ });++ afterEach(async () => {+ for (const ws of peers) ws.terminate();+ await io.close();+ });++ /** A websocket peer that answers pings like a live client and sends `connect` once the server has opened. */+ const open = (connect: string): { frames: string[]; closed: () => boolean } => {+ const { port } = httpServer.address() as AddressInfo;+ const ws = new WebSocket(`ws://127.0.0.1:${port}/socket.io/?EIO=4&transport=websocket`);+ peers.push(ws);+ const frames: string[] = [];+ let closed = false;+ ws.on('message', (data: Buffer) => {+ const frame = data.toString();+ frames.push(frame);+ if (frame === '2') ws.send('3');+ if (frame.startsWith('0')) ws.send(connect);+ });+ ws.on('close', () => {+ closed = true;+ });+ return { frames, closed: () => closed };+ };+ const wait = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));++ it('refuses a CONNECT to the root namespace, so the connect timeout closes the peer', async () => {+ const peer = open('40');++ await wait(250);+ expect(peer.frames.some(frame => frame.startsWith('44') && frame.includes('Invalid namespace'))).toBe(true);+ expect(peer.closed()).toBe(false);++ await wait(500);+ expect(peer.closed()).toBe(true);+ });++ it('still admits a peer that joins /events, and keeps it past the connect timeout', async () => {+ const peer = open('40/events,');++ await wait(250);+ expect(peer.frames.some(frame => frame.startsWith('40/events,'))).toBe(true);++ await wait(500);+ expect(peer.closed()).toBe(false);+ });+});