1
Fork 0

Begin tracking active connections

This commit is contained in:
Tobias Berger 2022-01-08 20:23:03 +01:00
parent 25a11f5761
commit 00ce8f1016
Signed by: toby
GPG key ID: 2D05EFAB764D6A88

View file

@ -4,7 +4,11 @@ import { WebSocketServer } from "ws";
import * as crypto from "crypto";
import type { AckMessage, TextMessage } from "./lib/ServerMessage";
import type {
AckMessage,
IdResponseMessage,
TextMessage,
} from "./lib/ServerMessage";
import {
isServerMessage,
@ -41,7 +45,14 @@ async function handleTextMessage(message: TextMessage, from: string) {
}
}
webSocketServer.on("connection", function connection(socket, request) {
async function handleCloseConnection(id: string) {
activeConnections.delete(id);
}
const activeConnections = new Set<string>();
let nextId = 0;
webSocketServer.on("connection", function connection(socket) {
const close = (reason: string, code: number = 1000) => {
socket.send(
JSON.stringify({
@ -51,36 +62,24 @@ webSocketServer.on("connection", function connection(socket, request) {
} as AckMessage)
);
socket.close(code, `closing connection. reason: ${reason}`);
handleCloseConnection(authorId);
};
let authorID: string;
{
let ip: string | undefined;
if (request.headers["x-forwarded-for"] !== undefined) {
const forwardedFor = request.headers["x-forwarded-for"];
ip =
typeof forwardedFor === "string"
? forwardedFor.split(",")[0]?.trim()
: forwardedFor[0];
} else {
ip = request.socket.remoteAddress;
}
if (ip === undefined) {
close("could not generate author id", 1008);
console.error("connection without IP. closing.");
return;
}
authorID = hash(ip + SALT);
}
const authorId: string = hash(nextId++ + SALT);
socket.on("message", function (rawMessage: string) {
const message = JSON.parse(rawMessage);
if (!isServerMessage(message)) {
console.error(`Unexpected message received from client \`${message}\``);
return;
}
if (isTextMessage(message)) {
handleTextMessage(message, authorID);
if (message.author === authorId) {
handleTextMessage(message, authorId);
}
}
clearTimeout(closeTimeout);
closeTimeout = setTimeout(close, timeout);
});
@ -88,14 +87,16 @@ webSocketServer.on("connection", function connection(socket, request) {
console.log("closed a connection");
});
console.log("new client connected! ID:", authorID);
console.log("new client connected! ID:", authorId);
socket.send(
JSON.stringify({
type: MessageType.ACK,
date: Date.now(),
type: MessageType.ID_RESPONSE,
__ctx: "connected successfully",
} as AckMessage)
date: Date.now(),
authorId,
} as IdResponseMessage)
);
activeConnections.add(authorId);
let closeTimeout = setTimeout(close, timeout);
});