From ba497ee3eb52c4abf1464380d015d8c788714364 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Fri, 2 Sep 2022 00:24:04 +0100 Subject: [PATCH] fix(uws): prevent the server from crashing after upgrade This should fix a rare case where the Engine.IO connection was upgraded to WebSocket while the Socket.IO socket was disconnected, which would result in the following exception: > TypeError: Cannot read properties of undefined (reading 'forEach') > at subscribe (/node_modules/socket.io/dist/uws.js:87:11) > at Socket. (/node_modules/socket.io/dist/uws.js:28:17) > at Socket.emit (node:events:402:35) > at WebSocket.onPacket (/node_modules/engine.io/build/socket.js:214:22) > at WebSocket.emit (node:events:390:28) > at WebSocket.onPacket (/node_modules/engine.io/build/transport.js:92:14) > at WebSocket.onData (/node_modules/engine.io/build/transport.js:101:14) > at message (/node_modules/engine.io/build/userver.js:56:30) Related: /~https://github.com/socketio/socket.io/issues/4443 --- lib/uws.ts | 4 +++- test/uws.ts | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/uws.ts b/lib/uws.ts index 1abc6a0184..6e400c7f77 100644 --- a/lib/uws.ts +++ b/lib/uws.ts @@ -25,7 +25,9 @@ export function patchAdapter(app /* : TemplatedApp */) { if (isNew) { socket.conn.on("upgrade", () => { const rooms = this.sids.get(id); - subscribe(this.nsp.name, socket, isNew, rooms); + if (rooms) { + subscribe(this.nsp.name, socket, isNew, rooms); + } }); } }; diff --git a/test/uws.ts b/test/uws.ts index de185d7c03..814a2467fd 100644 --- a/test/uws.ts +++ b/test/uws.ts @@ -186,6 +186,12 @@ describe("socket.io with uWebSocket.js-based engine", () => { io.to("room1").emit("hello"); }); + it("should not crash when socket is disconnected before the upgrade", (done) => { + client.on("disconnect", () => done()); + + io.of("/").sockets.get(client.id)!.disconnect(); + }); + it("should serve static files", (done) => { const clientVersion = require("socket.io-client/package.json").version;