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

mock-update-server.ts

160 lines5.1 KB

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