import "server-only"; import { cookies } from "next/headers"; import { sessionEnded, tokenExpirySeconds, type SessionData } from "@/app/lib/sessionCodec"; import { cachedSessionPolicy, sessionIdleTtlSeconds } from "@/app/lib/server/sessionPolicy"; // sign-session-cookies (F32): the cookie is signed, so its flags and absolute cap cannot be edited. import { sealSession, openSession } from "@/app/lib/sessionSeal"; import { sessionCookieName } from "@/app/lib/sessionCookieName"; // The env fallbacks now live with the saved policy (enforce-session-timeouts); re-exported for existing callers. export { sessionIdleTtlSeconds, sessionAbsoluteTtlSeconds } from "@/app/lib/server/sessionPolicy"; function nowSeconds(): number { return Math.floor(Date.now() / 1000); } /** * The cookie maxAge, derived from the JWT's own expiry so the cookie never outlives the token * it carries (closing the old 1h-token / 8h-cookie mismatch). Falls back to the configured idle * TTL only when the token's exp cannot be read. */ function maxAgeFromToken(token: string): number { const exp = tokenExpirySeconds(token); if (exp == null) return sessionIdleTtlSeconds(); return Math.max(1, exp - nowSeconds()); } export async function setSession( token: string, resetPasswordRequired = false, absoluteExpiry?: number, ): Promise { // A fresh session gets a fresh cap unless the caller (e.g. a rewrite path) supplies one; the sliding refresh must // stop at this deadline. enforce-session-timeouts: it also records sign-in and activity times and the idle limit, // from the last saved policy this process read (keepalive, called on the first page, brings it up to date). const now = nowSeconds(); const policy = cachedSessionPolicy(); await writeSession({ token, resetPasswordRequired, absoluteExpiry: absoluteExpiry ?? now + policy.absoluteTtlSeconds, signedInAt: now, lastActivity: now, idleTtl: policy.idleTtlSeconds, }); } /** Seals `data` into the session cookie; maxAge follows the token's own expiry. */ export async function writeSession(data: SessionData): Promise { const store = await cookies(); store.set(sessionCookieName(), await sealSession(data), { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: maxAgeFromToken(data.token), }); } /** The signed-in session, or null when there is none or it is past its idle limit or cap (enforce-session-timeouts). */ export async function readSession(): Promise { const store = await cookies(); const session = await openSession(store.get(sessionCookieName())?.value); return session && !sessionEnded(session, nowSeconds()) ? session : null; } export async function getToken(): Promise { return (await readSession())?.token ?? null; } export async function clearSession(): Promise { const store = await cookies(); // A browser ignores a __Host- cookie deletion that lacks Secure and Path=/, so expire it with the same attributes. store.set(sessionCookieName(), "", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 0 }); } /** Absolute session cap for a fresh session: now + configured absolute TTL. */ export async function newAbsoluteExpiry(): Promise { return nowSeconds() + cachedSessionPolicy().absoluteTtlSeconds; } /** * Rewrites the session cookie with a refreshed token, preserving the reset-flag and the absolute * cap (the sliding session never moves its absolute deadline). maxAge is re-derived from the new * token's exp, keeping cookie and token aligned after every refresh. */ export async function rewriteSessionWithToken(token: string, session: SessionData): Promise { // Every other field (reset flag, cap, sign-in and activity times, idle limit) carries over unchanged. await writeSession({ ...session, token }); }