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