Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

310 lines11.0 KB

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