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

http.ts

531 lines20.0 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 { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
33import {
34 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
35 storeAttachmentUpload,
36 validateAttachmentUploadToken,
37} from "./assets/AttachmentUpload.ts";
38import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
39import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
40import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
41import {
42 annotateEnvironmentRequest,
43 failEnvironmentScopeRequired,
44 failEnvironmentAuthInvalid,
45 failEnvironmentInternal,
46} from "./auth/http.ts";
47import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
48import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
49​
50const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
51const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
52const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
53const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
54// HTML previews are agent output, not the app. The sandbox gives the document an
55// opaque origin: scripts run, but same-origin cookies, storage, and API calls are
56// out of reach. Relative sibling assets still load through their signed URLs.
57const HTML_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-modals";
58​
59// Types a browser may render as a document if a proxy strips the disposition
60// header. Downloads of these fall back to octet-stream.
61const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
62const isSafeDownloadMimeType = (mimeType: string): boolean =>
63 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
64 !/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
65const isSafeInlineVideoMimeType = (mimeType: string): boolean =>
66 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");
67const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
68 mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
69​
70/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
71export function downloadContentDisposition(fileName?: string): string {
72 if (fileName === undefined) {
73 return "attachment";
74 }
75 // toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
76 // eslint-disable-next-line no-control-regex -- Header filenames must strip ASCII controls.
77 const sanitized = fileName.toWellFormed().replace(/[\u0000-\u001f"\\]/g, "_");
78 const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
79 const needsExtended = asciiFallback !== sanitized;
80 const extendedName = encodeURIComponent(sanitized).replace(
81 /['()*]/g,
82 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
83 );
84 return `attachment; filename="${asciiFallback}"${
85 needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
86 }`;
88​
89export function assetResponseHeaders(
90 filePath: string,
91 options?: {
92 readonly download?: boolean;
93 readonly fileName?: string;
94 readonly mimeType?: string;
95 },
96): Record<string, string> {
97 const lowerPath = filePath.toLowerCase();
98 const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
99 return {
100 "Cache-Control": "private, max-age=3600",
101 "X-Content-Type-Options": "nosniff",
102 ...(options?.download
103 ? {
104 "Content-Disposition": downloadContentDisposition(options.fileName),
105 "Content-Security-Policy": "default-src 'none'; sandbox",
106 "Content-Type":
107 options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
108 ? options.mimeType
109 : "application/octet-stream",
110 }
111 : inlineMimeType !== undefined && isSafeInlineVideoMimeType(inlineMimeType)
112 ? { "Content-Type": inlineMimeType }
113 : inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)
114 ? {
115 "Content-Type":
116 inlineMimeType.toLowerCase() === "text/html"
117 ? "text/html; charset=utf-8"
118 : "application/pdf",
119 ...(inlineMimeType.toLowerCase() === "text/html"
120 ? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
121 : {}),
122 }
123 : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
124 ? {
125 "Content-Type": "text/html; charset=utf-8",
126 "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
127 }
128 : {}),
129 ...(!options?.download && lowerPath.endsWith(".svg")
130 ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
131 : {}),
132 };
134​
135/** A single byte range for native video readers; unsupported range syntax uses the full file. */
136function assetByteRange(header: string, size: bigint) {
137 const match = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
138 if (!match || (!match[1] && !match[2])) return null;
139 const first = match[1] ? BigInt(match[1]) : null;
140 const last = match[2] ? BigInt(match[2]) : null;
141 if (first !== null && last !== null && last < first) return null;
142 if (size === 0n || (first !== null && first >= size) || (first === null && last === 0n)) {
143 return { _tag: "Unsatisfiable" as const };
144 }
145 const start = first ?? (last! >= size ? 0n : size - last!);
146 const end = first === null || last === null || last >= size ? size - 1n : last;
147 if (!Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end))) {
148 return { _tag: "Unsatisfiable" as const };
149 }
150 return {
151 _tag: "Range" as const,
152 offset: start,
153 bytesToRead: end - start + 1n,
154 contentRange: `bytes ${start}-${end}/${size}`,
155 };
157​
158export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
159 asset: {
160 readonly path: string;
161 readonly download?: boolean;
162 readonly fileName?: string;
163 readonly mimeType?: string;
164 readonly file?: OpenMediaFile;
165 },
166 rangeHeader?: string,
167 ifRangeHeader?: string,
168 method: "GET" | "HEAD" = "GET",
169) {
170 const headers = assetResponseHeaders(asset.path, asset);
171 const mediaFile = asset.file;
172 const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
173 const isVideo = headers["Content-Type"]?.toLowerCase().startsWith("video/") === true;
174 if (mediaFile && isVideo) {
175 // Host videos can change in place. Do not invite conditional range requests
176 // with validators that cannot establish byte-for-byte identity.
177 headers["Cache-Control"] = "private, no-store";
178 }
179 let status = 200;
180 let offset = 0n;
181 let bytesToRead: bigint | undefined;
182 if (isVideo) {
183 headers["Accept-Ranges"] = "bytes";
184 // If-Range requires a matching validator. A full response is safe when we cannot validate it.
185 if (method === "GET" && rangeHeader && ifRangeHeader === undefined) {
186 const fs = yield* FileSystem.FileSystem;
187 const info = mediaInfo ?? (yield* fs.stat(asset.path));
188 const range = assetByteRange(rangeHeader, info.size);
189 if (range?._tag === "Unsatisfiable") {
190 return HttpServerResponse.empty({
191 status: 416,
192 headers: { ...headers, "Content-Range": `bytes */${info.size}` },
193 });
194 }
195 if (range?._tag === "Range") {
196 status = 206;
197 offset = range.offset;
198 bytesToRead = range.bytesToRead;
199 headers["Content-Range"] = range.contentRange;
200 }
201 }
202 }
203 if (mediaFile && mediaInfo) {
204 const size = bytesToRead ?? mediaInfo.size;
205 headers["Content-Type"] ??= Mime.getType(asset.path) ?? "application/octet-stream";
206 headers["Content-Length"] = String(size);
207 if (!isVideo) {
208 headers["Last-Modified"] = mediaInfo.mtime.toUTCString();
209 headers.ETag = `W/"${mediaInfo.size.toString(16)}-${mediaInfo.mtimeMs.toString(16)}"`;
210 }
211 if (method === "HEAD" || size === 0n) {
212 return HttpServerResponse.empty({ status, headers });
213 }
214 const body = streamMediaFile(mediaFile, offset, size);
215 if (!body) {
216 return HttpServerResponse.text("File is too large to preview.", { status: 413 });
217 }
218 return HttpServerResponse.stream(body, {
219 status,
220 headers,
221 });
222 }
223 return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers });
224});
225​
226export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
227 global: true,
228});
229​
230export const browserApiCorsLayer = Layer.unwrap(
231 Effect.gen(function* () {
232 const config = yield* ServerConfig.ServerConfig;
233 const devOrigin = config.devUrl?.origin;
234 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
235 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
236 //
237 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
238 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
239 // through Vite and is same-origin (no preflight at all), so this is a
240 // safety net for the desktop renderer and any direct-to-backend caller.
241 return HttpRouter.cors({
242 ...(devOrigin
243 ? {
244 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
245 credentials: true,
246 }
247 : {}),
248 allowedMethods: browserApiCorsAllowedMethods,
249 allowedHeaders: browserApiCorsAllowedHeaders,
250 maxAge: 600,
251 });
252 }),
253);
254​
255export function isLoopbackHostname(hostname: string): boolean {
256 const normalizedHostname = hostname
257 .trim()
258 .toLowerCase()
259 .replace(/^\[(.*)\]$/, "$1");
260 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
262​
263export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
264 const redirectUrl = new URL(devUrl.toString());
265 redirectUrl.pathname = requestUrl.pathname;
266 redirectUrl.search = requestUrl.search;
267 redirectUrl.hash = requestUrl.hash;
268 return redirectUrl.toString();
270​
271const authenticateRawRouteWithScope = (
272 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
273) =>
274 Effect.gen(function* () {
275 const request = yield* HttpServerRequest.HttpServerRequest;
276 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
277 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
278 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
279 failEnvironmentAuthInvalid(
280 EnvironmentAuth.serverAuthCredentialReason(error),
281 EnvironmentAuth.serverAuthDpopFailureReason(error),
282 ),
283 ),
284 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
285 failEnvironmentInternal("internal_error", error),
286 ),
287 );
288 if (!session.scopes.includes(scope)) {
289 return yield* failEnvironmentScopeRequired(scope);
290 }
291 });
292​
293export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
294 EnvironmentHttpApi,
295 "metadata",
296 Effect.fnUntraced(function* (handlers) {
297 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
298 return handlers.handle(
299 "descriptor",
300 Effect.fn("environment.metadata.descriptor")(function* (args) {
301 yield* annotateEnvironmentRequest(args.endpoint.name);
302 return yield* serverEnvironment.getDescriptor;
303 }, traceRelayRequest),
304 );
305 }),
306);
307​
308class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
309 readonly cause: unknown;
310 readonly bodyJson: OtlpTracer.TraceData;
311}> {}
312​
313export const otlpTracesProxyRouteLayer = HttpRouter.add(
314 "POST",
315 OTLP_TRACES_PROXY_PATH,
316 Effect.gen(function* () {
317 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
318 const request = yield* HttpServerRequest.HttpServerRequest;
319 const config = yield* ServerConfig.ServerConfig;
320 const otlpTracesUrl = config.otlpTracesUrl;
321 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
322 const httpClient = yield* HttpClient.HttpClient;
323 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
324​
325 yield* Effect.try({
326 try: () => decodeOtlpTraceRecords(bodyJson),
327 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
328 }).pipe(
329 Effect.flatMap((records) => browserTraceCollector.record(records)),
330 Effect.catch((cause) =>
331 Effect.logWarning("Failed to decode browser OTLP traces", {
332 cause,
333 bodyJson,
334 }),
335 ),
336 );
337​
338 if (otlpTracesUrl === undefined) {
339 return HttpServerResponse.empty({ status: 204 });
340 }
341​
342 return yield* httpClient
343 .post(otlpTracesUrl, {
344 body: HttpBody.jsonUnsafe(bodyJson),
345 })
346 .pipe(
347 Effect.flatMap(HttpClientResponse.filterStatusOk),
348 Effect.as(HttpServerResponse.empty({ status: 204 })),
349 Effect.tapError((cause) =>
350 Effect.logWarning("Failed to export browser OTLP traces", {
351 cause,
352 otlpTracesUrl,
353 }),
354 ),
355 Effect.orElseSucceed(() =>
356 HttpServerResponse.text("Trace export failed.", { status: 502 }),
357 ),
358 );
359 }).pipe(
360 Effect.catchTags({
361 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
362 EnvironmentInternalError: HttpServerRespondable.toResponse,
363 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
364 }),
365 ),
366);
367​
368export const assetRouteLayer = HttpRouter.add(
369 "GET",
370 `${ASSET_ROUTE_PREFIX}/*`,
371 Effect.gen(function* () {
372 const request = yield* HttpServerRequest.HttpServerRequest;
373 const url = HttpServerRequest.toURL(request);
374 if (Option.isNone(url)) {
375 return HttpServerResponse.text("Bad Request", { status: 400 });
376 }
377​
378 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
379 const separatorIndex = suffix.indexOf("/");
380 if (separatorIndex <= 0) {
381 return HttpServerResponse.text("Not Found", { status: 404 });
382 }
383​
384 const asset = yield* resolveAsset(
385 suffix.slice(0, separatorIndex),
386 suffix.slice(separatorIndex + 1),
387 );
388 if (!asset) {
389 return HttpServerResponse.text("Not Found", { status: 404 });
390 }
391 return yield* assetFileResponse(
392 asset,
393 request.method === "GET" ? request.headers.range : undefined,
394 request.headers["if-range"],
395 request.method === "HEAD" ? "HEAD" : "GET",
396 ).pipe(
397 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
398 );
399 }),
400);
401​
402export const attachmentUploadRouteLayer = HttpRouter.add(
403 "POST",
404 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
405 Effect.gen(function* () {
406 const request = yield* HttpServerRequest.HttpServerRequest;
407 const url = HttpServerRequest.toURL(request);
408 if (Option.isNone(url)) {
409 return HttpServerResponse.text("Bad Request", { status: 400 });
410 }
411​
412 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
413 if (!token) {
414 return HttpServerResponse.text("Not Found", { status: 404 });
415 }
416 const claims = yield* validateAttachmentUploadToken(token);
417 if (!claims) {
418 return HttpServerResponse.text("Not Found", { status: 404 });
419 }
420​
421 const contentLengthHeader = request.headers["content-length"];
422 if (
423 contentLengthHeader !== undefined &&
424 (!Number.isInteger(Number(contentLengthHeader)) ||
425 Number(contentLengthHeader) !== claims.sizeBytes)
426 ) {
427 return HttpServerResponse.text("Content-Length must match the upload size.", {
428 status: 400,
429 });
430 }
431​
432 // Keep the request stream in the route scope until the response is sent.
433 const bodyPull = yield* Stream.toPull(request.stream);
434 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
435 return stored.ok
436 ? HttpServerResponse.empty({ status: 204 })
437 : HttpServerResponse.text(stored.detail, { status: stored.status });
438 }),
439);
440​
441export const staticAndDevRouteLayer = HttpRouter.add(
442 "GET",
443 "*",
444 Effect.gen(function* () {
445 const request = yield* HttpServerRequest.HttpServerRequest;
446 const url = HttpServerRequest.toURL(request);
447​
448 if (Option.isNone(url)) {
449 return HttpServerResponse.text("Bad Request", { status: 400 });
450 }
451​
452 const config = yield* ServerConfig.ServerConfig;
453 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
454 return HttpServerResponse.text("Not Found", { status: 404 });
455 }
456​
457 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
458 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
459 status: 302,
460 });
461 }
462​
463 const staticDir =
464 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
465 if (!staticDir) {
466 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
467 status: 503,
468 });
469 }
470​
471 const fileSystem = yield* FileSystem.FileSystem;
472 const path = yield* Path.Path;
473 const staticRoot = path.resolve(staticDir);
474 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
475 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
476 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
477 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
478 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
479 if (
480 staticRelativePath.length === 0 ||
481 hasRawLeadingParentSegment ||
482 hasPathTraversalSegment ||
483 staticRelativePath.includes("\0")
484 ) {
485 return HttpServerResponse.text("Invalid static file path", { status: 400 });
486 }
487​
488 const isWithinStaticRoot = (candidate: string) =>
489 candidate === staticRoot ||
490 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
491​
492 let filePath = path.resolve(staticRoot, staticRelativePath);
493 if (!isWithinStaticRoot(filePath)) {
494 return HttpServerResponse.text("Invalid static file path", { status: 400 });
495 }
496​
497 const ext = path.extname(filePath);
498 if (!ext) {
499 filePath = path.resolve(filePath, "index.html");
500 if (!isWithinStaticRoot(filePath)) {
501 return HttpServerResponse.text("Invalid static file path", { status: 400 });
502 }
503 }
504​
505 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
506 if (!fileInfo || fileInfo.type !== "File") {
507 const indexPath = path.resolve(staticRoot, "index.html");
508 const indexData = yield* fileSystem
509 .readFile(indexPath)
510 .pipe(Effect.orElseSucceed(() => null));
511 if (!indexData) {
512 return HttpServerResponse.text("Not Found", { status: 404 });
513 }
514 return HttpServerResponse.uint8Array(indexData, {
515 status: 200,
516 contentType: "text/html; charset=utf-8",
517 });
518 }
519​
520 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
521 const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
522 if (!data) {
523 return HttpServerResponse.text("Internal Server Error", { status: 500 });
524 }
525​
526 return HttpServerResponse.uint8Array(data, {
527 status: 200,
528 contentType,
529 });
530 }),
531);