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

http.ts

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