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

http.ts

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