1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
import WebSocket, { Server } from "../util/WebSocket";
import { IncomingMessage } from "http";
import { Close } from "./Close";
import { Message } from "./Message";
import { setHeartbeat } from "../util/setHeartbeat";
import { Send } from "../util/Send";
import { CLOSECODES, OPCODES } from "../util/Constants";
import { createDeflate } from "zlib";
import { URL } from "url";
var erlpack: any;
try {
erlpack = require("erlpack");
} catch (error) {}
// TODO: check rate limit
// TODO: specify rate limit in config
// TODO: check msg max size
export async function Connection(this: Server, socket: WebSocket, request: IncomingMessage) {
try {
socket.on("close", Close);
// @ts-ignore
socket.on("message", Message);
const { searchParams } = new URL(`http://localhost${request.url}`);
// @ts-ignore
socket.encoding = searchParams.get("encoding") || "json";
if (!["json", "etf"].includes(socket.encoding)) {
if (socket.encoding === "etf" && erlpack) throw new Error("Erlpack is not installed: 'npm i -D erlpack'");
return socket.close(CLOSECODES.Decode_error);
}
// @ts-ignore
socket.version = Number(searchParams.get("version")) || 8;
if (socket.version != 8) return socket.close(CLOSECODES.Invalid_API_version);
// @ts-ignore
socket.compress = searchParams.get("compress") || "";
if (socket.compress) {
if (socket.compress !== "zlib-stream") return socket.close(CLOSECODES.Decode_error);
socket.deflate = createDeflate({ chunkSize: 65535 });
socket.deflate.on("data", (chunk) => socket.send(chunk));
}
socket.events = {};
socket.permissions = {};
socket.sequence = 0;
setHeartbeat(socket);
await Send(socket, {
op: OPCODES.Hello,
d: {
heartbeat_interval: 1000 * 30,
},
});
socket.readyTimeout = setTimeout(() => {
return socket.close(CLOSECODES.Session_timed_out);
}, 1000 * 30);
} catch (error) {
console.error(error);
return socket.close(CLOSECODES.Unknown_error);
}
}
|