forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

server.ts191 lines, 7.5 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
9// Every knob comes from the environment; the values themselves live in exactly
10// one place — the image's ENV block (see Containerfile), overridden per
11// deployment by hezarfen_frontend.env. Boot refuses rather than guessing: a
12// missing value here means the image was stripped or the process was started
13// outside it, and silently binding :5000-style defaults hides that.
14function required(name: string): string {
15 const value = Bun.env[name];
16 if (!value) {
17 console.error(
18 `${name} is not set. The image supplies the defaults (see the ENV block in Containerfile); ` +
19 `set ${name} in hezarfen_frontend.env to override them.`,
20 );
21 process.exit(1);
22 }
23 return value;
24}
25
26const PORT = Number(required("PORT"));
27const HOST = required("HOST");
28const BACKEND_ORIGIN = required("BACKEND_ORIGIN");
29const BACKEND_HTTP = BACKEND_ORIGIN.replace(/\/+$/, "");
30const BACKEND_WS = BACKEND_HTTP.replace(/^http/, "ws");
31function backendHost(origin: string): string {
32 try {
33 return new URL(origin).host;
34 } catch {
35 console.error(`BACKEND_ORIGIN is not a valid URL: ${origin}`);
36 process.exit(1);
37 }
38}
39
40const BACKEND_HOST = backendHost(BACKEND_HTTP);
41
42const DIST = `${import.meta.dir}/dist`;
43
44// Strip the /api prefix exactly like nginx did (rewrite ^/api(/.*)$ -> $1),
45// so /api/exams/x -> /exams/x and /api -> "".
46function backendPath(url: URL): string {
47 return url.pathname.replace(/^\/api(?=\/|$)/, "") + url.search;
48}
49
50function isApi(pathname: string): boolean {
51 return pathname === "/api" || pathname.startsWith("/api/");
52}
53
54// One held-open client socket to the backend per browser socket. Frames are
55// piped both ways; messages that arrive before the upstream finishes its
56// handshake are queued, not dropped.
57type Bridge = {
58 upstream: WebSocket;
59 ready: boolean;
60 queue: (string | Uint8Array)[];
61};
62
63// Sent on every file this server answers itself (the SPA shell and its
64// assets). Framing is limited to our own origin: the app embeds same-origin
65// file previews, but no other site may frame it (clickjacking). HSTS is only
66// honoured over HTTPS, i.e. behind the TLS-terminating proxy in production.
67const SECURITY_HEADERS: Record<string, string> = {
68 "Content-Security-Policy": "frame-ancestors 'self'; object-src 'none'; base-uri 'self'",
69 "X-Frame-Options": "SAMEORIGIN",
70 "X-Content-Type-Options": "nosniff",
71 "Referrer-Policy": "strict-origin-when-cross-origin",
72 "Strict-Transport-Security": "max-age=31536000",
73};
74
75async function serveStatic(pathname: string): Promise<Response> {
76 // No path traversal out of dist.
77 if (pathname.includes("..")) return new Response("bad request", { status: 400, headers: SECURITY_HEADERS });
78 const rel = pathname === "/" ? "/index.html" : pathname;
79 const file = Bun.file(DIST + rel);
80 if (await file.exists()) {
81 const headers: Record<string, string> = { ...SECURITY_HEADERS };
82 // Vite emits content-hashed files under /assets — safe to cache forever.
83 if (rel.startsWith("/assets/")) headers["Cache-Control"] = "public, max-age=31536000, immutable";
84 else if (rel === "/index.html") headers["Cache-Control"] = "no-store";
85 return new Response(file, { headers });
86 }
87 // A missing hashed asset must stay a 404. Returning index.html here makes
88 // browsers report a misleading "failed to fetch dynamically imported
89 // module" because they receive HTML where JavaScript was requested.
90 if (rel.startsWith("/assets/")) return new Response("asset not found", { status: 404, headers: SECURITY_HEADERS });
91 // SPA fallback: unknown non-asset paths are client routes, serve the shell.
92 return new Response(Bun.file(`${DIST}/index.html`), { headers: { ...SECURITY_HEADERS, "Cache-Control": "no-store" } });
93}
94
95async function proxyHttp(req: Request, url: URL): Promise<Response> {
96 const target = BACKEND_HTTP + backendPath(url);
97 const headers = new Headers(req.headers);
98 // Let fetch set Host from the target; forwarding the browser's Host confuses
99 // the backend's absolute-URL / cookie-domain logic.
100 headers.set("host", BACKEND_HOST);
101 const hasBody = req.method !== "GET" && req.method !== "HEAD";
102 const resp = await fetch(target, {
103 method: req.method,
104 headers,
105 body: hasBody ? req.body : undefined,
106 redirect: "manual",
107 // Stream the request body instead of buffering it (uploads).
108 ...(hasBody ? { duplex: "half" } : {}),
109 } as RequestInit);
110 return resp;
111}
112
113const server = Bun.serve<Bridge>({
114 port: PORT,
115 hostname: HOST,
116 // Long-running exam sockets must not be reaped by an idle timeout; the
117 // backend sends its own periodic state ticks but a quiet client can still
118 // sit for minutes between frames.
119 idleTimeout: 0,
120 async fetch(req, srv) {
121 let url: URL;
122 try {
123 url = new URL(req.url);
124 } catch {
125 return new Response("bad request", { status: 400 });
126 }
127
128 if (isApi(url.pathname)) {
129 // WebSocket upgrade (/api/exams/:id/attempt/ws): open the upstream and
130 // bridge. Forward the session cookie — it's what authenticates the WS.
131 if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
132 const cookie = req.headers.get("cookie") ?? undefined;
133 const proto = req.headers.get("sec-websocket-protocol") ?? undefined;
134 // SAFETY: Bun's WebSocket constructor accepts a protocol string array,
135 // while its DOM declaration selects an incompatible overload here.
136 const upstream = new WebSocket(BACKEND_WS + backendPath(url), {
137 headers: cookie ? { cookie } : undefined,
138 ...(proto ? { protocols: proto.split(",").map((p) => p.trim()) } : {}),
139 } as unknown as string[]);
140 const bridge: Bridge = { upstream, ready: false, queue: [] };
141 const ok = srv.upgrade(req, { data: bridge });
142 if (ok) return undefined;
143 upstream.close();
144 return new Response("websocket upgrade failed", { status: 426 });
145 }
146 return proxyHttp(req, url);
147 }
148
149 return serveStatic(url.pathname);
150 },
151 websocket: {
152 open(ws) {
153 const b = ws.data;
154 b.upstream.onopen = () => {
155 b.ready = true;
156 for (const m of b.queue) {
157 // SAFETY: Bun accepts Uint8Array websocket frames at runtime; its
158 // current DOM types reject ArrayBufferLike in this overload.
159 b.upstream.send(m as unknown as ArrayBuffer);
160 }
161 b.queue.length = 0;
162 };
163 b.upstream.onmessage = (e) => {
164 // e.data is string for text frames, ArrayBuffer/Uint8Array for binary.
165 ws.send(e.data as string | Uint8Array);
166 };
167 b.upstream.onclose = (e) => ws.close(e.code || 1000, e.reason);
168 b.upstream.onerror = () => {
169 try {
170 ws.close(1011, "upstream error");
171 } catch {
172 // socket already gone
173 }
174 };
175 },
176 message(ws, message) {
177 const b = ws.data;
178 if (b.ready) b.upstream.send(message);
179 else b.queue.push(message);
180 },
181 close(ws, code, reason) {
182 try {
183 ws.data.upstream.close(code >= 1000 && code <= 4999 ? code : 1000, reason);
184 } catch {
185 // upstream already closed
186 }
187 },
188 },
189});
190
191console.log(`serving dist/ on ${HOST}:${server.port}, proxying /api -> ${BACKEND_HTTP}`);