Choosing Between Bun's `--public-dir` Flag and Custom Middleware for Preventing Accidental Public File Access
0 reputation · 06 Oct 2021, 12:12 UTC
0 reputation · 06 Oct 2021, 12:12 UTC
32775 reputation · 06 Oct 2021, 22:42 UTC
When Bun serves static files, the choice between bun serve --public-dir and hand-rolled Bun.serve middleware determines how reliably directory-traversal attacks are mitigated.
Confirmed fact: The --public-dir flag routes every request through Bun's internal handler, which resolves the requested path, normalizes URL-encoded segments (e.g., %2F becomes /), and returns 404 if the resolved path falls outside the specified directory. This means traversal attempts like ..%2F are decoded before comparison and effectively treated as .., resulting in a 404 response.
Custom middleware approach: Middleware built on Bun.serve can replicate this check by inspecting request.url, percent-decoding each path segment, and rejecting paths that contain .. or escape the root directory. However, the security of custom middleware hinges on the completeness of its decoding logic; missed edge cases such as double-encoding or symlink resolution can create gaps.
Environment-variable ambiguity: Bun automatically parses .env files and makes all parsed variables available via process.env; there is no evidence that only BUN_-prefixed variables are injected in production mode. This ambiguity does not directly affect directory-traversal protection, but custom middleware must avoid exposing process.env in any response payloads.
The --public-dir flag offers a stronger out-of-the-box guarantee for typical deployments, yet its protection can be undermined if a reverse proxy in front of Bun also normalizes paths. Custom middleware gives fine-grained control but demands rigorous testing across encoding variants and runtime environments.
--public-dir by requesting ..%2F..%2Fetc/passwd and confirming a 404 is returned.process.env after bun run to verify which .env variables are present.To finalize the recommendation, please confirm the Bun runtime version and whether the server is invoked via bun run, a compiled binary, or behind a reverse proxy, as .env loading scope and path-handling behavior differ across these contexts.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.