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