import { existsSync, readdirSync, statSync } from "node:fs"; import { join, normalize } from "node:path"; const rootDir = process.cwd(); const port = Number.parseInt(process.env.PORT ?? "3000", 10); function resolveSafePath(urlPathname: string): string | null { let pathname = urlPathname; try { pathname = decodeURIComponent(pathname); } catch { return null; } if (pathname.endsWith("/")) pathname += "index.html"; const rel = pathname.replace(/^\/+/, ""); const normalized = normalize(rel); if (normalized.startsWith("..") || normalized.includes("/..") || normalized.includes("\\..")) { return null; } const parts = normalized.split(/[\\/]+/).filter(Boolean); if (parts.some((p) => p !== "." && p.startsWith("."))) return null; return join(rootDir, normalized); } Bun.serve({ port, async fetch(req) { if (req.method !== "GET" && req.method !== "HEAD") { return new Response("Method Not Allowed", { status: 405 }); } const url = new URL(req.url); const filePath = resolveSafePath(url.pathname); if (!filePath) return new Response("Bad Request", { status: 400 }); // Redirect directory paths missing trailing slash. if (!url.pathname.endsWith("/") && existsSync(filePath) && statSync(filePath).isDirectory()) { return Response.redirect(`${url.pathname}/`, 308); } if (!existsSync(filePath)) { // If it's a directory URL but there's no index.html, show a tiny listing. if (url.pathname.endsWith("/")) { const dirPath = resolveSafePath(url.pathname.replace(/\/$/, "")); if (!dirPath) return new Response("Bad Request", { status: 400 }); if (existsSync(dirPath) && statSync(dirPath).isDirectory()) { const entries = readdirSync(dirPath, { withFileTypes: true }) .filter((d) => !d.name.startsWith(".")) .map((d) => ({ name: d.name, isDir: d.isDirectory() })) .sort((a, b) => Number(b.isDir) - Number(a.isDir) || a.name.localeCompare(b.name)); const items = [ url.pathname !== "/" ? `
  • ../
  • ` : "", ...entries.map(({ name, isDir }) => { const href = `${url.pathname}${encodeURIComponent(name)}${isDir ? "/" : ""}`; return `
  • ${name}${isDir ? "/" : ""}
  • `; }), ].join(""); const html = `Index of ${url.pathname}

    Index of ${url.pathname}

    `; const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" }); headers.set("Content-Length", String(Buffer.byteLength(html))); return new Response(req.method === "HEAD" ? null : html, { status: 200, headers }); } } return new Response("Not Found", { status: 404 }); } const file = Bun.file(filePath); const headers = new Headers(); if (file.type) headers.set("Content-Type", file.type); headers.set("Content-Length", String(file.size)); return new Response(req.method === "HEAD" ? null : file, { status: 200, headers }); }, }); console.log(`Serving ${rootDir} at http://localhost:${port}`);