// Author: Simon-Pierre Boucher // Contact: contact@spboucher.ai // Project: chat.spboucher.ai import { cookies, headers } from "next/headers"; import { NextResponse } from "next/server"; import { getSession, SESSION_COOKIE, type SessionInfo } from "./auth"; /** DB-backed session check for route handlers and server components. */ export async function currentSession(): Promise { const jar = await cookies(); return getSession(jar.get(SESSION_COOKIE)?.value); } /** Returns the session or a ready-to-return 401 response. Every /api route uses this. */ export async function requireSession(): Promise< { session: SessionInfo; unauthorized: null } | { session: null; unauthorized: NextResponse } > { const session = await currentSession(); if (!session) { return { session: null, unauthorized: NextResponse.json({ error: "Unauthorized" }, { status: 401 }), }; } return { session, unauthorized: null }; } /** Client IP, trusting X-Forwarded-For from the ngrok tunnel. */ export async function clientIp(): Promise { const h = await headers(); const xff = h.get("x-forwarded-for"); if (xff) return xff.split(",")[0].trim(); return h.get("x-real-ip") ?? "unknown"; }