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());
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 }`;
78}
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 };
108}
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);
145}
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();
153}
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(EnvironmentAuth.serverAuthCredentialReason(error)),
164 ),
165 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
166 failEnvironmentInternal("internal_error", error),
167 ),
168 );
169 if (!session.scopes.includes(scope)) {
170 return yield* failEnvironmentScopeRequired(scope);
171 }
172 });
173
174export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
175 EnvironmentHttpApi,
176 "metadata",
177 Effect.fnUntraced(function* (handlers) {
178 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
179 return handlers.handle(
180 "descriptor",
181 Effect.fn("environment.metadata.descriptor")(function* (args) {
182 yield* annotateEnvironmentRequest(args.endpoint.name);
183 return yield* serverEnvironment.getDescriptor;
184 }, traceRelayRequest),
185 );
186 }),
187);
188
189class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
190 readonly cause: unknown;
191 readonly bodyJson: OtlpTracer.TraceData;
192}> {}
193
194export const otlpTracesProxyRouteLayer = HttpRouter.add(
195 "POST",
196 OTLP_TRACES_PROXY_PATH,
197 Effect.gen(function* () {
198 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
199 const request = yield* HttpServerRequest.HttpServerRequest;
200 const config = yield* ServerConfig.ServerConfig;
201 const otlpTracesUrl = config.otlpTracesUrl;
202 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
203 const httpClient = yield* HttpClient.HttpClient;
204 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
205
206 yield* Effect.try({
207 try: () => decodeOtlpTraceRecords(bodyJson),
208 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
209 }).pipe(
210 Effect.flatMap((records) => browserTraceCollector.record(records)),
211 Effect.catch((cause) =>
212 Effect.logWarning("Failed to decode browser OTLP traces", {
213 cause,
214 bodyJson,
215 }),
216 ),
217 );
218
219 if (otlpTracesUrl === undefined) {
220 return HttpServerResponse.empty({ status: 204 });
221 }
222
223 return yield* httpClient
224 .post(otlpTracesUrl, {
225 body: HttpBody.jsonUnsafe(bodyJson),
226 })
227 .pipe(
228 Effect.flatMap(HttpClientResponse.filterStatusOk),
229 Effect.as(HttpServerResponse.empty({ status: 204 })),
230 Effect.tapError((cause) =>
231 Effect.logWarning("Failed to export browser OTLP traces", {
232 cause,
233 otlpTracesUrl,
234 }),
235 ),
236 Effect.orElseSucceed(() =>
237 HttpServerResponse.text("Trace export failed.", { status: 502 }),
238 ),
239 );
240 }).pipe(
241 Effect.catchTags({
242 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
243 EnvironmentInternalError: HttpServerRespondable.toResponse,
244 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
245 }),
246 ),
247);
248
249export const assetRouteLayer = HttpRouter.add(
250 "GET",
251 `${ASSET_ROUTE_PREFIX}/*`,
252 Effect.gen(function* () {
253 const request = yield* HttpServerRequest.HttpServerRequest;
254 const url = HttpServerRequest.toURL(request);
255 if (Option.isNone(url)) {
256 return HttpServerResponse.text("Bad Request", { status: 400 });
257 }
258
259 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
260 const separatorIndex = suffix.indexOf("/");
261 if (separatorIndex <= 0) {
262 return HttpServerResponse.text("Not Found", { status: 404 });
263 }
264
265 const asset = yield* resolveAsset(
266 suffix.slice(0, separatorIndex),
267 suffix.slice(separatorIndex + 1),
268 );
269 if (!asset) {
270 return HttpServerResponse.text("Not Found", { status: 404 });
271 }
272 return yield* HttpServerResponse.file(asset.path, {
273 status: 200,
274 headers: assetResponseHeaders(
275 asset.path,
276 asset.download
277 ? {
278 download: true,
279 ...(asset.fileName !== undefined ? { fileName: asset.fileName } : {}),
280 ...(asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {}),
281 }
282 : undefined,
283 ),
284 }).pipe(
285 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
286 );
287 }),
288);
289
290export const attachmentUploadRouteLayer = HttpRouter.add(
291 "POST",
292 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
293 Effect.gen(function* () {
294 const request = yield* HttpServerRequest.HttpServerRequest;
295 const url = HttpServerRequest.toURL(request);
296 if (Option.isNone(url)) {
297 return HttpServerResponse.text("Bad Request", { status: 400 });
298 }
299
300 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
301 if (!token) {
302 return HttpServerResponse.text("Not Found", { status: 404 });
303 }
304 const claims = yield* validateAttachmentUploadToken(token);
305 if (!claims) {
306 return HttpServerResponse.text("Not Found", { status: 404 });
307 }
308
309 const contentLengthHeader = request.headers["content-length"];
310 if (
311 contentLengthHeader !== undefined &&
312 (!Number.isInteger(Number(contentLengthHeader)) ||
313 Number(contentLengthHeader) !== claims.sizeBytes)
314 ) {
315 return HttpServerResponse.text("Content-Length must match the upload size.", {
316 status: 400,
317 });
318 }
319
320 // Keep the request stream in the route scope until the response is sent.
321 const bodyPull = yield* Stream.toPull(request.stream);
322 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
323 return stored.ok
324 ? HttpServerResponse.empty({ status: 204 })
325 : HttpServerResponse.text(stored.detail, { status: stored.status });
326 }),
327);
328
329export const staticAndDevRouteLayer = HttpRouter.add(
330 "GET",
331 "*",
332 Effect.gen(function* () {
333 const request = yield* HttpServerRequest.HttpServerRequest;
334 const url = HttpServerRequest.toURL(request);
335
336 if (Option.isNone(url)) {
337 return HttpServerResponse.text("Bad Request", { status: 400 });
338 }
339
340 const config = yield* ServerConfig.ServerConfig;
341 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
342 return HttpServerResponse.text("Not Found", { status: 404 });
343 }
344
345 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
346 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
347 status: 302,
348 });
349 }
350
351 const staticDir =
352 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
353 if (!staticDir) {
354 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
355 status: 503,
356 });
357 }
358
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 const staticRoot = path.resolve(staticDir);
362 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
363 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
364 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
365 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
366 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
367 if (
368 staticRelativePath.length === 0 ||
369 hasRawLeadingParentSegment ||
370 hasPathTraversalSegment ||
371 staticRelativePath.includes("\0")
372 ) {
373 return HttpServerResponse.text("Invalid static file path", { status: 400 });
374 }
375
376 const isWithinStaticRoot = (candidate: string) =>
377 candidate === staticRoot ||
378 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
379
380 let filePath = path.resolve(staticRoot, staticRelativePath);
381 if (!isWithinStaticRoot(filePath)) {
382 return HttpServerResponse.text("Invalid static file path", { status: 400 });
383 }
384
385 const ext = path.extname(filePath);
386 if (!ext) {
387 filePath = path.resolve(filePath, "index.html");
388 if (!isWithinStaticRoot(filePath)) {
389 return HttpServerResponse.text("Invalid static file path", { status: 400 });
390 }
391 }
392
393 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
394 if (!fileInfo || fileInfo.type !== "File") {
395 const indexPath = path.resolve(staticRoot, "index.html");
396 const indexData = yield* fileSystem
397 .readFile(indexPath)
398 .pipe(Effect.orElseSucceed(() => null));
399 if (!indexData) {
400 return HttpServerResponse.text("Not Found", { status: 404 });
401 }
402 return HttpServerResponse.uint8Array(indexData, {
403 status: 200,
404 contentType: "text/html; charset=utf-8",
405 });
406 }
407
408 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
409 const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
410 if (!data) {
411 return HttpServerResponse.text("Internal Server Error", { status: 500 });
412 }
413
414 return HttpServerResponse.uint8Array(data, {
415 status: 200,
416 contentType,
417 });
418 }),
419);