spb/tools-spboucher-ai
Public
1import "server-only";2import { headers } from "next/headers";3import { redirect } from "next/navigation";4import { getSession, verifyCsrf, type SessionUser } from "./session";56export class HttpError extends Error { constructor(public status: number, message: string) { super(message); } }78/** Route handlers: 401 without session, 403 if MFA pending or password change required; mutating requests need same-origin + CSRF header. */9export async function requireUser(req?: Request): Promise<SessionUser> {10 const s = await getSession(); if (!s) throw new HttpError(401, "Unauthenticated");11 if (s.totpEnabled && !s.mfaPassed) throw new HttpError(403, "MFA required");12 if (req && !["GET", "HEAD", "OPTIONS"].includes(req.method)) {13 await assertSameOrigin();14 if (!verifyCsrf(s, req.headers.get("x-csrf-token"))) throw new HttpError(403, "CSRF token invalid");15 }16 return s;17}18export async function requireUserPage(): Promise<SessionUser> {19 const s = await getSession(); if (!s) redirect("/login");20 if (s.totpEnabled && !s.mfaPassed) redirect("/login?step=totp");21 if (s.mustChangePassword && !((await headers()).get("x-pathname") ?? "").startsWith("/admin/settings")) redirect("/admin/settings?must_change=1");22 return s;23}24export async function assertSameOrigin() {25 const h = await headers();26 const sfs = h.get("sec-fetch-site");27 if (sfs && sfs !== "same-origin" && sfs !== "none") throw new HttpError(403, "Cross-site request blocked");28 const origin = h.get("origin");29 if (origin) {30 const host = h.get("x-forwarded-host") ?? h.get("host");31 const allowed = new Set([process.env.APP_URL?.replace(/\/$/, ""), `https://${host}`, `http://${host}`].filter(Boolean));32 if (!allowed.has(origin)) throw new HttpError(403, "Origin mismatch");33 }34}35export function jsonError(e: unknown) {36 if (e instanceof HttpError) return Response.json({ error: e.message }, { status: e.status });37 if (e && typeof e === "object" && "issues" in e) return Response.json({ error: "Validation failed", issues: (e as any).issues }, { status: 400 });38 console.error(e);39 return Response.json({ error: "Internal error" }, { status: 500 });40}41