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

http.ts

427 lines15.7 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 * as Stream from "effect/Stream";
16import { cast } from "effect/Function";
17import {
18 HttpBody,
19 HttpClient,
20 HttpClientResponse,
21 HttpMiddleware,
22 HttpRouter,
23 HttpServerResponse,
24 HttpServerRequest,
25 HttpServerRespondable,
26} from "effect/unstable/http";
27import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
28import { OtlpTracer } from "effect/unstable/observability";
29​
30import * as ServerConfig from "./config.ts";
31import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
32import {
33 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
34 storeAttachmentUpload,
35 validateAttachmentUploadToken,
36} from "./assets/AttachmentUpload.ts";
37import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
38import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
39import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
40import {
41 annotateEnvironmentRequest,
42 failEnvironmentScopeRequired,
43 failEnvironmentAuthInvalid,
44 failEnvironmentInternal,
45} from "./auth/http.ts";
46import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
47import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
48​
49const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
50const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
51const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
52const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
53​
54// Types a browser may render as a document if a proxy strips the disposition
55// header. Downloads of these fall back to octet-stream.
56const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
57const isSafeDownloadMimeType = (mimeType: string): boolean =>
58 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
59 !/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
60const isSafeInlineVideoMimeType = (mimeType: string): boolean =>
61 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");
62​
63/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
64export function downloadContentDisposition(fileName?: string): string {
65 if (fileName === undefined) {
66 return "attachment";
67 }
68 // toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
69 // eslint-disable-next-line no-control-regex -- Header filenames must strip ASCII controls.
70 const sanitized = fileName.toWellFormed().replace(/[\u0000-\u001f"\\]/g, "_");
71 const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
72 const needsExtended = asciiFallback !== sanitized;
73 const extendedName = encodeURIComponent(sanitized).replace(
74 /['()*]/g,
75 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
76 );
77 return `attachment; filename="${asciiFallback}"${
78 needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
79 }`;
81​
82export function assetResponseHeaders(
83 filePath: string,
84 options?: {
85 readonly download?: boolean;
86 readonly fileName?: string;
87 readonly mimeType?: string;
88 },
89): Record<string, string> {
90 const lowerPath = filePath.toLowerCase();
91 const inlineVideoMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
92 return {
93 "Cache-Control": "private, max-age=3600",
94 "X-Content-Type-Options": "nosniff",
95 ...(options?.download
96 ? {
97 "Content-Disposition": downloadContentDisposition(options.fileName),
98 "Content-Security-Policy": "default-src 'none'; sandbox",
99 "Content-Type":
100 options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
101 ? options.mimeType
102 : "application/octet-stream",
103 }
104 : inlineVideoMimeType !== undefined && isSafeInlineVideoMimeType(inlineVideoMimeType)
105 ? { "Content-Type": inlineVideoMimeType }
106 : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
107 ? { "Content-Type": "text/html; charset=utf-8" }
108 : {}),
109 ...(!options?.download && lowerPath.endsWith(".svg")
110 ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
111 : {}),
112 };
114​
115export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
116 global: true,
117});
118​
119export const browserApiCorsLayer = Layer.unwrap(
120 Effect.gen(function* () {
121 const config = yield* ServerConfig.ServerConfig;
122 const devOrigin = config.devUrl?.origin;
123 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
124 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
125 //
126 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
127 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
128 // through Vite and is same-origin (no preflight at all), so this is a
129 // safety net for the desktop renderer and any direct-to-backend caller.
130 return HttpRouter.cors({
131 ...(devOrigin
132 ? {
133 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
134 credentials: true,
135 }
136 : {}),
137 allowedMethods: browserApiCorsAllowedMethods,
138 allowedHeaders: browserApiCorsAllowedHeaders,
139 maxAge: 600,
140 });
141 }),
142);
143​
144export function isLoopbackHostname(hostname: string): boolean {
145 const normalizedHostname = hostname
146 .trim()
147 .toLowerCase()
148 .replace(/^\[(.*)\]$/, "$1");
149 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
151​
152export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
153 const redirectUrl = new URL(devUrl.toString());
154 redirectUrl.pathname = requestUrl.pathname;
155 redirectUrl.search = requestUrl.search;
156 redirectUrl.hash = requestUrl.hash;
157 return redirectUrl.toString();
159​
160const authenticateRawRouteWithScope = (
161 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
162) =>
163 Effect.gen(function* () {
164 const request = yield* HttpServerRequest.HttpServerRequest;
165 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
166 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
167 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
168 failEnvironmentAuthInvalid(
169 EnvironmentAuth.serverAuthCredentialReason(error),
170 EnvironmentAuth.serverAuthDpopFailureReason(error),
171 ),
172 ),
173 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
174 failEnvironmentInternal("internal_error", error),
175 ),
176 );
177 if (!session.scopes.includes(scope)) {
178 return yield* failEnvironmentScopeRequired(scope);
179 }
180 });
181​
182export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
183 EnvironmentHttpApi,
184 "metadata",
185 Effect.fnUntraced(function* (handlers) {
186 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
187 return handlers.handle(
188 "descriptor",
189 Effect.fn("environment.metadata.descriptor")(function* (args) {
190 yield* annotateEnvironmentRequest(args.endpoint.name);
191 return yield* serverEnvironment.getDescriptor;
192 }, traceRelayRequest),
193 );
194 }),
195);
196​
197class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
198 readonly cause: unknown;
199 readonly bodyJson: OtlpTracer.TraceData;
200}> {}
201​
202export const otlpTracesProxyRouteLayer = HttpRouter.add(
203 "POST",
204 OTLP_TRACES_PROXY_PATH,
205 Effect.gen(function* () {
206 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
207 const request = yield* HttpServerRequest.HttpServerRequest;
208 const config = yield* ServerConfig.ServerConfig;
209 const otlpTracesUrl = config.otlpTracesUrl;
210 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
211 const httpClient = yield* HttpClient.HttpClient;
212 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
213​
214 yield* Effect.try({
215 try: () => decodeOtlpTraceRecords(bodyJson),
216 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
217 }).pipe(
218 Effect.flatMap((records) => browserTraceCollector.record(records)),
219 Effect.catch((cause) =>
220 Effect.logWarning("Failed to decode browser OTLP traces", {
221 cause,
222 bodyJson,
223 }),
224 ),
225 );
226​
227 if (otlpTracesUrl === undefined) {
228 return HttpServerResponse.empty({ status: 204 });
229 }
230​
231 return yield* httpClient
232 .post(otlpTracesUrl, {
233 body: HttpBody.jsonUnsafe(bodyJson),
234 })
235 .pipe(
236 Effect.flatMap(HttpClientResponse.filterStatusOk),
237 Effect.as(HttpServerResponse.empty({ status: 204 })),
238 Effect.tapError((cause) =>
239 Effect.logWarning("Failed to export browser OTLP traces", {
240 cause,
241 otlpTracesUrl,
242 }),
243 ),
244 Effect.orElseSucceed(() =>
245 HttpServerResponse.text("Trace export failed.", { status: 502 }),
246 ),
247 );
248 }).pipe(
249 Effect.catchTags({
250 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
251 EnvironmentInternalError: HttpServerRespondable.toResponse,
252 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
253 }),
254 ),
255);
256​
257export const assetRouteLayer = HttpRouter.add(
258 "GET",
259 `${ASSET_ROUTE_PREFIX}/*`,
260 Effect.gen(function* () {
261 const request = yield* HttpServerRequest.HttpServerRequest;
262 const url = HttpServerRequest.toURL(request);
263 if (Option.isNone(url)) {
264 return HttpServerResponse.text("Bad Request", { status: 400 });
265 }
266​
267 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
268 const separatorIndex = suffix.indexOf("/");
269 if (separatorIndex <= 0) {
270 return HttpServerResponse.text("Not Found", { status: 404 });
271 }
272​
273 const asset = yield* resolveAsset(
274 suffix.slice(0, separatorIndex),
275 suffix.slice(separatorIndex + 1),
276 );
277 if (!asset) {
278 return HttpServerResponse.text("Not Found", { status: 404 });
279 }
280 return yield* HttpServerResponse.file(asset.path, {
281 status: 200,
282 headers: assetResponseHeaders(
283 asset.path,
284 asset.download || asset.mimeType !== undefined
285 ? {
286 ...(asset.download ? { download: true } : {}),
287 ...(asset.fileName !== undefined ? { fileName: asset.fileName } : {}),
288 ...(asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {}),
289 }
290 : undefined,
291 ),
292 }).pipe(
293 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
294 );
295 }),
296);
297​
298export const attachmentUploadRouteLayer = HttpRouter.add(
299 "POST",
300 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
301 Effect.gen(function* () {
302 const request = yield* HttpServerRequest.HttpServerRequest;
303 const url = HttpServerRequest.toURL(request);
304 if (Option.isNone(url)) {
305 return HttpServerResponse.text("Bad Request", { status: 400 });
306 }
307​
308 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
309 if (!token) {
310 return HttpServerResponse.text("Not Found", { status: 404 });
311 }
312 const claims = yield* validateAttachmentUploadToken(token);
313 if (!claims) {
314 return HttpServerResponse.text("Not Found", { status: 404 });
315 }
316​
317 const contentLengthHeader = request.headers["content-length"];
318 if (
319 contentLengthHeader !== undefined &&
320 (!Number.isInteger(Number(contentLengthHeader)) ||
321 Number(contentLengthHeader) !== claims.sizeBytes)
322 ) {
323 return HttpServerResponse.text("Content-Length must match the upload size.", {
324 status: 400,
325 });
326 }
327​
328 // Keep the request stream in the route scope until the response is sent.
329 const bodyPull = yield* Stream.toPull(request.stream);
330 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
331 return stored.ok
332 ? HttpServerResponse.empty({ status: 204 })
333 : HttpServerResponse.text(stored.detail, { status: stored.status });
334 }),
335);
336​
337export const staticAndDevRouteLayer = HttpRouter.add(
338 "GET",
339 "*",
340 Effect.gen(function* () {
341 const request = yield* HttpServerRequest.HttpServerRequest;
342 const url = HttpServerRequest.toURL(request);
343​
344 if (Option.isNone(url)) {
345 return HttpServerResponse.text("Bad Request", { status: 400 });
346 }
347​
348 const config = yield* ServerConfig.ServerConfig;
349 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
350 return HttpServerResponse.text("Not Found", { status: 404 });
351 }
352​
353 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
354 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
355 status: 302,
356 });
357 }
358​
359 const staticDir =
360 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
361 if (!staticDir) {
362 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
363 status: 503,
364 });
365 }
366​
367 const fileSystem = yield* FileSystem.FileSystem;
368 const path = yield* Path.Path;
369 const staticRoot = path.resolve(staticDir);
370 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
371 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
372 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
373 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
374 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
375 if (
376 staticRelativePath.length === 0 ||
377 hasRawLeadingParentSegment ||
378 hasPathTraversalSegment ||
379 staticRelativePath.includes("\0")
380 ) {
381 return HttpServerResponse.text("Invalid static file path", { status: 400 });
382 }
383​
384 const isWithinStaticRoot = (candidate: string) =>
385 candidate === staticRoot ||
386 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
387​
388 let filePath = path.resolve(staticRoot, staticRelativePath);
389 if (!isWithinStaticRoot(filePath)) {
390 return HttpServerResponse.text("Invalid static file path", { status: 400 });
391 }
392​
393 const ext = path.extname(filePath);
394 if (!ext) {
395 filePath = path.resolve(filePath, "index.html");
396 if (!isWithinStaticRoot(filePath)) {
397 return HttpServerResponse.text("Invalid static file path", { status: 400 });
398 }
399 }
400​
401 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
402 if (!fileInfo || fileInfo.type !== "File") {
403 const indexPath = path.resolve(staticRoot, "index.html");
404 const indexData = yield* fileSystem
405 .readFile(indexPath)
406 .pipe(Effect.orElseSucceed(() => null));
407 if (!indexData) {
408 return HttpServerResponse.text("Not Found", { status: 404 });
409 }
410 return HttpServerResponse.uint8Array(indexData, {
411 status: 200,
412 contentType: "text/html; charset=utf-8",
413 });
414 }
415​
416 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
417 const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
418 if (!data) {
419 return HttpServerResponse.text("Internal Server Error", { status: 500 });
420 }
421​
422 return HttpServerResponse.uint8Array(data, {
423 status: 200,
424 contentType,
425 });
426 }),
427);