hlsa/backend/api/index.ts

53 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2024-11-20 07:25:04 -05:00
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,
})
);
});
2024-11-20 07:55:44 -05:00
res.statusCode = 204;
res.end();
2024-11-20 07:25:04 -05:00
}
});
server.listen(8080);