Open History to see the last commit
1import Mime from "@effect/platform-node/Mime";
2import { Data, Effect, FileSystem, Option, Path } from "effect";
3import { cast } from "effect/Function";
4import {
5 HttpBody,
6 HttpClient,
7 HttpClientResponse,
8 HttpRouter,
9 HttpServerResponse,
10 HttpServerRequest,
11} from "effect/unstable/http";
12import { OtlpTracer } from "effect/unstable/observability";
13
14import {
15 ATTACHMENTS_ROUTE_PREFIX,
16 normalizeAttachmentRelativePath,
17 resolveAttachmentRelativePath,
18} from "./attachmentPaths";
19import { resolveAttachmentPathById } from "./attachmentStore";
20import { resolveStaticDir, ServerConfig } from "./config";
21import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
22import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
23import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
24import { ServerAuth } from "./auth/Services/ServerAuth.ts";
25import { respondToAuthError } from "./auth/http.ts";
26import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
27
28const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
29const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
30const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
31const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
32
33export const browserApiCorsLayer = HttpRouter.cors({
34 allowedMethods: ["GET", "POST", "OPTIONS"],
35 allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
36 maxAge: 600,
37});
38
39export function isLoopbackHostname(hostname: string): boolean {
40 const normalizedHostname = hostname
41 .trim()
42 .toLowerCase()
43 .replace(/^\[(.*)\]$/, "$1");
44 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
45}
46
47export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
48 const redirectUrl = new URL(devUrl.toString());
49 redirectUrl.pathname = requestUrl.pathname;
50 redirectUrl.search = requestUrl.search;
51 redirectUrl.hash = requestUrl.hash;
52 return redirectUrl.toString();
53}
54
55const requireAuthenticatedRequest = Effect.gen(function* () {
56 const request = yield* HttpServerRequest.HttpServerRequest;
57 const serverAuth = yield* ServerAuth;
58 yield* serverAuth.authenticateHttpRequest(request);
59});
60
61export const serverEnvironmentRouteLayer = HttpRouter.add(
62 "GET",
63 "/.well-known/t3/environment",
64 Effect.gen(function* () {
65 const descriptor = yield* Effect.service(ServerEnvironment).pipe(
66 Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
67 );
68 return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
69 }),
70);
71
72class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
73 readonly cause: unknown;
74 readonly bodyJson: OtlpTracer.TraceData;
75}> {}
76
77export const otlpTracesProxyRouteLayer = HttpRouter.add(
78 "POST",
79 OTLP_TRACES_PROXY_PATH,
80 Effect.gen(function* () {
81 yield* requireAuthenticatedRequest;
82 const request = yield* HttpServerRequest.HttpServerRequest;
83 const config = yield* ServerConfig;
84 const otlpTracesUrl = config.otlpTracesUrl;
85 const browserTraceCollector = yield* BrowserTraceCollector;
86 const httpClient = yield* HttpClient.HttpClient;
87 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
88
89 yield* Effect.try({
90 try: () => decodeOtlpTraceRecords(bodyJson),
91 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
92 }).pipe(
93 Effect.flatMap((records) => browserTraceCollector.record(records)),
94 Effect.catch((cause) =>
95 Effect.logWarning("Failed to decode browser OTLP traces", {
96 cause,
97 bodyJson,
98 }),
99 ),
100 );
101
102 if (otlpTracesUrl === undefined) {
103 return HttpServerResponse.empty({ status: 204 });
104 }
105
106 return yield* httpClient
107 .post(otlpTracesUrl, {
108 body: HttpBody.jsonUnsafe(bodyJson),
109 })
110 .pipe(
111 Effect.flatMap(HttpClientResponse.filterStatusOk),
112 Effect.as(HttpServerResponse.empty({ status: 204 })),
113 Effect.tapError((cause) =>
114 Effect.logWarning("Failed to export browser OTLP traces", {
115 cause,
116 otlpTracesUrl,
117 }),
118 ),
119 Effect.catch(() =>
120 Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
121 ),
122 );
123 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
124);
125
126export const attachmentsRouteLayer = HttpRouter.add(
127 "GET",
128 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
129 Effect.gen(function* () {
130 yield* requireAuthenticatedRequest;
131 const request = yield* HttpServerRequest.HttpServerRequest;
132 const url = HttpServerRequest.toURL(request);
133 if (Option.isNone(url)) {
134 return HttpServerResponse.text("Bad Request", { status: 400 });
135 }
136
137 const config = yield* ServerConfig;
138 const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
139 const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
140 if (!normalizedRelativePath) {
141 return HttpServerResponse.text("Invalid attachment path", { status: 400 });
142 }
143
144 const isIdLookup =
145 !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
146 const filePath = isIdLookup
147 ? resolveAttachmentPathById({
148 attachmentsDir: config.attachmentsDir,
149 attachmentId: normalizedRelativePath,
150 })
151 : resolveAttachmentRelativePath({
152 attachmentsDir: config.attachmentsDir,
153 relativePath: normalizedRelativePath,
154 });
155 if (!filePath) {
156 return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
157 status: isIdLookup ? 404 : 400,
158 });
159 }
160
161 const fileSystem = yield* FileSystem.FileSystem;
162 const fileInfo = yield* fileSystem
163 .stat(filePath)
164 .pipe(Effect.catch(() => Effect.succeed(null)));
165 if (!fileInfo || fileInfo.type !== "File") {
166 return HttpServerResponse.text("Not Found", { status: 404 });
167 }
168
169 return yield* HttpServerResponse.file(filePath, {
170 status: 200,
171 headers: {
172 "Cache-Control": "public, max-age=31536000, immutable",
173 },
174 }).pipe(
175 Effect.catch(() =>
176 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
177 ),
178 );
179 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
180);
181
182export const projectFaviconRouteLayer = HttpRouter.add(
183 "GET",
184 "/api/project-favicon",
185 Effect.gen(function* () {
186 yield* requireAuthenticatedRequest;
187 const request = yield* HttpServerRequest.HttpServerRequest;
188 const url = HttpServerRequest.toURL(request);
189 if (Option.isNone(url)) {
190 return HttpServerResponse.text("Bad Request", { status: 400 });
191 }
192
193 const projectCwd = url.value.searchParams.get("cwd");
194 if (!projectCwd) {
195 return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
196 }
197
198 const faviconResolver = yield* ProjectFaviconResolver;
199 const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
200 if (!faviconFilePath) {
201 return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
202 status: 200,
203 contentType: "image/svg+xml",
204 headers: {
205 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
206 },
207 });
208 }
209
210 return yield* HttpServerResponse.file(faviconFilePath, {
211 status: 200,
212 headers: {
213 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
214 },
215 }).pipe(
216 Effect.catch(() =>
217 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
218 ),
219 );
220 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
221);
222
223export const staticAndDevRouteLayer = HttpRouter.add(
224 "GET",
225 "*",
226 Effect.gen(function* () {
227 const request = yield* HttpServerRequest.HttpServerRequest;
228 const url = HttpServerRequest.toURL(request);
229 if (Option.isNone(url)) {
230 return HttpServerResponse.text("Bad Request", { status: 400 });
231 }
232
233 const config = yield* ServerConfig;
234 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
235 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
236 status: 302,
237 });
238 }
239
240 const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
241 if (!staticDir) {
242 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
243 status: 503,
244 });
245 }
246
247 const fileSystem = yield* FileSystem.FileSystem;
248 const path = yield* Path.Path;
249 const staticRoot = path.resolve(staticDir);
250 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
251 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
252 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
253 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
254 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
255 if (
256 staticRelativePath.length === 0 ||
257 hasRawLeadingParentSegment ||
258 hasPathTraversalSegment ||
259 staticRelativePath.includes("\0")
260 ) {
261 return HttpServerResponse.text("Invalid static file path", { status: 400 });
262 }
263
264 const isWithinStaticRoot = (candidate: string) =>
265 candidate === staticRoot ||
266 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
267
268 let filePath = path.resolve(staticRoot, staticRelativePath);
269 if (!isWithinStaticRoot(filePath)) {
270 return HttpServerResponse.text("Invalid static file path", { status: 400 });
271 }
272
273 const ext = path.extname(filePath);
274 if (!ext) {
275 filePath = path.resolve(filePath, "index.html");
276 if (!isWithinStaticRoot(filePath)) {
277 return HttpServerResponse.text("Invalid static file path", { status: 400 });
278 }
279 }
280
281 const fileInfo = yield* fileSystem
282 .stat(filePath)
283 .pipe(Effect.catch(() => Effect.succeed(null)));
284 if (!fileInfo || fileInfo.type !== "File") {
285 const indexPath = path.resolve(staticRoot, "index.html");
286 const indexData = yield* fileSystem
287 .readFile(indexPath)
288 .pipe(Effect.catch(() => Effect.succeed(null)));
289 if (!indexData) {
290 return HttpServerResponse.text("Not Found", { status: 404 });
291 }
292 return HttpServerResponse.uint8Array(indexData, {
293 status: 200,
294 contentType: "text/html; charset=utf-8",
295 });
296 }
297
298 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
299 const data = yield* fileSystem
300 .readFile(filePath)
301 .pipe(Effect.catch(() => Effect.succeed(null)));
302 if (!data) {
303 return HttpServerResponse.text("Internal Server Error", { status: 500 });
304 }
305
306 return HttpServerResponse.uint8Array(data, {
307 status: 200,
308 contentType,
309 });
310 }),
311);