The best way to control Claude Code, Codex and more from any computer or phone

main
ts 393 lines 16.8 KB
Raw
1 import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
2 import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform"
3 import * as NodePathLayer from "@effect/platform-node/NodePath"
4 import { assert, describe, it } from "@effect/vitest"
5 import { HttpRouter, HttpStaticServer } from "effect/http"
6 import * as Layer from "effect/Layer"
7 import * as Fs from "node:fs"
8 import { copyFile, cp, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"
9 import { tmpdir } from "node:os"
10 import * as NodePath from "node:path"
11 import { fileURLToPath } from "node:url"
12 import { vi } from "vitest"
13
14 vi.mock("node:fs", async (importOriginal) => {
15 const original = await importOriginal<typeof Fs>()
16 return { ...original, createReadStream: vi.fn(original.createReadStream) }
17 })
18
19 const fixturesRoot = fileURLToPath(new URL("./fixtures/http-static-server", import.meta.url))
20 const fixturesOutsideFile = fileURLToPath(new URL("./fixtures/http-static-server-outside.txt", import.meta.url))
21
22 const staticFilesLayer = Layer.mergeAll(
23 NodePathLayer.layer,
24 NodeFileSystem.layer,
25 NodeHttpPlatform.layer
26 )
27
28 const makeHandler = (
29 root: string,
30 options: Omit<Parameters<typeof HttpStaticServer.layer>[0], "root"> = {}
31 ) =>
32 HttpRouter.toWebHandler(
33 HttpStaticServer.layer({
34 root,
35 ...options
36 }).pipe(Layer.provideMerge(staticFilesLayer)),
37 { disableLogger: true }
38 )
39
40 const withStaticFiles = async (
41 run: (context: {
42 readonly handler: (request: Request) => Promise<Response>
43 readonly root: string
44 readonly outsideFile: string
45 }) => Promise<void>,
46 options: Omit<Parameters<typeof HttpStaticServer.layer>[0], "root"> = {}
47 ) => {
48 const temporaryRoot = await mkdtemp(NodePath.join(tmpdir(), "effect-http-static-server-"))
49 const root = NodePath.join(temporaryRoot, "root")
50 const outsideFile = NodePath.join(temporaryRoot, NodePath.basename(fixturesOutsideFile))
51
52 await Promise.all([
53 cp(fixturesRoot, root, { recursive: true }),
54 copyFile(fixturesOutsideFile, outsideFile)
55 ])
56
57 const { handler, dispose } = makeHandler(root, options)
58 try {
59 await run({ handler, root, outsideFile })
60 } finally {
61 await dispose()
62 await rm(temporaryRoot, { recursive: true, force: true })
63 }
64 }
65
66 describe("HttpStaticServer", { concurrent: false }, () => {
67 it("serves files with expected content type and body", async () => {
68 await withStaticFiles(async ({ handler }) => {
69 const response = await handler(new Request("http://localhost/hello.txt"))
70 assert.strictEqual(response.status, 200)
71 assert.strictEqual(response.headers.get("content-type"), "text/plain; charset=utf-8")
72 assert.strictEqual((await response.text()).trimEnd(), "hello static file")
73 })
74 })
75
76 it("serves default index file for directory paths", async () => {
77 await withStaticFiles(async ({ handler }) => {
78 const response = await handler(new Request("http://localhost/guide/"))
79 assert.strictEqual(response.status, 200)
80 assert.strictEqual(response.headers.get("content-type"), "text/html; charset=utf-8")
81 assert.strictEqual((await response.text()).trimEnd(), "<html><body>guide index</body></html>")
82 })
83 })
84
85 for (const prefix of ["", "/static"]) {
86 it(`redirects directory URLs with their query string under ${prefix || "/"}`, async () => {
87 await withStaticFiles(async ({ handler }) => {
88 const response = await handler(new Request(`http://localhost${prefix}/guide?x=1&next=%2Fdocs`))
89 assert.strictEqual(response.status, 301)
90 assert.strictEqual(response.headers.get("location"), `${prefix}/guide/?x=1&next=%2Fdocs`)
91
92 const index = await handler(
93 new Request(new URL(response.headers.get("location")!, "http://localhost"))
94 )
95 assert.strictEqual(index.status, 200)
96 assert.strictEqual(index.headers.get("location"), null)
97 assert.strictEqual((await index.text()).trimEnd(), "<html><body>guide index</body></html>")
98 }, { prefix: prefix || undefined })
99 })
100 }
101
102 it("supports custom index file and disabled index fallback", async () => {
103 await withStaticFiles(async ({ handler }) => {
104 const response = await handler(new Request("http://localhost/custom/"))
105 assert.strictEqual(response.status, 200)
106 assert.strictEqual((await response.text()).trimEnd(), "<html><body>custom home</body></html>")
107 }, { index: "home.html" })
108
109 await withStaticFiles(async ({ handler }) => {
110 const response = await handler(new Request("http://localhost/custom"))
111 assert.strictEqual(response.status, 404)
112 }, { index: undefined })
113 })
114
115 it("returns 304 for If-None-Match exact, weak, and wildcard", async () => {
116 await withStaticFiles(async ({ handler }) => {
117 const warmup = await handler(new Request("http://localhost/conditional.txt"))
118 const etag = warmup.headers.get("etag")
119 assert.notStrictEqual(etag, null)
120 if (etag === null) {
121 throw new Error("missing etag")
122 }
123 const weakComparable = etag.startsWith("W/") ? etag.slice(2) : `W/${etag}`
124
125 const exact = await handler(
126 new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": etag } })
127 )
128 const weak = await handler(
129 new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": weakComparable } })
130 )
131 const any = await handler(new Request("http://localhost/conditional.txt", { headers: { "If-None-Match": "*" } }))
132
133 assert.deepStrictEqual([exact.status, weak.status, any.status], [304, 304, 304])
134 assert.strictEqual(exact.headers.get("etag"), etag)
135 assert.strictEqual(exact.headers.get("cache-control"), "public, max-age=60")
136 assert.strictEqual(exact.headers.get("content-type"), null)
137 assert.strictEqual(exact.headers.get("content-length"), null)
138 }, { cacheControl: "public, max-age=60" })
139 })
140
141 it("returns 304 for If-Modified-Since and 200 when file changed", async () => {
142 await withStaticFiles(async ({ handler, root }) => {
143 const first = await handler(new Request("http://localhost/conditional.txt"))
144 const lastModified = first.headers.get("last-modified")
145 assert.notStrictEqual(lastModified, null)
146 if (lastModified === null) {
147 throw new Error("missing last-modified")
148 }
149
150 const notModified = await handler(
151 new Request("http://localhost/conditional.txt", {
152 headers: {
153 "If-Modified-Since": lastModified
154 }
155 })
156 )
157 assert.strictEqual(notModified.status, 304)
158
159 const conditionalFile = NodePath.join(root, "conditional.txt")
160 await writeFile(conditionalFile, "updated conditional body")
161 const updatedTime = new Date(Date.now() + 10_000)
162 await utimes(conditionalFile, updatedTime, updatedTime)
163
164 const modified = await handler(
165 new Request("http://localhost/conditional.txt", {
166 headers: {
167 "If-Modified-Since": lastModified
168 }
169 })
170 )
171 assert.strictEqual(modified.status, 200)
172 assert.strictEqual(await modified.text(), "updated conditional body")
173 })
174 })
175
176 it("honors Range only for a matching strong If-Range ETag", async () => {
177 await withStaticFiles(async ({ handler, root }) => {
178 const first = await handler(new Request("http://localhost/range.txt"))
179 const etag = first.headers.get("etag")!
180 assert.strictEqual(etag.startsWith("W/"), false)
181 const fullBody = await first.text()
182 vi.mocked(Fs.createReadStream).mockClear()
183
184 const matching = await handler(
185 new Request("http://localhost/range.txt", {
186 headers: { Range: "bytes=0-10", "If-Range": etag }
187 })
188 )
189 assert.strictEqual(matching.status, 206)
190 assert.strictEqual(matching.headers.get("content-range"), `bytes 0-10/${fullBody.length}`)
191 assert.strictEqual(await matching.text(), "0123456789a")
192 // Only the selected range acquires a source, not the discarded full response.
193 assert.deepStrictEqual(vi.mocked(Fs.createReadStream).mock.calls, [[NodePath.join(root, "range.txt"), {
194 start: 0,
195 end: 10
196 }]])
197
198 // Weak tags and Last-Modified dates never match: filesystem metadata
199 // cannot prove a date is a strong validator.
200 for (const ifRange of [`W/${etag}`, first.headers.get("last-modified")!]) {
201 const response = await handler(
202 new Request("http://localhost/range.txt", {
203 headers: { Range: "bytes=0-10", "If-Range": ifRange }
204 })
205 )
206 assert.strictEqual(response.status, 200)
207 assert.strictEqual(response.headers.get("content-range"), null)
208 assert.strictEqual(await response.text(), fullBody)
209 }
210 })
211 })
212
213 it.each(["bytes=10-", "bytes=100-200"])(
214 "returns the full changed file for a stale If-Range ETag with Range %s",
215 async (range) => {
216 await withStaticFiles(async ({ handler, root }) => {
217 const first = await handler(new Request("http://localhost/range.txt"))
218 const etag = first.headers.get("etag")!
219 await first.text()
220 const updatedBody = "NEW-NEW-NEW-NEW-NEW-NEW-"
221 await writeFile(NodePath.join(root, "range.txt"), updatedBody)
222 const resumed = await handler(
223 new Request("http://localhost/range.txt", {
224 headers: { Range: range, "If-Range": etag }
225 })
226 )
227 assert.strictEqual(resumed.status, 200)
228 assert.strictEqual(resumed.headers.get("content-range"), null)
229 assert.strictEqual(resumed.headers.get("content-length"), String(updatedBody.length))
230 assert.notStrictEqual(resumed.headers.get("etag"), etag)
231 assert.strictEqual(await resumed.text(), updatedBody)
232 })
233 }
234 )
235
236 it("handles range requests for valid, invalid, and malformed headers", async () => {
237 await withStaticFiles(async ({ handler }) => {
238 const full = await handler(new Request("http://localhost/range.txt"))
239 const etag = full.headers.get("etag")!
240 const fullBody = await full.text()
241 const fileSize = fullBody.length
242
243 const first = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=0-10" } }))
244 assert.strictEqual(first.status, 206)
245 assert.strictEqual(first.headers.get("content-range"), `bytes 0-10/${fileSize}`)
246 assert.strictEqual(await first.text(), "0123456789a")
247
248 const openEnded = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=5-" } }))
249 assert.strictEqual(openEnded.status, 206)
250 assert.strictEqual(openEnded.headers.get("content-range"), `bytes 5-${fileSize - 1}/${fileSize}`)
251 assert.strictEqual(await openEnded.text(), fullBody.slice(5))
252
253 const suffix = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=-10" } }))
254 assert.strictEqual(suffix.status, 206)
255 assert.strictEqual(suffix.headers.get("content-range"), `bytes ${fileSize - 10}-${fileSize - 1}/${fileSize}`)
256 assert.strictEqual(await suffix.text(), fullBody.slice(-10))
257
258 vi.mocked(Fs.createReadStream).mockClear()
259 const invalid = await handler(
260 new Request("http://localhost/range.txt", {
261 headers: { Range: "bytes=100-200", "If-Range": etag }
262 })
263 )
264 assert.strictEqual(invalid.status, 416)
265 assert.strictEqual(invalid.headers.get("content-range"), `bytes */${fileSize}`)
266 assert.strictEqual(await invalid.text(), "")
267 assert.deepStrictEqual(vi.mocked(Fs.createReadStream).mock.calls, [])
268
269 const malformed = await handler(new Request("http://localhost/range.txt", { headers: { Range: "bytes=abc" } }))
270 assert.strictEqual(malformed.status, 200)
271 assert.strictEqual(await malformed.text(), fullBody)
272 })
273 })
274
275 const unsafeRangeInteger = (BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)).toString()
276
277 it.each([
278 `bytes=${unsafeRangeInteger}-`,
279 `bytes=${unsafeRangeInteger}-${unsafeRangeInteger}`
280 ])("returns 416 for a range start above Number.MAX_SAFE_INTEGER: %s", async (range) => {
281 await withStaticFiles(async ({ handler }) => {
282 const fullBody = await handler(new Request("http://localhost/range.txt")).then((response) => response.text())
283 const response = await handler(
284 new Request("http://localhost/range.txt", { headers: { Range: range } })
285 )
286
287 assert.strictEqual(response.status, 416)
288 assert.strictEqual(response.headers.get("content-range"), `bytes */${fullBody.length}`)
289 assert.strictEqual(await response.text(), "")
290 })
291 })
292
293 it.each([
294 `bytes=0-${unsafeRangeInteger}`,
295 `bytes=-${unsafeRangeInteger}`
296 ])("returns the whole file as 206 for range ends and suffixes above Number.MAX_SAFE_INTEGER: %s", async (range) => {
297 await withStaticFiles(async ({ handler }) => {
298 const fullBody = await handler(new Request("http://localhost/range.txt")).then((response) => response.text())
299 const response = await handler(new Request("http://localhost/range.txt", { headers: { Range: range } }))
300
301 assert.strictEqual(response.status, 206)
302 assert.strictEqual(response.headers.get("content-range"), `bytes 0-${fullBody.length - 1}/${fullBody.length}`)
303 assert.strictEqual(response.headers.get("content-length"), String(fullBody.length))
304 assert.strictEqual(await response.text(), fullBody)
305 })
306 })
307
308 it("clamps a range end above Number.MAX_SAFE_INTEGER while preserving a nonzero start", async () => {
309 await withStaticFiles(async ({ handler }) => {
310 const fullBody = await handler(new Request("http://localhost/range.txt")).then((response) => response.text())
311 const response = await handler(
312 new Request("http://localhost/range.txt", { headers: { Range: `bytes=5-${unsafeRangeInteger}` } })
313 )
314
315 assert.strictEqual(response.status, 206)
316 assert.strictEqual(response.headers.get("content-range"), `bytes 5-${fullBody.length - 1}/${fullBody.length}`)
317 assert.strictEqual(response.headers.get("content-length"), String(fullBody.length - 5))
318 assert.strictEqual(await response.text(), fullBody.slice(5))
319 })
320 })
321
322 it("handles SPA fallback for html accept and missing routes", async () => {
323 await withStaticFiles(async ({ handler }) => {
324 const htmlFallback = await handler(new Request("http://localhost/missing", { headers: { accept: "text/html" } }))
325 assert.strictEqual(htmlFallback.status, 200)
326 assert.strictEqual((await htmlFallback.text()).trimEnd(), "<html><body>root index</body></html>")
327
328 const withExtension = await handler(
329 new Request("http://localhost/missing.js", { headers: { accept: "text/html" } })
330 )
331 assert.strictEqual(withExtension.status, 404)
332
333 const withoutHtmlAccept = await handler(
334 new Request("http://localhost/missing", { headers: { accept: "application/json" } })
335 )
336 assert.strictEqual(withoutHtmlAccept.status, 404)
337 }, { spa: true, index: "index.html" })
338 })
339
340 it("rejects directory traversal attempts", async () => {
341 await withStaticFiles(async ({ handler, outsideFile }) => {
342 const plainTraversal = await handler(new Request("http://localhost/../../../etc/passwd"))
343 const encodedTraversal = await handler(new Request("http://localhost/..%2F..%2Fetc%2Fpasswd"))
344 const encodedExistingParentFileTraversal = await handler(
345 new Request(`http://localhost/..%2F${encodeURIComponent(NodePath.basename(outsideFile))}`)
346 )
347
348 assert.deepStrictEqual([
349 plainTraversal.status,
350 encodedTraversal.status,
351 encodedExistingParentFileTraversal.status
352 ], [
353 404,
354 404,
355 404
356 ])
357 })
358 })
359
360 it("rejects null bytes and malformed uri encoding", async () => {
361 await withStaticFiles(async ({ handler }) => {
362 const nullByte = await handler(new Request("http://localhost/null%00byte.txt"))
363 const malformed = await handler(new Request("http://localhost/%E0%A4%A"))
364
365 assert.deepStrictEqual([nullByte.status, malformed.status], [404, 404])
366 })
367 })
368
369 it("applies custom mime types and cache-control", async () => {
370 await withStaticFiles(async ({ handler }) => {
371 const response = await handler(new Request("http://localhost/hello.txt"))
372 assert.strictEqual(response.status, 200)
373 assert.strictEqual(response.headers.get("content-type"), "application/x-custom-text")
374 assert.strictEqual(response.headers.get("cache-control"), "public, max-age=120")
375 }, {
376 cacheControl: "public, max-age=120",
377 mimeTypes: {
378 txt: "application/x-custom-text"
379 }
380 })
381 })
382
383 it("uses application/octet-stream for unknown extension and 404 for missing file", async () => {
384 await withStaticFiles(async ({ handler }) => {
385 const unknown = await handler(new Request("http://localhost/file.binx"))
386 assert.strictEqual(unknown.status, 200)
387 assert.strictEqual(unknown.headers.get("content-type"), "application/octet-stream")
388
389 const missing = await handler(new Request("http://localhost/does-not-exist.txt"))
390 assert.strictEqual(missing.status, 404)
391 })
392 })
393 })