import { NextRequest, NextResponse } from "next/server"; /** * Mirrors proxy.ts in nachklang-feedback (and the gate in nachklang-admin and * nachklang-tickets) - keep them in step. * * A *convenience* gate, not a security boundary: it only checks that a session * cookie exists, so a forged value gets past it. That is fine - the API checks * every request, and the calendar's write routes sit behind * requireAppAccess('calendar'). What this buys is that a signed-out visitor * lands on the sign-in page straight away instead of on an admin shell that * flashes and then redirects. * * Only the cookie's *presence* is readable: it is httpOnly and set by the API * on another host. Cookies are scoped by host, not port, so in dev the cookie * the API sets for localhost:3000 is visible here on localhost:4200 too. This * gate cannot see permissions either - a signed-in colleague without calendar * access passes it and is stopped by the admin layout's /me call. */ // better-auth prefixes the cookie with `__Secure-` when it sets Secure, which // it does in production. Dev runs over http and gets the plain name // (confirmed against a local API on 2026-09-28). const SESSION_COOKIES = ["__Secure-nachklang.session_token", "nachklang.session_token"]; /** * A `?redirect=` value we are willing to follow *within this app*, or the admin * start page. Only a single-slash absolute path qualifies: "//evil.example" and * "/\\evil.example" are read by browsers as protocol-relative URLs to another * host. Cross-origin targets are the admin app's business - it validates them * against its own allow-list. */ const internalTarget = (raw: string | null): string => { if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) { return "/admin"; } return raw; }; export function proxy(req: NextRequest) { const { pathname, search } = req.nextUrl; const signedIn = SESSION_COOKIES.some((name) => req.cookies.has(name)); // The forwarder page, which is where this redirects to. Someone who already // has a cookie has almost certainly arrived from a bookmark; sending them on // to the admin app would ask them to sign in again for nothing. if (pathname === "/admin/login") { if (!signedIn) { return NextResponse.next(); } return NextResponse.redirect(new URL(internalTarget(req.nextUrl.searchParams.get("redirect")), req.url)); } if (!signedIn) { const loginUrl = new URL("/admin/login", req.url); loginUrl.searchParams.set("redirect", `${pathname}${search}`); return NextResponse.redirect(loginUrl); } return NextResponse.next(); } export const config = { matcher: ["/admin/:path*"], };