feat: add trustProxy option to respect X-Forwarded-* headers (#3757)
## Summary - Adds `trustProxy` option to `FreshConfig` (default: `false`) - When enabled, the handler reads `X-Forwarded-Proto` and `X-Forwarded-Host` headers and rewrites `ctx.url` so it reflects the actual client-facing URL - Useful for apps running behind nginx, Caddy, or other reverse proxies where `ctx.url` would otherwise return `http://` instead of `https://` Closes #2660 ## Usage ```ts const app = new App({ trustProxy: true }); ``` --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
990aeb03f3
commit
07878fcce9
@@ -190,6 +190,7 @@ export class App<State> {
|
||||
root: ".",
|
||||
basePath: config.basePath ?? "",
|
||||
mode: config.mode ?? "production",
|
||||
trustProxy: config.trustProxy ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -392,6 +393,8 @@ export class App<State> {
|
||||
this.#onError,
|
||||
);
|
||||
|
||||
const trustProxy = this.config.trustProxy;
|
||||
|
||||
return async (
|
||||
req: Request,
|
||||
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
|
||||
@@ -400,6 +403,18 @@ export class App<State> {
|
||||
// Prevent open redirect attacks
|
||||
url.pathname = url.pathname.replace(/\/+/g, "/");
|
||||
|
||||
// Apply X-Forwarded-* headers when behind a reverse proxy
|
||||
if (trustProxy) {
|
||||
const proto = req.headers.get("x-forwarded-proto");
|
||||
if (proto) {
|
||||
url.protocol = proto + ":";
|
||||
}
|
||||
const host = req.headers.get("x-forwarded-host");
|
||||
if (host) {
|
||||
url.host = host;
|
||||
}
|
||||
}
|
||||
|
||||
const method = req.method.toUpperCase() as Method;
|
||||
const matched = router.match(method, url);
|
||||
let { params, pattern, item: handler, methodMatch } = matched;
|
||||
|
||||
Reference in New Issue
Block a user