Skip to content

host parse #13309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/honest-mangos-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@react-router/express": patch
---

Better validation of `x-forwarded-host` header to preent potential security issues.
24 changes: 24 additions & 0 deletions packages/react-router-express/__tests__/server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,28 @@ describe("express createRemixRequest", () => {
);
expect(remixRequest.headers.get("host")).toBe("localhost:3000");
});

it("validates parsed port", async () => {
let expressRequest = createRequest({
url: "/foo/bar",
method: "GET",
protocol: "http",
hostname: "localhost",
headers: {
"Cache-Control": "max-age=300, s-maxage=3600",
Host: "localhost:3000",
"x-forwarded-host": ":/spoofed"
},
});
let expressResponse = createResponse();

let remixRequest = createRemixRequest(expressRequest, expressResponse);

expect(remixRequest.method).toBe("GET");
expect(remixRequest.headers.get("cache-control")).toBe(
"max-age=300, s-maxage=3600"
);
expect(remixRequest.headers.get("host")).toBe("localhost:3000");
expect(remixRequest.url).toBe("http://localhost:3000/foo/bar");
});
});
12 changes: 9 additions & 3 deletions packages/react-router-express/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,15 @@ export function createRemixRequest(
): Request {
// req.hostname doesn't include port information so grab that from
// `X-Forwarded-Host` or `Host`
let [, hostnamePort] = req.get("X-Forwarded-Host")?.split(":") ?? [];
let [, hostPort] = req.get("host")?.split(":") ?? [];
let port = hostnamePort || hostPort;
let [, hostnamePortStr] = req.get("X-Forwarded-Host")?.split(":") ?? [];
let [, hostPortStr] = req.get("host")?.split(":") ?? [];
let hostnamePort = Number.parseInt(hostnamePortStr, 10);
let hostPort = Number.parseInt(hostPortStr, 10);
let port = Number.isSafeInteger(hostnamePort)
? hostnamePort
: Number.isSafeInteger(hostPort)
? hostPort
: "";
// Use req.hostname here as it respects the "trust proxy" setting
let resolvedHost = `${req.hostname}${port ? `:${port}` : ""}`;
// Use `req.originalUrl` so Remix is aware of the full path
Expand Down