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