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