import "server-only"; import { cookies, headers } from "next/headers"; import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { and, eq, gt, isNull, ne } from "drizzle-orm"; import { db, schema } from "@/db"; import { cache } from "react"; export const COOKIE = process.env.NODE_ENV === "production" ? "__Host-tools_session" : "tools_session"; const IDLE_DAYS = 14, ABS_DAYS = 30, ROTATE_HOURS = 12; const sha = (s: string) => createHash("sha256").update(s).digest("hex"); export function clientIp(h: Headers) { return (h.get("x-forwarded-for")?.split(",")[0] ?? h.get("x-real-ip") ?? "0.0.0.0").trim(); } const cookieOpts = { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict" as const, path: "/" }; export async function createSession(userId: string, opts: { mfaPassed?: boolean } = {}) { const token = randomBytes(32).toString("base64url"); const h = await headers(); const now = Date.now(); await db.insert(schema.sessions).values({ userId, tokenHash: sha(token), csrfSecret: randomBytes(32).toString("base64url"), userAgent: h.get("user-agent")?.slice(0, 300) ?? null, ip: clientIp(h), expiresAt: new Date(now + IDLE_DAYS * 864e5), absoluteExpiresAt: new Date(now + ABS_DAYS * 864e5), mfaPassed: opts.mfaPassed ?? false }); return token; } export async function setSessionCookie(token: string) { (await cookies()).set(COOKIE, token, { ...cookieOpts, maxAge: ABS_DAYS * 86400 }); } export async function clearSessionCookie() { (await cookies()).set(COOKIE, "", { ...cookieOpts, maxAge: 0 }); } export type SessionUser = { id: string; email: string; displayName: string; role: string; totpEnabled: boolean; mustChangePassword: boolean; sessionId: string; mfaPassed: boolean; csrfSecret: string }; export const getSession = cache(async (): Promise => { const token = (await cookies()).get(COOKIE)?.value; if (!token) return null; const now = new Date(); const rows = await db.select({ s: schema.sessions, u: schema.users }).from(schema.sessions).innerJoin(schema.users, eq(schema.users.id, schema.sessions.userId)) .where(and(eq(schema.sessions.tokenHash, sha(token)), isNull(schema.sessions.revokedAt), gt(schema.sessions.expiresAt, now), gt(schema.sessions.absoluteExpiresAt, now))).limit(1); if (!rows.length) return null; const { s, u } = rows[0]; if (now.getTime() - s.lastSeenAt.getTime() > 5 * 60_000) db.update(schema.sessions).set({ lastSeenAt: now, expiresAt: new Date(now.getTime() + IDLE_DAYS * 864e5) }).where(eq(schema.sessions.id, s.id)).catch(() => {}); return { id: u.id, email: u.email, displayName: u.displayName, role: u.role, totpEnabled: u.totpEnabled, mustChangePassword: u.mustChangePassword, sessionId: s.id, mfaPassed: s.mfaPassed, csrfSecret: s.csrfSecret }; }); /** Rotate the session token (after login step-up or every ROTATE_HOURS). Returns the new token to set. */ export async function rotateSession(sessionId: string): Promise { const token = randomBytes(32).toString("base64url"); await db.update(schema.sessions).set({ tokenHash: sha(token), rotatedAt: new Date() }).where(eq(schema.sessions.id, sessionId)); return token; } export async function maybeRotate(s: SessionUser) { const [row] = await db.select({ rotatedAt: schema.sessions.rotatedAt }).from(schema.sessions).where(eq(schema.sessions.id, s.sessionId)); if (row && Date.now() - row.rotatedAt.getTime() > ROTATE_HOURS * 3600e3) { const t = await rotateSession(s.sessionId); await setSessionCookie(t); } } export async function markMfaPassed(sessionId: string) { await db.update(schema.sessions).set({ mfaPassed: true }).where(eq(schema.sessions.id, sessionId)); } export async function revokeSession(sessionId: string) { await db.update(schema.sessions).set({ revokedAt: new Date() }).where(eq(schema.sessions.id, sessionId)); } export async function revokeOtherSessions(userId: string, keep: string) { await db.update(schema.sessions).set({ revokedAt: new Date() }).where(and(eq(schema.sessions.userId, userId), isNull(schema.sessions.revokedAt), ne(schema.sessions.id, keep))); } /** CSRF: double-submit token derived from the per-session secret (HMAC with SESSION_SECRET). */ export function csrfToken(s: SessionUser) { return createHmac("sha256", process.env.SESSION_SECRET ?? "dev").update(s.csrfSecret).digest("base64url"); } export function verifyCsrf(s: SessionUser, token: string | null | undefined) { if (!token) return false; const a = Buffer.from(csrfToken(s)); const b = Buffer.from(token); return a.length === b.length && timingSafeEqual(a, b); }