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