import { cookies } from "next/headers"; import { ACTIVE_SITE_COOKIE_MAX_AGE, isStorableActiveSite } from "../../lib/activeSite"; import { activeSiteCookieForRequest } from "../../lib/activeSiteServer"; export const dynamic = "force-dynamic"; // THE COOKIE'S WRITER BEFORE A NAVIGATION (see app/lib/activeSite.ts): POST // `{ value }` from SiteScopeProvider when the picker moves the URL after the // choice (a site's own page, a `?site=` link's) answers `{ ok }`. A page that // stays writes through setActiveSiteAction, whose answer re-renders it. // // NOT A SERVER ACTION HERE (release 29 D1). A cookie set in a server action // makes Next re-render the page in the action's answer and apply it through // the router — answered BEFORE that applies, so the navigation the picker // made next discarded the pending action and replayed it as a refresh after // the push, and when React committed the two together the push's history // entry was written as a replace (Back skipped the page the choice was made // on: site-scope.spec). The route only writes; the picker refreshes once the // new URL has committed (the client cache is not cleared by a route). // // Same-origin only (a cross-site page could otherwise flip an operator's // scope): JSON, and an Origin, when sent, that is this host. The value is only // SHAPE-checked (a site id or "__all__"): whether it names a configured site is // decided at every read, so a site deleted later resolves as no selection. export async function POST(request: Request): Promise { const origin = request.headers.get("origin"); // The host the browser addressed: a proxy's X-Forwarded-Host first, as // Next's own server-action origin check reads it. const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host"); if (origin !== null && (() => { try { return new URL(origin).host !== host; } catch { return true; } })()) { return Response.json({ ok: false, error: "cross-origin" }, { status: 403 }); } if (!(request.headers.get("content-type") ?? "").startsWith("application/json")) { return Response.json({ ok: false, error: "expected JSON" }, { status: 415 }); } const body = (await request.json().catch(() => null)) as { value?: unknown } | null; const value = body?.value; if (typeof value !== "string" || !isStorableActiveSite(value)) { return Response.json({ ok: false, error: "not a site id or __all__" }, { status: 400 }); } const name = await activeSiteCookieForRequest(); (await cookies()).set(name, value, { path: "/", sameSite: "lax", maxAge: ACTIVE_SITE_COOKIE_MAX_AGE, // Only the server reads it: the page gets it through the layout. httpOnly: true, }); return Response.json({ ok: true }, { headers: { "cache-control": "no-store" } }); }