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