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

http.ts

197 lines7.0 KB

1import Mime from "@effect/platform-node/Mime";
2import { Effect, FileSystem, Option, Path } from "effect";
3import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
4​
5import {
6 ATTACHMENTS_ROUTE_PREFIX,
7 normalizeAttachmentRelativePath,
8 resolveAttachmentRelativePath,
9} from "./attachmentPaths";
10import { resolveAttachmentPathById } from "./attachmentStore";
11import { ServerConfig } from "./config";
12import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
13​
14const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
15const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
16​
17export const attachmentsRouteLayer = HttpRouter.add(
18 "GET",
19 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
20 Effect.gen(function* () {
21 const request = yield* HttpServerRequest.HttpServerRequest;
22 const url = HttpServerRequest.toURL(request);
23 if (Option.isNone(url)) {
24 return HttpServerResponse.text("Bad Request", { status: 400 });
25 }
26​
27 const config = yield* ServerConfig;
28 const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
29 const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
30 if (!normalizedRelativePath) {
31 return HttpServerResponse.text("Invalid attachment path", { status: 400 });
32 }
33​
34 const isIdLookup =
35 !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
36 const filePath = isIdLookup
37 ? resolveAttachmentPathById({
38 attachmentsDir: config.attachmentsDir,
39 attachmentId: normalizedRelativePath,
40 })
41 : resolveAttachmentRelativePath({
42 attachmentsDir: config.attachmentsDir,
43 relativePath: normalizedRelativePath,
44 });
45 if (!filePath) {
46 return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
47 status: isIdLookup ? 404 : 400,
48 });
49 }
50​
51 const fileSystem = yield* FileSystem.FileSystem;
52 const fileInfo = yield* fileSystem
53 .stat(filePath)
54 .pipe(Effect.catch(() => Effect.succeed(null)));
55 if (!fileInfo || fileInfo.type !== "File") {
56 return HttpServerResponse.text("Not Found", { status: 404 });
57 }
58​
59 return yield* HttpServerResponse.file(filePath, {
60 status: 200,
61 headers: {
62 "Cache-Control": "public, max-age=31536000, immutable",
63 },
64 }).pipe(
65 Effect.catch(() =>
66 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
67 ),
68 );
69 }),
70);
71​
72export const projectFaviconRouteLayer = HttpRouter.add(
73 "GET",
74 "/api/project-favicon",
75 Effect.gen(function* () {
76 const request = yield* HttpServerRequest.HttpServerRequest;
77 const url = HttpServerRequest.toURL(request);
78 if (Option.isNone(url)) {
79 return HttpServerResponse.text("Bad Request", { status: 400 });
80 }
81​
82 const projectCwd = url.value.searchParams.get("cwd");
83 if (!projectCwd) {
84 return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
85 }
86​
87 const faviconResolver = yield* ProjectFaviconResolver;
88 const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
89 if (!faviconFilePath) {
90 return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
91 status: 200,
92 contentType: "image/svg+xml",
93 headers: {
94 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
95 },
96 });
97 }
98​
99 return yield* HttpServerResponse.file(faviconFilePath, {
100 status: 200,
101 headers: {
102 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
103 },
104 }).pipe(
105 Effect.catch(() =>
106 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
107 ),
108 );
109 }),
110);
111​
112export const staticAndDevRouteLayer = HttpRouter.add(
113 "GET",
114 "*",
115 Effect.gen(function* () {
116 const request = yield* HttpServerRequest.HttpServerRequest;
117 const url = HttpServerRequest.toURL(request);
118 if (Option.isNone(url)) {
119 return HttpServerResponse.text("Bad Request", { status: 400 });
120 }
121​
122 const config = yield* ServerConfig;
123 if (config.devUrl) {
124 return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
125 }
126​
127 if (!config.staticDir) {
128 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
129 status: 503,
130 });
131 }
132​
133 const fileSystem = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const staticRoot = path.resolve(config.staticDir);
136 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
137 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
138 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
139 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
140 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
141 if (
142 staticRelativePath.length === 0 ||
143 hasRawLeadingParentSegment ||
144 hasPathTraversalSegment ||
145 staticRelativePath.includes("\0")
146 ) {
147 return HttpServerResponse.text("Invalid static file path", { status: 400 });
148 }
149​
150 const isWithinStaticRoot = (candidate: string) =>
151 candidate === staticRoot ||
152 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
153​
154 let filePath = path.resolve(staticRoot, staticRelativePath);
155 if (!isWithinStaticRoot(filePath)) {
156 return HttpServerResponse.text("Invalid static file path", { status: 400 });
157 }
158​
159 const ext = path.extname(filePath);
160 if (!ext) {
161 filePath = path.resolve(filePath, "index.html");
162 if (!isWithinStaticRoot(filePath)) {
163 return HttpServerResponse.text("Invalid static file path", { status: 400 });
164 }
165 }
166​
167 const fileInfo = yield* fileSystem
168 .stat(filePath)
169 .pipe(Effect.catch(() => Effect.succeed(null)));
170 if (!fileInfo || fileInfo.type !== "File") {
171 const indexPath = path.resolve(staticRoot, "index.html");
172 const indexData = yield* fileSystem
173 .readFile(indexPath)
174 .pipe(Effect.catch(() => Effect.succeed(null)));
175 if (!indexData) {
176 return HttpServerResponse.text("Not Found", { status: 404 });
177 }
178 return HttpServerResponse.uint8Array(indexData, {
179 status: 200,
180 contentType: "text/html; charset=utf-8",
181 });
182 }
183​
184 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
185 const data = yield* fileSystem
186 .readFile(filePath)
187 .pipe(Effect.catch(() => Effect.succeed(null)));
188 if (!data) {
189 return HttpServerResponse.text("Internal Server Error", { status: 500 });
190 }
191​
192 return HttpServerResponse.uint8Array(data, {
193 status: 200,
194 contentType,
195 });
196 }),
197);