49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
import { createServer } from "http";
|
|
import { WebSocketServer } from "ws";
|
|
|
|
const server = createServer();
|
|
const wsServer = new WebSocketServer({ noServer: true });
|
|
let lastAutomoddedTime = Date.now();
|
|
|
|
wsServer.on("connection", (ws) => {
|
|
ws.on("error", console.error);
|
|
ws.send(
|
|
JSON.stringify({
|
|
lastAutomoddedTime,
|
|
})
|
|
);
|
|
});
|
|
|
|
server.on("upgrade", (req, socket, head) => {
|
|
const path = new URL(req.url!, "wss://automod.nin0.dev").pathname;
|
|
|
|
if (path === "/ws")
|
|
wsServer.handleUpgrade(req, socket, head, (ws) => {
|
|
wsServer.emit("connection", ws, req);
|
|
});
|
|
else socket.destroy();
|
|
});
|
|
|
|
server.on("request", (req, res) => {
|
|
if (!req.headers.upgrade) {
|
|
if (req.headers.authorization !== process.env.KEY) {
|
|
res.statusCode = 403;
|
|
return res.end();
|
|
}
|
|
|
|
const timeValueThatShouldBeTrusted = parseInt(
|
|
req.rawHeaders[req.rawHeaders.indexOf("X-Time") + 1]
|
|
);
|
|
lastAutomoddedTime = timeValueThatShouldBeTrusted;
|
|
|
|
wsServer.clients.forEach((c) => {
|
|
c.send(
|
|
JSON.stringify({
|
|
lastAutomoddedTime,
|
|
})
|
|
);
|
|
});
|
|
}
|
|
});
|
|
|
|
server.listen(8080);
|