import "server-only"; import { headers } from "next/headers"; import { redirect } from "next/navigation"; import { getSession, verifyCsrf, type SessionUser } from "./session"; export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } } /** Route handlers: 401 without session, 403 if MFA pending or password change required; mutating requests need same-origin + CSRF header. */ export async function requireUser(req?: Request): Promise { const s = await getSession(); if (!s) throw new HttpError(401, "Unauthenticated"); if (s.totpEnabled && !s.mfaPassed) throw new HttpError(403, "MFA required"); if (req && !["GET", "HEAD", "OPTIONS"].includes(req.method)) { await assertSameOrigin(); if (!verifyCsrf(s, req.headers.get("x-csrf-token"))) throw new HttpError(403, "CSRF token invalid"); } return s; } export async function requireUserPage(): Promise { const s = await getSession(); if (!s) redirect("/login"); if (s.totpEnabled && !s.mfaPassed) redirect("/login?step=totp"); if (s.mustChangePassword && !((await headers()).get("x-pathname") ?? "").startsWith("/admin/settings")) redirect("/admin/settings?must_change=1"); return s; } export async function assertSameOrigin() { const h = await headers(); const sfs = h.get("sec-fetch-site"); if (sfs && sfs !== "same-origin" && sfs !== "none") throw new HttpError(403, "Cross-site request blocked"); const origin = h.get("origin"); if (origin) { const host = h.get("x-forwarded-host") ?? h.get("host"); const allowed = new Set([process.env.APP_URL?.replace(/\/$/, ""), `https://${host}`, `http://${host}`].filter(Boolean)); if (!allowed.has(origin)) throw new HttpError(403, "Origin mismatch"); } } export function jsonError(e: unknown) { if (e instanceof HttpError) return Response.json({ error: e.message }, { status: e.status }); if (e && typeof e === "object" && "issues" in e) return Response.json({ error: "Validation failed", issues: (e as any).issues }, { status: 400 }); console.error(e); return Response.json({ error: "Internal error" }, { status: 500 }); }