Redirects use the address the browser used, not the server's listen address
Behind Docker or a proxy, request.url says http://0.0.0.0:3000, so the sign-in link sent people there. originOf() reads the Host or X-Forwarded-Host header. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
44aa5e0933
commit
c50c645cfb
8 files changed
+38
-8
No files matched your search
@@ -0,0 +1,10 @@
|
||||
// node src/lib/origin.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { originOf } from "./origin.ts";
|
||||
|
||||
const req = (url: string, headers: Record<string, string> = {}) => new Request(url, { headers });
|
||||
assert.equal(originOf(req("http://0.0.0.0:3000/auth/callback", { host: "192.168.1.10:3000" })), "http://192.168.1.10:3000", "Docker: the address the browser used");
|
||||
assert.equal(originOf(req("http://localhost:3000/x", { host: "localhost:3000", "x-forwarded-host": "broke.example.com", "x-forwarded-proto": "https" })), "https://broke.example.com", "behind a proxy");
|
||||
assert.equal(originOf(req("http://localhost:3000/x", { host: "evil.com/path?" })), "http://localhost:3000", "a malformed host falls back");
|
||||
assert.equal(originOf(req("https://broke.vercel.app/x")), "https://broke.vercel.app", "no host header");
|
||||
console.log("origin ok");
|
||||
@@ -0,0 +1,13 @@
|
||||
// The address the browser used to reach broke, for redirects and callback links.
|
||||
// request.url carries the server's own listen address instead (http://0.0.0.0:3000 in Docker,
|
||||
// http://localhost:3000 behind a proxy), so the Host header the browser or proxy sent wins.
|
||||
const HOST = /^[a-z0-9.-]+(:\d+)?$|^\[[0-9a-f:]+\](:\d+)?$/i;
|
||||
|
||||
export function originOf(request: Request) {
|
||||
const own = new URL(request.url);
|
||||
const h = request.headers;
|
||||
const host = (h.get("x-forwarded-host") ?? h.get("host") ?? "").split(",")[0].trim();
|
||||
if (!HOST.test(host)) return own.origin;
|
||||
const proto = (h.get("x-forwarded-proto") ?? "").split(",")[0].trim();
|
||||
return `${proto === "https" || proto === "http" ? proto : own.protocol.slice(0, -1)}://${host}`;
|
||||
}
|
||||
Reference in new issue
Block a user