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:
MangaValkandClaude Opus 5.5 committed 2026-11-17 13:56:32 +01:00
1 parent 44aa5e0933
commit c50c645cfb
8 files changed
+38 -8

No files matched your search

+3 -2
View File
@@ -2,18 +2,19 @@ import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { codeSeen, exchangeOnce, saveKey } from "@/lib/llm/openrouter";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
// OpenRouter sends the user back here. The state must match the cookie, then the code becomes this user's key.
export async function GET(request: Request) {
const url = new URL(request.url);
const back = (q: string) => {
const res = NextResponse.redirect(`${url.origin}/connect-ai?${q}`);
const res = NextResponse.redirect(`${originOf(request)}/connect-ai?${q}`);
res.cookies.delete({ name: "or_pkce", path: "/api/ai/openrouter" });
return res;
};
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) return NextResponse.redirect(`${url.origin}/login`);
if (!user) return NextResponse.redirect(`${originOf(request)}/login`);
let saved: { verifier?: string; state?: string } = {};
try {
saved = JSON.parse((await cookies()).get("or_pkce")?.value ?? "{}");
+2 -1
View File
@@ -1,10 +1,11 @@
import { NextResponse } from "next/server";
import { authStart } from "@/lib/llm/openrouter";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
// "Connect OpenRouter": remembers the PKCE secret in a short-lived cookie and sends the user to approve broke.
export async function GET(request: Request) {
const { origin } = new URL(request.url);
const origin = originOf(request);
const { data: { user } } = await (await createClient()).auth.getUser();
if (!user) return NextResponse.redirect(`${origin}/login`);
const { url, verifier, state } = authStart(`${origin}/api/ai/openrouter/callback`);
@@ -4,6 +4,7 @@ import { configured } from "@/lib/providers";
import { ebFinish, isFeed } from "@/lib/providers/feeds";
import { linkFeed } from "@/lib/sync";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
// The vendor sends the user back here after consent. The state must match the cookie set when they left.
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
@@ -11,12 +12,12 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
const url = new URL(request.url);
const q = url.searchParams;
const back = (r: string) => {
const res = NextResponse.redirect(`${url.origin}/accounts/add?${r}`);
const res = NextResponse.redirect(`${originOf(request)}/accounts/add?${r}`);
res.cookies.delete({ name: "bank_connect", path: "/api/bank/connect" });
return res;
};
const { data: { user } } = await (await createClient()).auth.getUser();
if (!user) return NextResponse.redirect(`${url.origin}/login`);
if (!user) return NextResponse.redirect(`${originOf(request)}/login`);
let saved: { state?: string; userId?: string } = {};
try {
saved = JSON.parse((await cookies()).get("bank_connect")?.value ?? "{}");
+2 -1
View File
@@ -3,6 +3,7 @@ import { configured } from "@/lib/providers";
import { basiqStart, belvoStart, ebBanks, ebStart, isFeed, newState, validCpf } from "@/lib/providers/feeds";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
const COOKIE = "bank_connect";
@@ -23,7 +24,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const { origin } = new URL(request.url);
const origin = originOf(request);
const { data: { user } } = await (await createClient()).auth.getUser();
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
if (!isFeed(id) || !configured(id)) return NextResponse.json({ error: "This connection isn't set up yet." }, { status: 400 });
+3 -1
View File
@@ -1,8 +1,10 @@
import { NextResponse } from "next/server";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const { searchParams } = new URL(request.url);
const origin = originOf(request);
const code = searchParams.get("code");
if (code) {
const supabase = await createClient();
+2 -1
View File
@@ -2,11 +2,12 @@ import { NextResponse } from "next/server";
import { sameOrigin } from "@/lib/setup";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
import { originOf } from "@/lib/origin";
// Dev-only login bypass: signs in as DEV_LOGIN_EMAIL without an email link. Dead in production builds.
// POST from the login page only, so another site can't sign a visitor in.
export async function POST(request: Request) {
const { origin } = new URL(request.url);
const origin = originOf(request);
const email = process.env.DEV_LOGIN_EMAIL;
if (process.env.NODE_ENV === "production" || !email) return new NextResponse("Not found", { status: 404 });
if (!sameOrigin(request)) return new NextResponse("Forbidden", { status: 403 });
+10
View File
@@ -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");
+13
View File
@@ -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}`;
}