Open History to see the last commit
1import * as NodeHttp from "node:http";
2
3import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { Config, Effect, FileSystem, Layer, Path } from "effect";
6import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
7
8interface MockUpdateServerConfig {
9 readonly port: number;
10 readonly rootRealPath: string;
11}
12
13const resolveMockUpdateServerConfig = Effect.gen(function* () {
14 const fileSystem = yield* FileSystem.FileSystem;
15 const path = yield* Path.Path;
16 const config = yield* Config.all({
17 port: Config.port("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.withDefault(3000)),
18 root: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT").pipe(
19 Config.withDefault("../release-mock"),
20 ),
21 }).asEffect();
22
23 const resolvedRoot = path.resolve(import.meta.dirname, config.root);
24
25 return {
26 port: config.port,
27 rootRealPath: yield* fileSystem.realPath(resolvedRoot),
28 } satisfies MockUpdateServerConfig;
29});
30
31const isOutsideRoot = (rootRealPath: string, filePath: string) =>
32 Effect.gen(function* () {
33 const path = yield* Path.Path;
34 const relativePath = path.relative(rootRealPath, filePath);
35 return (
36 relativePath === ".." || relativePath.startsWith("../") || relativePath.startsWith("..\\")
37 );
38 });
39
40const isWithinRoot = (rootRealPath: string, filePath: string) =>
41 Effect.gen(function* () {
42 const fileSystem = yield* FileSystem.FileSystem;
43 const resolvedFilePath = yield* fileSystem.realPath(filePath).pipe(
44 Effect.match({
45 onFailure: () => undefined,
46 onSuccess: (resolvedPath) => resolvedPath,
47 }),
48 );
49
50 return (
51 resolvedFilePath !== undefined && !(yield* isOutsideRoot(rootRealPath, resolvedFilePath))
52 );
53 });
54
55const resolveRequestedFilePath = (rootRealPath: string, requestUrl: string | undefined) =>
56 Effect.gen(function* () {
57 const path = yield* Path.Path;
58 const rawPath = (requestUrl ?? "/").split("?", 1)[0] ?? "/";
59 const decodedPath = yield* Effect.try({
60 try: () => decodeURIComponent(rawPath),
61 catch: () => null,
62 }).pipe(
63 Effect.match({
64 onFailure: () => undefined,
65 onSuccess: (value) => value,
66 }),
67 );
68
69 if (!decodedPath) {
70 return undefined;
71 }
72
73 if (decodedPath.includes("\0")) {
74 return undefined;
75 }
76
77 const filePath = path.resolve(
78 rootRealPath,
79 `.${decodedPath.startsWith("/") ? decodedPath : `/${decodedPath}`}`,
80 );
81
82 return (yield* isOutsideRoot(rootRealPath, filePath)) ? undefined : filePath;
83 });
84
85const isServableFile = (rootRealPath: string, filePath: string) =>
86 Effect.gen(function* () {
87 const fileSystem = yield* FileSystem.FileSystem;
88 const stat = yield* fileSystem.stat(filePath).pipe(
89 Effect.match({
90 onFailure: () => undefined,
91 onSuccess: (info) => info,
92 }),
93 );
94
95 if (stat?.type !== "File") {
96 return false;
97 }
98
99 return yield* isWithinRoot(rootRealPath, filePath);
100 });
101
102export const makeMockUpdateRouteLayer = (rootRealPath: string) => {
103 return HttpRouter.add(
104 "*",
105 "*",
106 Effect.gen(function* () {
107 const request = yield* HttpServerRequest.HttpServerRequest;
108 const requestPath = (request.url ?? "/").split("?", 1)[0] ?? "/";
109 yield* Effect.logInfo(`Request received for path: ${requestPath}`);
110
111 const filePath = yield* resolveRequestedFilePath(rootRealPath, request.url);
112 if (!filePath) {
113 yield* Effect.logWarning(`Attempted to access file outside of root: ${request.url ?? "/"}`);
114 return HttpServerResponse.text("Not Found", { status: 404 });
115 }
116
117 if (!(yield* isServableFile(rootRealPath, filePath))) {
118 yield* Effect.logWarning(`Attempted to access invalid file: ${filePath}`);
119 return HttpServerResponse.text("Not Found", { status: 404 });
120 }
121
122 yield* Effect.logInfo(`Serving file: ${filePath}`);
123 return yield* HttpServerResponse.file(filePath, { status: 200 });
124 }).pipe(
125 Effect.catchCause((cause) =>
126 Effect.gen(function* () {
127 yield* Effect.logError(`Unhandled mock update request failure: ${cause}`);
128 return HttpServerResponse.text("Internal Server Error", { status: 500 });
129 }),
130 ),
131 ),
132 );
133};
134
135const makeMockUpdateServerLayer = (config: MockUpdateServerConfig) =>
136 HttpRouter.serve(makeMockUpdateRouteLayer(config.rootRealPath)).pipe(
137 Layer.provideMerge(
138 NodeHttpServer.layer(NodeHttp.createServer, {
139 host: "localhost",
140 port: config.port,
141 }),
142 ),
143 Layer.provideMerge(NodeServices.layer),
144 );
145
146if (import.meta.main) {
147 resolveMockUpdateServerConfig.pipe(
148 Effect.map(makeMockUpdateServerLayer),
149 Layer.unwrap,
150 Layer.launch,
151 Effect.provide(NodeServices.layer),
152 NodeRuntime.runMain,
153 );
154}