Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

323 lines11.4 KB

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