2021-03-04 21:28:02 +02:00
|
|
|
const websockets = require("ws");
|
2021-10-03 21:05:54 +03:00
|
|
|
const { v4 } = require("uuid");
|
|
|
|
const mongoose = require("mongoose");
|
2021-03-04 21:28:02 +02:00
|
|
|
|
2021-09-08 00:18:44 +03:00
|
|
|
const { policies, gatewayPingInterval, gatewayPingCheckInterval, clientFacingPingInterval } = require("../../../config");
|
2021-10-05 18:29:37 +03:00
|
|
|
const { experiments } = require("../../../config");
|
2021-03-17 03:01:11 +02:00
|
|
|
const User = require("../../../models/User");
|
2021-03-26 22:50:21 +02:00
|
|
|
const Channel = require("../../../models/Channel");
|
2021-10-02 22:50:12 +03:00
|
|
|
const Message = require("../../../models/Message");
|
2021-06-10 14:02:31 +03:00
|
|
|
const { parseMessage, packet } = require("./messageparser");
|
2021-03-17 03:01:11 +02:00
|
|
|
const { checkToken } = require("../../../common/auth/authfunctions");
|
2021-10-13 17:51:05 +03:00
|
|
|
const config = require("../../../config");
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-06 20:42:30 +03:00
|
|
|
const wsCloseCodes = {
|
|
|
|
PAYLOAD_ERROR: [4001, "Error while handling payload"],
|
|
|
|
NOT_AUTHENTICATED: [4002, "Not authenticated"],
|
|
|
|
SERVER_DENIED_CONNECTION: [4003, "Server denied connection"],
|
|
|
|
AUTHENTICATION_ERROR: [4004, "Authentication error"],
|
|
|
|
TOO_MANY_SESSIONS: [4005, "Too many sessions"],
|
|
|
|
NOT_AUTHORIZED: [4006, "Not authorized"],
|
|
|
|
FLOODING: [4007, "Flooding"],
|
2021-09-08 00:18:44 +03:00
|
|
|
NO_PING: [4008, "No ping"],
|
2021-10-13 17:51:05 +03:00
|
|
|
UNSUPPORTED_ATTRIBUTE: [4009, "Unsupported attribute"],
|
|
|
|
ILLEGAL_PAYLOAD_SIZE: [4010, "Illegal payload size"],
|
2021-09-06 20:42:30 +03:00
|
|
|
};
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-15 17:11:33 +03:00
|
|
|
const attributes = {
|
2021-10-02 22:50:12 +03:00
|
|
|
PRESENCE_UPDATES: "PRESENCE_UPDATES",
|
2021-09-15 16:39:08 +03:00
|
|
|
};
|
|
|
|
|
2021-10-03 21:05:54 +03:00
|
|
|
const supportedAttributes = [attributes.PRESENCE_UPDATES];
|
2021-09-15 16:39:08 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
class GatewaySession {
|
|
|
|
constructor() {
|
|
|
|
this.authenticated = false;
|
|
|
|
this.user = null;
|
|
|
|
this.token = null;
|
2021-10-03 21:05:54 +03:00
|
|
|
this.sessionId = v4();
|
2021-09-15 17:11:33 +03:00
|
|
|
this.attributes = [];
|
2021-09-14 17:02:29 +03:00
|
|
|
|
|
|
|
// Specific to websocket sessions
|
|
|
|
this.isWebsocketConnection = false;
|
|
|
|
this.ws = null;
|
|
|
|
this.lastPing = new Date();
|
|
|
|
this.channels = [];
|
|
|
|
}
|
2021-05-21 01:33:47 +03:00
|
|
|
|
2021-09-15 17:11:33 +03:00
|
|
|
hasAttribute(roleName) {
|
2021-09-15 16:39:08 +03:00
|
|
|
if (roleName.length < 1) return true; // TODO: HACK
|
2021-09-15 17:11:33 +03:00
|
|
|
return this.attributes.includes(roleName);
|
2021-09-15 16:39:08 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
setWebsocketClient(ws) {
|
|
|
|
this.ws = ws;
|
|
|
|
this.isWebsocketConnection = true;
|
2021-05-21 01:33:47 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
async authenticateWithToken(token) {
|
|
|
|
let user = null;
|
|
|
|
try {
|
|
|
|
user = await checkToken(token);
|
|
|
|
if (!user) return false;
|
|
|
|
this.token = token;
|
|
|
|
this.user = user;
|
|
|
|
this.authenticated = true;
|
|
|
|
return true;
|
|
|
|
} catch(e) {
|
|
|
|
return false;
|
|
|
|
}
|
2021-05-21 01:33:47 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
send(name, data) {
|
|
|
|
this.ws.send(packet(name, data));
|
2021-05-21 01:33:47 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
isReady() {
|
|
|
|
return this.authenticated && this.ws;
|
2021-05-21 01:33:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
class GatewayHandler {
|
|
|
|
constructor() {
|
2021-06-10 14:02:31 +03:00
|
|
|
this.sessionCounters = {};
|
2021-09-14 17:02:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// server event handlers
|
|
|
|
handleServerConfigRequest() {
|
|
|
|
return {
|
|
|
|
path: "/gateway"
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
handleServerReady(wss) {
|
|
|
|
this.wss = wss;
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-08 00:18:44 +03:00
|
|
|
this.pingCheckIntervalFunction = setInterval(() => {
|
2021-03-17 03:01:11 +02:00
|
|
|
this.wss.clients.forEach((client) => {
|
2021-09-08 00:18:44 +03:00
|
|
|
if ((new Date() - client.session.lastPing) >= gatewayPingInterval) {
|
2021-09-14 17:02:29 +03:00
|
|
|
client.close(wsCloseCodes.NO_PING[0], wsCloseCodes.NO_PING[1]);
|
2021-03-17 03:01:11 +02:00
|
|
|
}
|
|
|
|
});
|
2021-09-08 00:18:44 +03:00
|
|
|
}, gatewayPingCheckInterval);
|
2021-09-14 17:02:29 +03:00
|
|
|
}
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
handleServerClose() {
|
|
|
|
clearInterval(this.pingCheckIntervalFunction);
|
|
|
|
}
|
2021-03-04 21:28:02 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
handleConnection(ws) {
|
2021-09-15 15:54:08 +03:00
|
|
|
if (!policies.allowGatewayConnection) {
|
|
|
|
return ws.close(wsCloseCodes.SERVER_DENIED_CONNECTION[0], wsCloseCodes.SERVER_DENIED_CONNECTION[1]);
|
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
const session = new GatewaySession();
|
|
|
|
session.setWebsocketClient(ws);
|
2021-10-03 21:05:54 +03:00
|
|
|
session.send("HELLO", { pingInterval: clientFacingPingInterval, supportedAttributes });
|
2021-09-14 17:02:29 +03:00
|
|
|
return session;
|
|
|
|
}
|
2021-06-10 14:02:31 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
handleConnectionClose(ws) {
|
|
|
|
if (ws.session && ws.session.user && ws.session.channels) {
|
|
|
|
if (this.sessionCounters[ws.session.user._id] <= 1) {
|
2021-09-15 17:11:33 +03:00
|
|
|
this.eachInChannel({channelId: ws.session.channels[0], role: attributes.PRESENCE_UPDATES}, (client) => {
|
2021-09-14 17:02:29 +03:00
|
|
|
if (client.session && client.session.isReady()) {
|
|
|
|
client.session.send("EVENT_CHANNEL_MEMBERS", {
|
|
|
|
[ws.session.user._id]: {
|
|
|
|
_id: ws.session.user._id,
|
|
|
|
username: ws.session.user.username,
|
|
|
|
status: 0,
|
|
|
|
status_text: ""
|
2021-08-13 21:56:10 +03:00
|
|
|
}
|
2021-09-14 17:02:29 +03:00
|
|
|
});
|
2021-03-17 03:01:11 +02:00
|
|
|
}
|
2021-09-14 17:02:29 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
this.sessionCounters[ws.session.user._id]--;
|
|
|
|
if (this.sessionCounters[ws.session.user._id] <= 0) {
|
|
|
|
this.sessionCounters[ws.session.user._id] = null;
|
|
|
|
delete this.sessionCounters[ws.session.user._id];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-09-08 00:18:44 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
handleMessage(senderSession, packet) {
|
|
|
|
return this[`handle_${packet.opcodeType}`](packet, senderSession);
|
|
|
|
}
|
2021-09-08 00:18:44 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
// utility functions
|
|
|
|
addSessionCounter(id) {
|
|
|
|
if (!this.sessionCounters[id]) this.sessionCounters[id] = 0;
|
|
|
|
this.sessionCounters[id]++;
|
|
|
|
if (this.sessionCounters[id] > policies.perUserMaxGatewayConnections) return false;
|
|
|
|
return true;
|
|
|
|
}
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
getClients() {
|
|
|
|
return this.wss.clients;
|
|
|
|
}
|
2021-05-21 01:33:47 +03:00
|
|
|
|
2021-09-15 16:39:08 +03:00
|
|
|
eachInChannel({channelId, role=""}, callback) {
|
2021-09-14 17:02:29 +03:00
|
|
|
const clients = this.getClients();
|
|
|
|
clients.forEach((client) => {
|
2021-09-15 17:11:33 +03:00
|
|
|
if (client.session && client.session.isReady() && client.session.hasAttribute(role) && client.session.channels.includes(channelId))
|
2021-09-14 17:02:29 +03:00
|
|
|
callback(client);
|
|
|
|
});
|
|
|
|
}
|
2021-05-25 15:51:35 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
// Gateway message handlers
|
|
|
|
async handle_YOO({ data }, session) {
|
2021-09-15 15:56:24 +03:00
|
|
|
if (session.authenticated) return {error: wsCloseCodes.PAYLOAD_ERROR};
|
2021-09-14 17:02:29 +03:00
|
|
|
try {
|
|
|
|
if (!(await session.authenticateWithToken(data.token))) return {error: wsCloseCodes.AUTHENTICATION_ERROR};
|
|
|
|
} catch(e) {
|
|
|
|
return {error: wsCloseCodes.AUTHENTICATION_ERROR};
|
|
|
|
}
|
|
|
|
if (!this.addSessionCounter(session.user._id)) return {error: wsCloseCodes.TOO_MANY_SESSIONS};
|
|
|
|
|
2021-10-22 01:21:03 +03:00
|
|
|
const channels = (await Channel.find().lean().sort({ _id: -1 }).limit(50).select("-__v").populate("creator", User.getPulicFields(true))) || [];
|
2021-09-14 17:02:29 +03:00
|
|
|
session.channels = channels.map(x => x._id.toString());
|
|
|
|
|
2021-09-15 17:11:33 +03:00
|
|
|
if (data.attributes) {
|
|
|
|
if (!Array.isArray(data.attributes) || data.attributes.length > 8) return {error: wsCloseCodes.PAYLOAD_ERROR};
|
2021-10-03 21:05:54 +03:00
|
|
|
for (let i = 0; i < data.attributes.length; i++) {
|
|
|
|
if (!supportedAttributes.includes(data.attributes[i]))
|
|
|
|
return {error: wsCloseCodes.UNSUPPORTED_ATTRIBUTE};
|
2021-09-15 16:39:08 +03:00
|
|
|
}
|
2021-09-15 17:11:33 +03:00
|
|
|
session.attributes = data.attributes;
|
2021-09-15 16:39:08 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
session.send("YOO_ACK", { session_id: session.sessionId, channels, user: { username: session.user.username, _id: session.user._id }, __global_experiments: experiments });
|
|
|
|
|
|
|
|
const channel = session.channels[0];
|
|
|
|
if (channel) {
|
|
|
|
const presence = {};
|
|
|
|
|
2021-09-15 16:39:08 +03:00
|
|
|
this.eachInChannel({channelId: channel}, ({ session: remoteSession }) => {
|
2021-09-14 17:02:29 +03:00
|
|
|
presence[remoteSession.user._id] = {
|
|
|
|
_id: remoteSession.user._id,
|
|
|
|
username: remoteSession.user.username,
|
|
|
|
status: 1,
|
|
|
|
status_text: "Online"
|
|
|
|
};
|
2021-09-15 17:11:33 +03:00
|
|
|
if (remoteSession.sessionId !== session.sessionId && remoteSession.hasAttribute(attributes.PRESENCE_UPDATES)) {
|
2021-09-14 17:02:29 +03:00
|
|
|
remoteSession.send("EVENT_CHANNEL_MEMBERS", {
|
|
|
|
[session.user._id]: {
|
|
|
|
_id: session.user._id,
|
|
|
|
username: session.user.username,
|
|
|
|
status: 1,
|
|
|
|
status_text: "Online"
|
2021-05-21 01:33:47 +03:00
|
|
|
}
|
2021-09-14 17:02:29 +03:00
|
|
|
});
|
2021-03-17 03:01:11 +02:00
|
|
|
}
|
2021-03-04 21:28:02 +02:00
|
|
|
});
|
2021-09-14 17:02:29 +03:00
|
|
|
|
2021-09-15 17:11:33 +03:00
|
|
|
(session.hasAttribute(attributes.PRESENCE_UPDATES)) && session.send("EVENT_CHANNEL_MEMBERS", presence);
|
2021-09-14 17:02:29 +03:00
|
|
|
}
|
2021-03-04 21:28:02 +02:00
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
async handle_ACTION_PING({ data }, session) {
|
|
|
|
if (!session.isReady()) return {error: wsCloseCodes.NOT_AUTHENTICATED};
|
|
|
|
if (data !== "1") throw new Error("msg: ACTION_PING payload data should be a `1`");
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
const user = await checkToken(session.token);
|
|
|
|
if (!user) return {error: wsCloseCodes.AUTHENTICATION_ERROR};
|
|
|
|
session.lastPing = new Date();
|
|
|
|
}
|
2021-05-21 01:33:47 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
async handle_ACTION_CREATE_MESSAGE({ data }, session) {
|
|
|
|
if (!session.isReady()) return {error: wsCloseCodes.NOT_AUTHENTICATED};
|
|
|
|
if (typeof data.content !== "string" || typeof data.channel !== "object" || typeof data.channel._id !== "string") throw new Error("msg: invalid fields in json payload");
|
|
|
|
|
|
|
|
const messageContent = data.content.trim();
|
2021-09-15 16:39:08 +03:00
|
|
|
if (messageContent.length > 2000 || messageContent.length < 1) return;
|
2021-09-14 17:02:29 +03:00
|
|
|
if (data.channel._id.length !== 24) throw new Error("msg: payload has invalid id"); // MONGODB ONLY!!
|
|
|
|
|
|
|
|
// Check if the user is in that channel before broadcasting the message
|
|
|
|
if (!session.channels.includes(data.channel._id)) return {error: wsCloseCodes.NOT_AUTHORIZED};
|
|
|
|
|
2021-10-03 21:05:54 +03:00
|
|
|
this.eachInChannel({channelId: data.channel._id}, async ({ session: remoteSession }) => {
|
|
|
|
let id;
|
|
|
|
if (policies.allowSavingMessages) {
|
|
|
|
const message = await Message.create({
|
|
|
|
author: session.user._id,
|
|
|
|
channel: data.channel._id,
|
|
|
|
content: messageContent,
|
|
|
|
createdAt: new Date().getTime()
|
|
|
|
});
|
|
|
|
id = message._id;
|
|
|
|
} else {
|
|
|
|
id = new mongoose.Types.ObjectId();
|
|
|
|
}
|
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
remoteSession.send("EVENT_CREATE_MESSAGE", {
|
|
|
|
content: messageContent,
|
|
|
|
channel: {
|
|
|
|
_id: data.channel._id
|
|
|
|
},
|
|
|
|
author: {
|
|
|
|
_id: session.user._id,
|
|
|
|
username: session.user.username
|
|
|
|
},
|
2021-10-03 21:05:54 +03:00
|
|
|
_id: id
|
2021-09-14 17:02:29 +03:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
class GatewayServer {
|
|
|
|
constructor(httpServer) {
|
|
|
|
this.httpServer = httpServer;
|
|
|
|
this.wss = null;
|
|
|
|
this.handler = null;
|
|
|
|
}
|
2021-05-21 01:33:47 +03:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
bindHandler(handler) {
|
|
|
|
if (this.wss) throw new Error("GatewayServer: cannot bindHandler() to a server which already has a bound handler.");
|
|
|
|
|
|
|
|
const newHandler = new handler();
|
|
|
|
this.handler = newHandler;
|
|
|
|
this.wss = new websockets.Server({ server: this.httpServer, ...(this.handler.handleServerConfigRequest()) });
|
|
|
|
this.handler.handleServerReady(this.wss);
|
|
|
|
this.wss.on("close", () => this.handler.handleServerClose());
|
|
|
|
this.wss.on("connection", (ws) => {
|
|
|
|
const session = this.handler.handleConnection(ws);
|
|
|
|
if (!session)
|
|
|
|
return ws.close();
|
|
|
|
if (session.__error)
|
|
|
|
return ws.close(session.__error[0], session.__error[1]);
|
|
|
|
ws.session = session;
|
|
|
|
ws.on("message", async (data, isBinary) => {
|
|
|
|
try {
|
2021-10-13 17:51:05 +03:00
|
|
|
if (isBinary || !ws.session)
|
|
|
|
return ws.close(wsCloseCodes.PAYLOAD_ERROR[0], wsCloseCodes.PAYLOAD_ERROR[1]);
|
|
|
|
if (data.byteLength > config.gatewayMaxPayloadBytes)
|
2021-10-22 01:21:03 +03:00
|
|
|
return ws.close(wsCloseCodes.ILLEGAL_PAYLOAD_SIZE[0], wsCloseCodes.ILLEGAL_PAYLOAD_SIZE[1]);
|
2021-09-14 17:02:29 +03:00
|
|
|
const status = await this.handler.handleMessage(ws.session, parseMessage(data.toString()));
|
|
|
|
if (status && status.error) {
|
|
|
|
return ws.close(status.error[0], status.error[1]);
|
|
|
|
}
|
|
|
|
} catch(e) {
|
|
|
|
console.error("GatewayServer: unexpected error while attempting to handle payload", e);
|
|
|
|
ws.close(wsCloseCodes.PAYLOAD_ERROR[0], wsCloseCodes.PAYLOAD_ERROR[1]);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
ws.on("close", (code, reason) => {
|
|
|
|
this.handler.handleConnectionClose(ws, code, reason);
|
|
|
|
});
|
|
|
|
});
|
2021-03-17 03:01:11 +02:00
|
|
|
}
|
2021-09-14 17:02:29 +03:00
|
|
|
}
|
2021-03-17 03:01:11 +02:00
|
|
|
|
2021-09-14 17:02:29 +03:00
|
|
|
module.exports = { GatewayServer, GatewayHandler };
|