forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

server.ts138 lines, 5.2 KiBHistoryRawDownload
1// Production server: serve the built SPA and reverse-proxy /api/* to the
2// backend, so the browser stays same-origin (session cookies, no CORS). This
3// replaces the old nginx image — Bun serves the static `dist/` and bridges
4// both plain HTTP and the exam-room WebSocket through to the backend.
5//
6// Local dev uses Vite's own proxy (vite.config.ts); this file is only the
7// container's runtime after `vite build`.
8
9const PORT = Number(Bun.env.PORT ?? 5173);
10// Where the backend lives on the compose network. Override in compose.
11const BACKEND_ORIGIN = Bun.env.BACKEND_ORIGIN ?? "http://127.0.0.1:8080";
12const BACKEND_HTTP = BACKEND_ORIGIN.replace(/\/+$/, "");
13const BACKEND_WS = BACKEND_HTTP.replace(/^http/, "ws");
14const BACKEND_HOST = new URL(BACKEND_HTTP).host;
15
16const DIST = `${import.meta.dir}/dist`;
17
18// Strip the /api prefix exactly like nginx did (rewrite ^/api(/.*)$ -> $1),
19// so /api/exams/x -> /exams/x and /api -> "".
20function backendPath(url: URL): string {
21 return url.pathname.replace(/^\/api(?=\/|$)/, "") + url.search;
22}
23
24function isApi(pathname: string): boolean {
25 return pathname === "/api" || pathname.startsWith("/api/");
26}
27
28// One held-open client socket to the backend per browser socket. Frames are
29// piped both ways; messages that arrive before the upstream finishes its
30// handshake are queued, not dropped.
31type Bridge = {
32 upstream: WebSocket;
33 ready: boolean;
34 queue: (string | Uint8Array)[];
35};
36
37async function serveStatic(pathname: string): Promise<Response> {
38 // No path traversal out of dist.
39 if (pathname.includes("..")) return new Response("bad request", { status: 400 });
40 const rel = pathname === "/" ? "/index.html" : pathname;
41 const file = Bun.file(DIST + rel);
42 if (await file.exists()) {
43 const headers: Record<string, string> = {};
44 // Vite emits content-hashed files under /assets — safe to cache forever.
45 if (rel.startsWith("/assets/")) headers["Cache-Control"] = "public, max-age=31536000, immutable";
46 else if (rel === "/index.html") headers["Cache-Control"] = "no-store";
47 return new Response(file, { headers });
48 }
49 // SPA fallback: unknown paths are client routes, serve the shell.
50 return new Response(Bun.file(`${DIST}/index.html`), { headers: { "Cache-Control": "no-store" } });
51}
52
53async function proxyHttp(req: Request, url: URL): Promise<Response> {
54 const target = BACKEND_HTTP + backendPath(url);
55 const headers = new Headers(req.headers);
56 // Let fetch set Host from the target; forwarding the browser's Host confuses
57 // the backend's absolute-URL / cookie-domain logic.
58 headers.set("host", BACKEND_HOST);
59 const hasBody = req.method !== "GET" && req.method !== "HEAD";
60 const resp = await fetch(target, {
61 method: req.method,
62 headers,
63 body: hasBody ? req.body : undefined,
64 redirect: "manual",
65 // Stream the request body instead of buffering it (uploads).
66 ...(hasBody ? { duplex: "half" } : {}),
67 } as RequestInit);
68 return resp;
69}
70
71const server = Bun.serve<Bridge, {}>({
72 port: PORT,
73 hostname: "0.0.0.0",
74 // Long-running exam sockets must not be reaped by an idle timeout; the
75 // backend sends its own periodic state ticks but a quiet client can still
76 // sit for minutes between frames.
77 idleTimeout: 0,
78 async fetch(req, srv) {
79 const url = new URL(req.url);
80
81 if (isApi(url.pathname)) {
82 // WebSocket upgrade (/api/exams/:id/attempt/ws): open the upstream and
83 // bridge. Forward the session cookie — it's what authenticates the WS.
84 if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
85 const cookie = req.headers.get("cookie") ?? undefined;
86 const proto = req.headers.get("sec-websocket-protocol") ?? undefined;
87 const upstream = new WebSocket(BACKEND_WS + backendPath(url), {
88 headers: cookie ? { cookie } : undefined,
89 ...(proto ? { protocols: proto.split(",").map((p) => p.trim()) } : {}),
90 } as unknown as string[]);
91 const bridge: Bridge = { upstream, ready: false, queue: [] };
92 const ok = srv.upgrade(req, { data: bridge });
93 if (ok) return undefined;
94 upstream.close();
95 return new Response("websocket upgrade failed", { status: 426 });
96 }
97 return proxyHttp(req, url);
98 }
99
100 return serveStatic(url.pathname);
101 },
102 websocket: {
103 open(ws) {
104 const b = ws.data;
105 b.upstream.onopen = () => {
106 b.ready = true;
107 for (const m of b.queue) b.upstream.send(m);
108 b.queue.length = 0;
109 };
110 b.upstream.onmessage = (e) => {
111 // e.data is string for text frames, ArrayBuffer/Uint8Array for binary.
112 ws.send(e.data as string | Uint8Array);
113 };
114 b.upstream.onclose = (e) => ws.close(e.code || 1000, e.reason);
115 b.upstream.onerror = () => {
116 try {
117 ws.close(1011, "upstream error");
118 } catch {
119 // socket already gone
120 }
121 };
122 },
123 message(ws, message) {
124 const b = ws.data;
125 if (b.ready) b.upstream.send(message);
126 else b.queue.push(message);
127 },
128 close(ws, code, reason) {
129 try {
130 ws.data.upstream.close(code >= 1000 && code <= 4999 ? code : 1000, reason);
131 } catch {
132 // upstream already closed
133 }
134 },
135 },
136});
137
138console.log(`serving dist/ on :${server.port}, proxying /api -> ${BACKEND_HTTP}`);