Open History to see the last commit
1import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
2import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform"
3import * as NodePathLayer from "@effect/platform-node/NodePath"
4import { assert, describe, it } from "@effect/vitest"
5import * as Layer from "effect/Layer"
6import { HttpRouter, HttpStaticServer } from "effect/unstable/http"
7import { copyFile, cp, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"
8import { tmpdir } from "node:os"
9import * as NodePath from "node:path"
10import { fileURLToPath } from "node:url"
11
12const fixturesRoot = fileURLToPath(new URL("./fixtures/http-static-server", import.meta.url))
13const fixturesOutsideFile = fileURLToPath(new URL("./fixtures/http-static-server-outside.txt", import.meta.url))
14
15const staticFilesLayer = Layer.mergeAll(
16 NodePathLayer.layer,
17 NodeFileSystem.layer,
18 NodeHttpPlatform.layer
19)
20
21const makeHandler = (
22 root: string,
23 options: Omit<Parameters<typeof HttpStaticServer.make>[0], "root"> = {}
24) =>
25 HttpRouter.toWebHandler(
26 HttpStaticServer.layer({
27 root,
28 ...options
29 }).pipe(Layer.provideMerge(staticFilesLayer)),
30 { disableLogger: true }
31 )
32
33const withStaticFiles = async (
34 run: (context: {
35 readonly handler: (request: Request) => Promise<Response>
36 readonly root: string
37 readonly outsideFile: string
38 }) => Promise<void>,
39 options: Omit<Parameters<typeof HttpStaticServer.make>[0], "root"> = {}
40) => {
41 const temporaryRoot = await mkdtemp(NodePath.join(tmpdir(), "effect-http-static-server-"))
42 const root = NodePath.join(temporaryRoot, "root")
43 const outsideFile = NodePath.join(temporaryRoot, NodePath.basename(fixturesOutsideFile))
44
45 await Promise.all([
46 cp(fixturesRoot, root, { recursive: true }),
47 copyFile(fixturesOutsideFile, outsideFile)
48 ])
49
50 const { handler, dispose } = makeHandler(root, options)
51 try {
52 await run({ handler, root, outsideFile })
53 } finally {
54 await dispose()
55 await rm(temporaryRoot, { recursive: true, force: true })
56 }
57}
58
59describe("HttpStaticServer", () => {
60 it("serves files with expected content type and body", async () => {
61 await withStaticFiles(async ({ handler }) => {
62 const response = await handler(new Request("http://localhost/hello.txt"))
63 assert.strictEqual(response.status, 200)
64 assert.strictEqual(response.headers.get("content-type"), "text/plain; charset=utf-8")
65 assert.strictEqual((await response.text()).trimEnd(), "hello static file")
66 })
67 })
68
69 it("serves default index file for directory paths", async () => {
70 await withStaticFiles(async ({ handler }) => {
71 const response = await handler(new Request("http://localhost/guide"))
72 assert.strictEqual(response.status, 200)
73 assert.strictEqual(response.headers.get("content-type"), "text/html; charset=utf-8")
74 assert.strictEqual((await response.text()).trimEnd(), "<html><body>guide index</body></html>")
75 })
76 })
77
78 it("supports custom index file and disabled index fallback", async () => {
79 await withStaticFiles(async ({ handler }) => {
80 const response = await handler(new Request("http://localhost/custom"))
81 assert.strictEqual(response.status, 200)
82 assert.strictEqual((await response.text()).trimEnd(), "<html><body>custom home</body></html>")
83 }, { index: "home.html" })
84
85 await withStaticFiles(async ({ handler }) => {
86 const response = await handler(new Request("http://localhost/custom"))
87 assert.strictEqual(response.status, 404)
88 }, { index: undefined })
89 })
90
91 it("returns 304 for If-None-Match exact, weak, and wildcard", async () => {
92 await withStaticFiles(async ({ handler }) => {
93 const warmup = await handler(new Request("http://localhost/conditional.txt"))
94 const etag = warmup.headers.get("etag")
95 assert.notStrictEqual(etag, null)
96 if (etag === null) {
97 throw new Error("missing etag")
98 }
99 const weakComparable = etag.startsWith("W/") ? etag.slice(2) : `W/${etag}`
100
101 const exact = await handler(
102 new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": etag } })
103 )
104 const weak = await handler(
105 new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": weakComparable } })
106 )
107 const any = await handler(new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": "*" } }))
108
109 assert.deepStrictEqual([exact.status, weak.status, any.status], [304, 304, 304])
110 assert.strictEqual(exact.headers.get("etag"), etag)
111 assert.strictEqual(exact.headers.get("cache-control"), "public, max-age=60")
112 assert.strictEqual(exact.headers.get("content-type"), null)
113 assert.strictEqual(exact.headers.get("content-length"), null)
114 }, { cacheControl: "public, max-age=60" })
115 })
116
117 it("returns 304 for If-Modified-Since and 200 when file changed", async () => {
118 await withStaticFiles(async ({ handler, root }) => {
119 const first = await handler(new Request("http://localhost/conditional.txt"))
120 const lastModified = first.headers.get("last-modified")
121 assert.notStrictEqual(lastModified, null)
122 if (lastModified === null) {
123 throw new Error("missing last-modified")
124 }
125
126 const notModified = await handler(
127 new Request("http://localhost/conditional.txt", {
128 headers: {
129 "If-Modified-Since": lastModified
130 }
131 })
132 )
133 assert.strictEqual(notModified.status, 304)
134
135 const conditionalFile = NodePath.join(root, "conditional.txt")
136 await writeFile(conditionalFile, "updated conditional body")
137 const updatedTime = new Date(Date.now() + 10_000)
138 await utimes(conditionalFile, updatedTime, updatedTime)
139
140 const modified = await handler(
141 new Request("http://localhost/conditional.txt", {
142 headers: {
143 "If-Modified-Since": lastModified
144 }
145 })
146 )
147 assert.strictEqual(modified.status, 200)
148 assert.strictEqual(await modified.text(), "updated conditional body")
149 })
150 })
151
152 it("handles range requests for valid, invalid, and malformed headers", async () => {
153 await withStaticFiles(async ({ handler }) => {
154 const fullBody = await handler(new Request("http://localhost/range.txt")).then((response) => response.text())
155 const fileSize = fullBody.length
156
157 const first = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=0-10" } }))
158 assert.strictEqual(first.status, 206)
159 assert.strictEqual(first.headers.get("content-range"), `bytes 0-10/${fileSize}`)
160 assert.strictEqual(await first.text(), "0123456789a")
161
162 const openEnded = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=5-" } }))
163 assert.strictEqual(openEnded.status, 206)
164 assert.strictEqual(openEnded.headers.get("content-range"), `bytes 5-${fileSize - 1}/${fileSize}`)
165 assert.strictEqual(await openEnded.text(), fullBody.slice(5))
166
167 const suffix = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=-10" } }))
168 assert.strictEqual(suffix.status, 206)
169 assert.strictEqual(suffix.headers.get("content-range"), `bytes ${fileSize - 10}-${fileSize - 1}/${fileSize}`)
170 assert.strictEqual(await suffix.text(), fullBody.slice(-10))
171
172 const invalid = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=100-200" } }))
173 assert.strictEqual(invalid.status, 416)
174 assert.strictEqual(invalid.headers.get("content-range"), `bytes */${fileSize}`)
175
176 const malformed = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=abc" } }))
177 assert.strictEqual(malformed.status, 200)
178 assert.strictEqual(await malformed.text(), fullBody)
179 })
180 })
181
182 it("handles SPA fallback for html accept and missing routes", async () => {
183 await withStaticFiles(async ({ handler }) => {
184 const htmlFallback = await handler(new Request("http://localhost/missing", { headers: { accept: "text/html" } }))
185 assert.strictEqual(htmlFallback.status, 200)
186 assert.strictEqual((await htmlFallback.text()).trimEnd(), "<html><body>root index</body></html>")
187
188 const withExtension = await handler(
189 new Request("http://localhost/missing.js", { headers: { accept: "text/html" } })
190 )
191 assert.strictEqual(withExtension.status, 404)
192
193 const withoutHtmlAccept = await handler(
194 new Request("http://localhost/missing", { headers: { accept: "application/json" } })
195 )
196 assert.strictEqual(withoutHtmlAccept.status, 404)
197 }, { spa: true, index: "index.html" })
198 })
199
200 it("rejects directory traversal attempts", async () => {
201 await withStaticFiles(async ({ handler, outsideFile }) => {
202 const plainTraversal = await handler(new Request("http://localhost/../../../etc/passwd"))
203 const encodedTraversal = await handler(new Request("http://localhost/..%2F..%2Fetc%2Fpasswd"))
204 const encodedExistingParentFileTraversal = await handler(
205 new Request(`http://localhost/..%2F${encodeURIComponent(NodePath.basename(outsideFile))}`)
206 )
207
208 assert.deepStrictEqual([
209 plainTraversal.status,
210 encodedTraversal.status,
211 encodedExistingParentFileTraversal.status
212 ], [
213 404,
214 404,
215 404
216 ])
217 })
218 })
219
220 it("rejects null bytes and malformed uri encoding", async () => {
221 await withStaticFiles(async ({ handler }) => {
222 const nullByte = await handler(new Request("http://localhost/null%00byte.txt"))
223 const malformed = await handler(new Request("http://localhost/%E0%A4%A"))
224
225 assert.deepStrictEqual([nullByte.status, malformed.status], [404, 404])
226 })
227 })
228
229 it("applies custom mime types and cache-control", async () => {
230 await withStaticFiles(async ({ handler }) => {
231 const response = await handler(new Request("http://localhost/hello.txt"))
232 assert.strictEqual(response.status, 200)
233 assert.strictEqual(response.headers.get("content-type"), "application/x-custom-text")
234 assert.strictEqual(response.headers.get("cache-control"), "public, max-age=120")
235 }, {
236 cacheControl: "public, max-age=120",
237 mimeTypes: {
238 txt: "application/x-custom-text"
239 }
240 })
241 })
242
243 it("uses application/octet-stream for unknown extension and 404 for missing file", async () => {
244 await withStaticFiles(async ({ handler }) => {
245 const unknown = await handler(new Request("http://localhost/file.binx"))
246 assert.strictEqual(unknown.status, 200)
247 assert.strictEqual(unknown.headers.get("content-type"), "application/octet-stream")
248
249 const missing = await handler(new Request("http://localhost/does-not-exist.txt"))
250 assert.strictEqual(missing.status, 404)
251 })
252 })
253})