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