support reverse proxies

This commit is contained in:
Soph :3 2024-07-19 04:52:39 +03:00
parent 094aeb061c
commit 698fafb6ba
Signed by: sophie
GPG key ID: EDA5D222A0C270F2
3 changed files with 16 additions and 4 deletions

View file

@ -14,6 +14,8 @@ To use this server [use a patched client](https://git.sad.ovh/sophie/pianoverse_
``` ```
HASH="somesecurestring" HASH="somesecurestring"
PORT=8081 PORT=8081
# Only if you're running pianoverse_server under a proxy like Caddy, nginx or Apache
TRUST_PROXY=true
``` ```
![chat](assets/screenshot1.png) ![chat](assets/screenshot1.png)

View file

@ -9,9 +9,9 @@ export class Client {
uniqWsID: string; uniqWsID: string;
private ws: ServerWebSocket<Client>; private ws: ServerWebSocket<Client>;
constructor(ws: ServerWebSocket<Client>) { constructor(ws: ServerWebSocket<Client>, ip: string) {
this.ws = ws; this.ws = ws;
this.id = [...Bun.SHA256.hash(ws.remoteAddress + process.env.HASH)] this.id = [...Bun.SHA256.hash(ip + process.env.HASH)]
.slice(0, 7) .slice(0, 7)
.map((z) => z.toString(16)) .map((z) => z.toString(16))
.join(""); .join("");

View file

@ -41,7 +41,14 @@ export class Server {
Bun.serve({ Bun.serve({
// #region WS upgrading // #region WS upgrading
fetch(req, server) { fetch(req, server) {
if (server.upgrade(req, { data: req.headers.get("User-Agent") })) { let data;
if(process.env.TRUST_PROXY) {
data = req.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()
if(!data) {
console.log('Trust proxy is enabled, but XFF is empty. Spoofing / server issue?')
}
}
if (server.upgrade(req, { data })) {
return; return;
} }
return new Response("Upgrade failed", { status: 500 }); return new Response("Upgrade failed", { status: 500 });
@ -297,7 +304,10 @@ export class Server {
} }
}, },
open(ws: ServerWebSocket<Client>) { open(ws: ServerWebSocket<Client>) {
const client = new Client(ws); let ip: string = ws.remoteAddress;
if(process.env.TRUST_PROXY) ip = ws.data as unknown as string;
const client = new Client(ws, ip);
if (getSiteBan(client.id)) { if (getSiteBan(client.id)) {
ws.close(); ws.close();
return; return;