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

http.ts

308 lines10.7 KB

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