server/utils/server.ts
Jesse Wierzbinski de69f27877
Some checks failed
CodeQL Scan / Analyze (javascript-typescript) (push) Failing after 1s
Build Docker Images / lint (push) Failing after 7s
Build Docker Images / check (push) Failing after 6s
Build Docker Images / tests (push) Failing after 6s
Build Docker Images / detect-circular (push) Failing after 6s
Deploy Docs to GitHub Pages / build (push) Failing after 0s
Build Docker Images / build (server, Dockerfile, ${{ github.repository_owner }}/server) (push) Has been skipped
Build Docker Images / build (worker, Worker.Dockerfile, ${{ github.repository_owner }}/worker) (push) Has been skipped
Deploy Docs to GitHub Pages / Deploy (push) Has been skipped
Mirror to Codeberg / Mirror (push) Failing after 0s
Nix Build / check (push) Failing after 1s
Test Publish / build (client) (push) Failing after 0s
Test Publish / build (sdk) (push) Failing after 0s
refactor(api): 🔊 Move HTTP logs to logtape/hono
2025-12-18 22:22:03 +01:00

57 lines
1.8 KiB
TypeScript

import type { ConfigSchema } from "@versia-server/config";
import { type Server, serve } from "bun";
import type { Hono } from "hono";
import { matches } from "ip-matching";
import type { z } from "zod";
import type { HonoEnv } from "~/types/api.ts";
export const createServer = (
config: z.infer<typeof ConfigSchema>,
app: Hono<HonoEnv>,
): Server<undefined> =>
serve({
port: config.http.bind_port,
reusePort: true,
tls: config.http.tls
? {
key: config.http.tls.key.file,
cert: config.http.tls.cert.file,
passphrase: config.http.tls.passphrase,
ca: config.http.tls.ca?.file,
}
: undefined,
hostname: config.http.bind,
async fetch(req, server): Promise<Response> {
const ip = server.requestIP(req);
const isTrustedProxy =
config.http.proxy_ips.includes("*") ||
(ip &&
config.http.proxy_ips.some((proxyIp) =>
matches(ip.address, proxyIp),
));
const url = new URL(req.url);
if (ip && isTrustedProxy) {
const xff = req.headers.get("x-forwarded-for");
const xfp = req.headers.get("x-forwarded-proto");
if (xff) {
const forwardedIps = xff.split(",").map((s) => s.trim());
const originalIp = forwardedIps[0];
ip.address = originalIp;
ip.family = originalIp.includes(":") ? "IPv6" : "IPv4";
}
if (xfp) {
url.protocol = xfp;
}
}
const output = await app.fetch(new Request(url, req), { ip });
return output;
},
});