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

http.ts

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