From 23511ec1018ba30b32974ef6cdd6619b59fa00f9 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Tue, 26 Jul 2022 23:24:58 -0700 Subject: socket error logging --- lib/sockets.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'lib') diff --git a/lib/sockets.js b/lib/sockets.js index e216d904..c80935d9 100644 --- a/lib/sockets.js +++ b/lib/sockets.js @@ -2,6 +2,7 @@ const jwt = require("jsonwebtoken"); const { v4: uuidv4 } = require("uuid"); const WebSocket = require("ws"); const { differenceInSeconds, subSeconds } = require("date-fns"); +const code = 1000; wss = new WebSocket.Server({ clientTracking: false, noServer: true }); @@ -64,7 +65,7 @@ setInterval(() => { for (const id in sockets[username]) { let ws = sockets[username][id]; ws.beats++; - if (ws.beats > 10) ws.close(); + if (ws.beats > 10) ws.close(code, "too many beats"); } } }, 2000); @@ -97,7 +98,7 @@ wss.on("connection", function(ws, req) { lastSeen[token] = new Date(); try { - if (!token || token === "null" || !jwt.decode(token)) return ws.close(); + if (!token || token === "null" || !jwt.decode(token)) return ws.close(code, `bad token ${token}`); const username = jwt.decode(token).username; if (!username) throw new Error("Invalid JWT token"); @@ -107,7 +108,7 @@ wss.on("connection", function(ws, req) { const p = existing.find(sid => sid !== id); sockets[username][p].send(JSON.stringify({ type: "logout" })); setTimeout(() => { - if (sockets[username][p]) sockets[username][p].close(); + if (sockets[username][p]) sockets[username][p].close(code, "too many sockets"); }, 5000); } sockets[username][id] = ws; @@ -151,7 +152,7 @@ wss.on("connection", function(ws, req) { } if (e.message.includes("not found")) ws.send(JSON.stringify({ type: "logout" })); - setTimeout(() => ws && ws.close(), 1000); + setTimeout(() => ws && ws.close(code, `closing due to error ${e.message}`), 1000); } break; case "token": @@ -186,7 +187,8 @@ wss.on("connection", function(ws, req) { } }); - ws.on("close", function() { + ws.on("close", function(code, reason) { + if (reason) console.log("closing socket", reason); try { const username = names[id]; if (sockets[username] && sockets[username][id]) { -- cgit v1.2.3