Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mock-update-server.ts

44 lines1.5 KB

1import { resolve, relative } from "node:path";
2import { realpathSync } from "node:fs";
3​
4const port = Number(process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000);
5const root =
6 process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT ??
7 resolve(import.meta.dirname, "..", "release-mock");
8​
9const mockServerLog = (level: "info" | "warn" | "error" = "info", message: string) => {
10 console[level](`[mock-update-server] ${message}`);
11};
12​
13function isWithinRoot(filePath: string): boolean {
14 try {
15 return !relative(realpathSync(root), realpathSync(filePath)).startsWith(".");
16 } catch (error) {
17 mockServerLog("error", `Error checking if file is within root: ${error}`);
18 return false;
19 }
21​
22Bun.serve({
23 port,
24 hostname: "localhost",
25 fetch: async (request) => {
26 const url = new URL(request.url);
27 const path = url.pathname;
28 mockServerLog("info", `Request received for path: ${path}`);
29 const filePath = resolve(root, `.${path}`);
30 if (!isWithinRoot(filePath)) {
31 mockServerLog("warn", `Attempted to access file outside of root: ${filePath}`);
32 return new Response("Not Found", { status: 404 });
33 }
34 const file = Bun.file(filePath);
35 if (!(await file.exists())) {
36 mockServerLog("warn", `Attempted to access non-existent file: ${filePath}`);
37 return new Response("Not Found", { status: 404 });
38 }
39 mockServerLog("info", `Serving file: ${filePath}`);
40 return new Response(file.stream());
41 },
42});
43​
44mockServerLog("info", `running on http://localhost:${port}`);