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

http.ts

375 lines13.1 KB

1import Mime from "@effect/platform-node/Mime";
2import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 EnvironmentHttpApi,
6} from "@t3tools/contracts";
7import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import { cast } from "effect/Function";
16import {
17 Headers,
18 HttpBody,
19 HttpClient,
20 HttpClientResponse,
21 HttpRouter,
22 HttpServerResponse,
23 HttpServerRequest,
24 HttpServerRespondable,
25} from "effect/unstable/http";
26import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
27import { OtlpTracer } from "effect/unstable/observability";
28​
29import * as ServerConfig from "./config.ts";
30import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
31import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
32import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
33import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
34import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
35import {
36 annotateEnvironmentRequest,
37 failEnvironmentScopeRequired,
38 failEnvironmentAuthInvalid,
39 failEnvironmentInternal,
40} from "./auth/http.ts";
41import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
42import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
43​
44const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
45const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
46const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
47const GZIP_MIN_BYTES = 1024;
48​
49function acceptsGzip(value: string | undefined): boolean {
50 if (!value) return false;
51​
52 const accepted = new Map(
53 value.split(",").map((entry) => {
54 const [coding = "", ...parameters] = entry.trim().toLowerCase().split(";");
55 const quality = parameters
56 .map((parameter) => parameter.trim().match(/^q=(.+)$/)?.[1])
57 .find((parameter) => parameter !== undefined);
58 return [coding, quality === undefined ? 1 : Number(quality)] as const;
59 }),
60 );
61 return (accepted.get("gzip") ?? accepted.get("*") ?? 0) > 0;
63​
64function varyByAcceptEncoding(value: string | undefined): string {
65 if (!value) return "Accept-Encoding";
66 const values = new Set(value.split(",").map((entry) => entry.trim().toLowerCase()));
67 return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
69​
70const compressHttpResponse = Effect.fnUntraced(function* (
71 response: HttpServerResponse.HttpServerResponse,
72 acceptEncoding: string | undefined,
73) {
74 const body = response.body;
75 if (
76 body._tag !== "Uint8Array" ||
77 body.contentLength < GZIP_MIN_BYTES ||
78 !body.contentType.startsWith("application/json") ||
79 response.headers["content-encoding"]
80 ) {
81 return response;
82 }
83​
84 const variedResponse = HttpServerResponse.setHeader(
85 response,
86 "vary",
87 varyByAcceptEncoding(response.headers.vary),
88 );
89 if (!acceptsGzip(acceptEncoding)) return variedResponse;
90​
91 const compression = yield* HttpResponseCompression.HttpResponseCompression;
92 const headers = Headers.set(
93 Headers.remove(variedResponse.headers, "content-length"),
94 "content-encoding",
95 "gzip",
96 );
97 return compression.gzip(body.body, {
98 status: response.status,
99 statusText: response.statusText,
100 headers,
101 cookies: response.cookies,
102 contentType: body.contentType,
103 });
104});
105​
106export const httpCompressionLayer = HttpRouter.middleware(
107 (httpEffect) =>
108 Effect.flatMap(
109 Effect.all([httpEffect, HttpServerRequest.HttpServerRequest]),
110 ([response, request]) => compressHttpResponse(response, request.headers["accept-encoding"]),
111 ),
112 { global: true },
113);
114​
115export const browserApiCorsLayer = Layer.unwrap(
116 Effect.gen(function* () {
117 const config = yield* ServerConfig.ServerConfig;
118 const devOrigin = config.devUrl?.origin;
119 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
120 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
121 //
122 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
123 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
124 // through Vite and is same-origin (no preflight at all), so this is a
125 // safety net for the desktop renderer and any direct-to-backend caller.
126 return HttpRouter.cors({
127 ...(devOrigin
128 ? {
129 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
130 credentials: true,
131 }
132 : {}),
133 allowedMethods: browserApiCorsAllowedMethods,
134 allowedHeaders: browserApiCorsAllowedHeaders,
135 maxAge: 600,
136 });
137 }),
138);
139​
140export function isLoopbackHostname(hostname: string): boolean {
141 const normalizedHostname = hostname
142 .trim()
143 .toLowerCase()
144 .replace(/^\[(.*)\]$/, "$1");
145 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
147​
148export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
149 const redirectUrl = new URL(devUrl.toString());
150 redirectUrl.pathname = requestUrl.pathname;
151 redirectUrl.search = requestUrl.search;
152 redirectUrl.hash = requestUrl.hash;
153 return redirectUrl.toString();
155​
156const authenticateRawRouteWithScope = (
157 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
158) =>
159 Effect.gen(function* () {
160 const request = yield* HttpServerRequest.HttpServerRequest;
161 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
162 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
163 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
164 failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
165 ),
166 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
167 failEnvironmentInternal("internal_error", error),
168 ),
169 );
170 if (!session.scopes.includes(scope)) {
171 return yield* failEnvironmentScopeRequired(scope);
172 }
173 });
174​
175export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
176 EnvironmentHttpApi,
177 "metadata",
178 Effect.fnUntraced(function* (handlers) {
179 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
180 return handlers.handle(
181 "descriptor",
182 Effect.fn("environment.metadata.descriptor")(function* (args) {
183 yield* annotateEnvironmentRequest(args.endpoint.name);
184 return yield* serverEnvironment.getDescriptor;
185 }, traceRelayRequest),
186 );
187 }),
188);
189​
190class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
191 readonly cause: unknown;
192 readonly bodyJson: OtlpTracer.TraceData;
193}> {}
194​
195export const otlpTracesProxyRouteLayer = HttpRouter.add(
196 "POST",
197 OTLP_TRACES_PROXY_PATH,
198 Effect.gen(function* () {
199 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
200 const request = yield* HttpServerRequest.HttpServerRequest;
201 const config = yield* ServerConfig.ServerConfig;
202 const otlpTracesUrl = config.otlpTracesUrl;
203 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
204 const httpClient = yield* HttpClient.HttpClient;
205 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
206​
207 yield* Effect.try({
208 try: () => decodeOtlpTraceRecords(bodyJson),
209 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
210 }).pipe(
211 Effect.flatMap((records) => browserTraceCollector.record(records)),
212 Effect.catch((cause) =>
213 Effect.logWarning("Failed to decode browser OTLP traces", {
214 cause,
215 bodyJson,
216 }),
217 ),
218 );
219​
220 if (otlpTracesUrl === undefined) {
221 return HttpServerResponse.empty({ status: 204 });
222 }
223​
224 return yield* httpClient
225 .post(otlpTracesUrl, {
226 body: HttpBody.jsonUnsafe(bodyJson),
227 })
228 .pipe(
229 Effect.flatMap(HttpClientResponse.filterStatusOk),
230 Effect.as(HttpServerResponse.empty({ status: 204 })),
231 Effect.tapError((cause) =>
232 Effect.logWarning("Failed to export browser OTLP traces", {
233 cause,
234 otlpTracesUrl,
235 }),
236 ),
237 Effect.orElseSucceed(() =>
238 HttpServerResponse.text("Trace export failed.", { status: 502 }),
239 ),
240 );
241 }).pipe(
242 Effect.catchTags({
243 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
244 EnvironmentInternalError: HttpServerRespondable.toResponse,
245 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
246 }),
247 ),
248);
249​
250export const assetRouteLayer = HttpRouter.add(
251 "GET",
252 `${ASSET_ROUTE_PREFIX}/*`,
253 Effect.gen(function* () {
254 const request = yield* HttpServerRequest.HttpServerRequest;
255 const url = HttpServerRequest.toURL(request);
256 if (Option.isNone(url)) {
257 return HttpServerResponse.text("Bad Request", { status: 400 });
258 }
259​
260 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
261 const separatorIndex = suffix.indexOf("/");
262 if (separatorIndex <= 0) {
263 return HttpServerResponse.text("Not Found", { status: 404 });
264 }
265​
266 const asset = yield* resolveAsset(
267 suffix.slice(0, separatorIndex),
268 suffix.slice(separatorIndex + 1),
269 );
270 if (!asset) {
271 return HttpServerResponse.text("Not Found", { status: 404 });
272 }
273 return yield* HttpServerResponse.file(asset.path, {
274 status: 200,
275 headers: {
276 "Cache-Control": "private, max-age=3600",
277 "X-Content-Type-Options": "nosniff",
278 },
279 }).pipe(
280 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
281 );
282 }),
283);
284​
285export const staticAndDevRouteLayer = HttpRouter.add(
286 "GET",
287 "*",
288 Effect.gen(function* () {
289 const request = yield* HttpServerRequest.HttpServerRequest;
290 const url = HttpServerRequest.toURL(request);
291​
292 if (Option.isNone(url)) {
293 return HttpServerResponse.text("Bad Request", { status: 400 });
294 }
295​
296 const config = yield* ServerConfig.ServerConfig;
297 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
298 return HttpServerResponse.text("Not Found", { status: 404 });
299 }
300​
301 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
302 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
303 status: 302,
304 });
305 }
306​
307 const staticDir =
308 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
309 if (!staticDir) {
310 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
311 status: 503,
312 });
313 }
314​
315 const fileSystem = yield* FileSystem.FileSystem;
316 const path = yield* Path.Path;
317 const staticRoot = path.resolve(staticDir);
318 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
319 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
320 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
321 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
322 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
323 if (
324 staticRelativePath.length === 0 ||
325 hasRawLeadingParentSegment ||
326 hasPathTraversalSegment ||
327 staticRelativePath.includes("\0")
328 ) {
329 return HttpServerResponse.text("Invalid static file path", { status: 400 });
330 }
331​
332 const isWithinStaticRoot = (candidate: string) =>
333 candidate === staticRoot ||
334 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
335​
336 let filePath = path.resolve(staticRoot, staticRelativePath);
337 if (!isWithinStaticRoot(filePath)) {
338 return HttpServerResponse.text("Invalid static file path", { status: 400 });
339 }
340​
341 const ext = path.extname(filePath);
342 if (!ext) {
343 filePath = path.resolve(filePath, "index.html");
344 if (!isWithinStaticRoot(filePath)) {
345 return HttpServerResponse.text("Invalid static file path", { status: 400 });
346 }
347 }
348​
349 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
350 if (!fileInfo || fileInfo.type !== "File") {
351 const indexPath = path.resolve(staticRoot, "index.html");
352 const indexData = yield* fileSystem
353 .readFile(indexPath)
354 .pipe(Effect.orElseSucceed(() => null));
355 if (!indexData) {
356 return HttpServerResponse.text("Not Found", { status: 404 });
357 }
358 return HttpServerResponse.uint8Array(indexData, {
359 status: 200,
360 contentType: "text/html; charset=utf-8",
361 });
362 }
363​
364 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
365 const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
366 if (!data) {
367 return HttpServerResponse.text("Internal Server Error", { status: 500 });
368 }
369​
370 return HttpServerResponse.uint8Array(data, {
371 status: 200,
372 contentType,
373 });
374 }),
375);