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 { cast } from "effect/Function";
16import {
17 HttpBody,
18 HttpClient,
19 HttpClientResponse,
20 HttpMiddleware,
21 HttpRouter,
22 HttpServerResponse,
23 HttpServerRequest,
24 HttpServerRespondable,
25} from "effect/unstable/http";
26import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
27import { OtlpTracer } from "effect/unstable/observability";
28
29import * as ServerConfig from "./config.ts";
30import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
31import {
32 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
33 storeAttachmentUpload,
34 validateAttachmentUploadToken,
35} from "./assets/AttachmentUpload.ts";
36import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
37import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
38import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
39import {
40 annotateEnvironmentRequest,
41 failEnvironmentScopeRequired,
42 failEnvironmentAuthInvalid,
43 failEnvironmentInternal,
44} from "./auth/http.ts";
45import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
46import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
47
48const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
49const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
50const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
51const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
52
53export function assetResponseHeaders(filePath: string): Record<string, string> {
54 const lowerPath = filePath.toLowerCase();
55 return {
56 "Cache-Control": "private, max-age=3600",
57 "X-Content-Type-Options": "nosniff",
58 ...(lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
59 ? { "Content-Type": "text/html; charset=utf-8" }
60 : {}),
61 ...(lowerPath.endsWith(".svg")
62 ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
63 : {}),
64 };
65}
66
67export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
68 global: true,
69});
70
71export const browserApiCorsLayer = Layer.unwrap(
72 Effect.gen(function* () {
73 const config = yield* ServerConfig.ServerConfig;
74 const devOrigin = config.devUrl?.origin;
75 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
76 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
77 //
78 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
79 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
80 // through Vite and is same-origin (no preflight at all), so this is a
81 // safety net for the desktop renderer and any direct-to-backend caller.
82 return HttpRouter.cors({
83 ...(devOrigin
84 ? {
85 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
86 credentials: true,
87 }
88 : {}),
89 allowedMethods: browserApiCorsAllowedMethods,
90 allowedHeaders: browserApiCorsAllowedHeaders,
91 maxAge: 600,
92 });
93 }),
94);
95
96export function isLoopbackHostname(hostname: string): boolean {
97 const normalizedHostname = hostname
98 .trim()
99 .toLowerCase()
100 .replace(/^\[(.*)\]$/, "$1");
101 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
102}
103
104export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
105 const redirectUrl = new URL(devUrl.toString());
106 redirectUrl.pathname = requestUrl.pathname;
107 redirectUrl.search = requestUrl.search;
108 redirectUrl.hash = requestUrl.hash;
109 return redirectUrl.toString();
110}
111
112const authenticateRawRouteWithScope = (
113 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
114) =>
115 Effect.gen(function* () {
116 const request = yield* HttpServerRequest.HttpServerRequest;
117 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
118 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
119 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
120 failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
121 ),
122 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
123 failEnvironmentInternal("internal_error", error),
124 ),
125 );
126 if (!session.scopes.includes(scope)) {
127 return yield* failEnvironmentScopeRequired(scope);
128 }
129 });
130
131export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
132 EnvironmentHttpApi,
133 "metadata",
134 Effect.fnUntraced(function* (handlers) {
135 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
136 return handlers.handle(
137 "descriptor",
138 Effect.fn("environment.metadata.descriptor")(function* (args) {
139 yield* annotateEnvironmentRequest(args.endpoint.name);
140 return yield* serverEnvironment.getDescriptor;
141 }, traceRelayRequest),
142 );
143 }),
144);
145
146class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
147 readonly cause: unknown;
148 readonly bodyJson: OtlpTracer.TraceData;
149}> {}
150
151export const otlpTracesProxyRouteLayer = HttpRouter.add(
152 "POST",
153 OTLP_TRACES_PROXY_PATH,
154 Effect.gen(function* () {
155 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
156 const request = yield* HttpServerRequest.HttpServerRequest;
157 const config = yield* ServerConfig.ServerConfig;
158 const otlpTracesUrl = config.otlpTracesUrl;
159 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
160 const httpClient = yield* HttpClient.HttpClient;
161 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
162
163 yield* Effect.try({
164 try: () => decodeOtlpTraceRecords(bodyJson),
165 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
166 }).pipe(
167 Effect.flatMap((records) => browserTraceCollector.record(records)),
168 Effect.catch((cause) =>
169 Effect.logWarning("Failed to decode browser OTLP traces", {
170 cause,
171 bodyJson,
172 }),
173 ),
174 );
175
176 if (otlpTracesUrl === undefined) {
177 return HttpServerResponse.empty({ status: 204 });
178 }
179
180 return yield* httpClient
181 .post(otlpTracesUrl, {
182 body: HttpBody.jsonUnsafe(bodyJson),
183 })
184 .pipe(
185 Effect.flatMap(HttpClientResponse.filterStatusOk),
186 Effect.as(HttpServerResponse.empty({ status: 204 })),
187 Effect.tapError((cause) =>
188 Effect.logWarning("Failed to export browser OTLP traces", {
189 cause,
190 otlpTracesUrl,
191 }),
192 ),
193 Effect.orElseSucceed(() =>
194 HttpServerResponse.text("Trace export failed.", { status: 502 }),
195 ),
196 );
197 }).pipe(
198 Effect.catchTags({
199 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
200 EnvironmentInternalError: HttpServerRespondable.toResponse,
201 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
202 }),
203 ),
204);
205
206export const assetRouteLayer = HttpRouter.add(
207 "GET",
208 `${ASSET_ROUTE_PREFIX}/*`,
209 Effect.gen(function* () {
210 const request = yield* HttpServerRequest.HttpServerRequest;
211 const url = HttpServerRequest.toURL(request);
212 if (Option.isNone(url)) {
213 return HttpServerResponse.text("Bad Request", { status: 400 });
214 }
215
216 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
217 const separatorIndex = suffix.indexOf("/");
218 if (separatorIndex <= 0) {
219 return HttpServerResponse.text("Not Found", { status: 404 });
220 }
221
222 const asset = yield* resolveAsset(
223 suffix.slice(0, separatorIndex),
224 suffix.slice(separatorIndex + 1),
225 );
226 if (!asset) {
227 return HttpServerResponse.text("Not Found", { status: 404 });
228 }
229 return yield* HttpServerResponse.file(asset.path, {
230 status: 200,
231 headers: assetResponseHeaders(asset.path),
232 }).pipe(
233 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
234 );
235 }),
236);
237
238export const attachmentUploadRouteLayer = HttpRouter.add(
239 "POST",
240 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
241 Effect.gen(function* () {
242 const request = yield* HttpServerRequest.HttpServerRequest;
243 const url = HttpServerRequest.toURL(request);
244 if (Option.isNone(url)) {
245 return HttpServerResponse.text("Bad Request", { status: 400 });
246 }
247
248 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
249 if (!token) {
250 return HttpServerResponse.text("Not Found", { status: 404 });
251 }
252 const claims = yield* validateAttachmentUploadToken(token);
253 if (!claims) {
254 return HttpServerResponse.text("Not Found", { status: 404 });
255 }
256
257 const contentLengthHeader = request.headers["content-length"];
258 if (
259 contentLengthHeader !== undefined &&
260 (!Number.isInteger(Number(contentLengthHeader)) ||
261 Number(contentLengthHeader) !== claims.sizeBytes)
262 ) {
263 return HttpServerResponse.text("Content-Length must match the upload size.", {
264 status: 400,
265 });
266 }
267
268 const body = yield* request.arrayBuffer.pipe(
269 Effect.provideService(HttpServerRequest.MaxBodySize, FileSystem.Size(claims.sizeBytes)),
270 Effect.orElseSucceed(() => null),
271 );
272 if (body === null) {
273 return HttpServerResponse.text("Failed to read the upload body.", { status: 400 });
274 }
275
276 const stored = yield* storeAttachmentUpload(claims, new Uint8Array(body));
277 return stored.ok
278 ? HttpServerResponse.empty({ status: 204 })
279 : HttpServerResponse.text(stored.detail, { status: stored.status });
280 }),
281);
282
283export const staticAndDevRouteLayer = HttpRouter.add(
284 "GET",
285 "*",
286 Effect.gen(function* () {
287 const request = yield* HttpServerRequest.HttpServerRequest;
288 const url = HttpServerRequest.toURL(request);
289
290 if (Option.isNone(url)) {
291 return HttpServerResponse.text("Bad Request", { status: 400 });
292 }
293
294 const config = yield* ServerConfig.ServerConfig;
295 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
296 return HttpServerResponse.text("Not Found", { status: 404 });
297 }
298
299 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
300 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
301 status: 302,
302 });
303 }
304
305 const staticDir =
306 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
307 if (!staticDir) {
308 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
309 status: 503,
310 });
311 }
312
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const staticRoot = path.resolve(staticDir);
316 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
317 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
318 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
319 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
320 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
321 if (
322 staticRelativePath.length === 0 ||
323 hasRawLeadingParentSegment ||
324 hasPathTraversalSegment ||
325 staticRelativePath.includes("\0")
326 ) {
327 return HttpServerResponse.text("Invalid static file path", { status: 400 });
328 }
329
330 const isWithinStaticRoot = (candidate: string) =>
331 candidate === staticRoot ||
332 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
333
334 let filePath = path.resolve(staticRoot, staticRelativePath);
335 if (!isWithinStaticRoot(filePath)) {
336 return HttpServerResponse.text("Invalid static file path", { status: 400 });
337 }
338
339 const ext = path.extname(filePath);
340 if (!ext) {
341 filePath = path.resolve(filePath, "index.html");
342 if (!isWithinStaticRoot(filePath)) {
343 return HttpServerResponse.text("Invalid static file path", { status: 400 });
344 }
345 }
346
347 const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
348 if (!fileInfo || fileInfo.type !== "File") {
349 const indexPath = path.resolve(staticRoot, "index.html");
350 const indexData = yield* fileSystem
351 .readFile(indexPath)
352 .pipe(Effect.orElseSucceed(() => null));
353 if (!indexData) {
354 return HttpServerResponse.text("Not Found", { status: 404 });
355 }
356 return HttpServerResponse.uint8Array(indexData, {
357 status: 200,
358 contentType: "text/html; charset=utf-8",
359 });
360 }
361
362 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
363 const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
364 if (!data) {
365 return HttpServerResponse.text("Internal Server Error", { status: 500 });
366 }
367
368 return HttpServerResponse.uint8Array(data, {
369 status: 200,
370 contentType,
371 });
372 }),
373);