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