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.orElseSucceed(() =>
160 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.stat(filePath).pipe(Effect.orElseSucceed(() => null));
209 if (!fileInfo || fileInfo.type !== "File") {
210 return HttpServerResponse.text("Not Found", { status: 404 });
211 }
212
213 return yield* HttpServerResponse.file(filePath, {
214 status: 200,
215 headers: {
216 "Cache-Control": "public, max-age=31536000, immutable",
217 },
218 }).pipe(
219 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
220 );
221 }).pipe(
222 Effect.catchTags({
223 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
224 EnvironmentInternalError: HttpServerRespondable.toResponse,
225 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
226 }),
227 ),
228);
229
230export const projectFaviconRouteLayer = HttpRouter.add(
231 "GET",
232 "/api/project-favicon",
233 Effect.gen(function* () {
234 yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
235 const request = yield* HttpServerRequest.HttpServerRequest;
236 const url = HttpServerRequest.toURL(request);
237 if (Option.isNone(url)) {
238 return HttpServerResponse.text("Bad Request", { status: 400 });
239 }
240
241 const projectCwd = url.value.searchParams.get("cwd");
242 if (!projectCwd) {
243 return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
244 }
245
246 const faviconResolver = yield* ProjectFaviconResolver;
247 const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
248 if (!faviconFilePath) {
249 return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
250 status: 200,
251 contentType: "image/svg+xml",
252 headers: {
253 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
254 },
255 });
256 }
257
258 return yield* HttpServerResponse.file(faviconFilePath, {
259 status: 200,
260 headers: {
261 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
262 },
263 }).pipe(
264 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
265 );
266 }).pipe(
267 Effect.catchTags({
268 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
269 EnvironmentInternalError: HttpServerRespondable.toResponse,
270 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
271 }),
272 ),
273);
274
275export const staticAndDevRouteLayer = HttpRouter.add(
276 "GET",
277 "*",
278 Effect.gen(function* () {
279 const request = yield* HttpServerRequest.HttpServerRequest;
280 const url = HttpServerRequest.toURL(request);
281
282 if (Option.isNone(url)) {
283 return HttpServerResponse.text("Bad Request", { status: 400 });
284 }
285
286 const config = yield* ServerConfig;
287 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
288 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
289 status: 302,
290 });
291 }
292
293 const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
294 if (!staticDir) {
295 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
296 status: 503,
297 });
298 }
299
300 const fileSystem = yield* FileSystem.FileSystem;
301 const path = yield* Path.Path;
302 const staticRoot = path.resolve(staticDir);
303 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
304 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
305 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
306 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
307 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
308 if (
309 staticRelativePath.length === 0 ||
310 hasRawLeadingParentSegment ||
311 hasPathTraversalSegment ||
312 staticRelativePath.includes("\0")
313 ) {
314 return HttpServerResponse.text("Invalid static file path", { status: 400 });
315 }
316
317 const isWithinStaticRoot = (candidate: string) =>
318 candidate === staticRoot ||
319 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
320
321 let filePath = path.resolve(staticRoot, staticRelativePath);
322 if (!isWithinStaticRoot(filePath)) {
323 return HttpServerResponse.text("Invalid static file path", { status: 400 });
324 }
325
326 const ext = path.extname(filePath);
327 if (!ext) {
328 filePath = path.resolve(filePath, "index.html");
329 if (!isWithinStaticRoot(filePath)) {
330 return HttpServerResponse.text("Invalid static file path", { status: 400 });
331 }
332 }
333
334 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => 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.orElseSucceed(() => 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.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
351 if (!data) {
352 return HttpServerResponse.text("Internal Server Error", { status: 500 });
353 }
354
355 return HttpServerResponse.uint8Array(data, {
356 status: 200,
357 contentType,
358 });
359 }),
360);