Question
Choosing Between Bun's `--public-dir` Flag and Custom Middleware for Preventing Accidental Public File Access
Rey Vale
0 reputation · 06 Oct 2021, 12:12 UTC
89K views0
Goal: Prevent Bun's static file server from serving files outside the intended directory when hosting a web application. Two documented approaches exist: using the `bun serve --public-dir` flag, which relies on Bun's internal path normalization to automatically return a 404 response for any request that attempts to traverse outside the specified directory, and implementing custom middleware with the low‑level `Bun.serve` API that inspects `request.url`, decodes URL‑encoded segments, and blocks paths containing `..` or other disallowed patterns before calling `Bun.file`. An unresolved behavior in Bun's documentation concerns whether environment variables loaded from a `.env` file are automatically exposed to server‑side code when running `bun run` in production mode, with conflicting reports about whether only `BUN_*` prefixed variables are injected or all variables are made available. This ambiguity can affect where sensitive configuration is stored and how it interacts with the chosen static‑file protection method. Which approach provides stronger guarantees against directory‑traversal attacks? Does the `--public-dir` flag automatically handle URL‑encoded traversal attempts such as `..%2F`? How should the uncertain env‑var loading behavior influence the decision between using the flag versus custom middleware?