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