import { SignJWT, jwtVerify } from "jose"; import { cookies } from "next/headers"; const secret = () => new TextEncoder().encode(process.env.SESSION_SECRET || "development-only-change-me"); export type Session = { id: number; username: string; role: string }; export async function createSession(user: Session) { const token = await new SignJWT(user).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("7d").sign(secret()); (await cookies()).set("hub_session", token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 604800 }); } export async function getSession(): Promise { const token = (await cookies()).get("hub_session")?.value; if (!token) return null; try { return (await jwtVerify(token, secret())).payload as unknown as Session; } catch { return null; } } export async function requireUser() { const user = await getSession(); if (!user) throw new Error("Unauthorized"); return user; } export async function clearSession() { (await cookies()).delete("hub_session"); }