import "server-only"; import { callMobileApi } from "@/app/lib/server/mobileApi"; import { readSession, rewriteSessionWithToken, sessionAbsoluteTtlSeconds, } from "@/app/lib/server/session"; import { tokenExpirySeconds } from "@/app/lib/sessionCodec"; // Sliding admin session (openspec/changes/add-admin-login-security): an active admin's token is // refreshed near expiry through the existing services-auth /auth/refreshToken (proxied by // mobile-api), up to a configurable absolute cap. Idle and absolute limits are configuration // (SESSION_IDLE_TTL / SESSION_ABSOLUTE_TTL, see session.ts); this module only decides WHEN to // refresh. /** Refresh when the token has this many seconds (or fewer) of life left. */ export function refreshGraceSeconds(): number { const raw = process.env.SESSION_REFRESH_GRACE; const parsed = raw ? Number(raw) : NaN; return Number.isFinite(parsed) && parsed >= 0 ? parsed : 300; // 5 minutes } function nowSeconds(): number { return Math.floor(Date.now() / 1000); } export type RefreshOutcome = | { refreshed: true; token: string } | { refreshed: false; reason: "no-session" | "not-due" | "absolute-cap" | "upstream-unavailable" }; /** * Refreshes the session cookie when the token is near expiry and the absolute cap has not been * reached. Returns the outcome; callers (e.g. the session-hydration route) use it only to know * whether the cookie was rewritten — a refusal is never an error. */ export async function maybeRefreshSession(): Promise { const session = await readSession(); if (!session) return { refreshed: false, reason: "no-session" }; const expiry = tokenExpirySeconds(session.token); if (expiry == null) return { refreshed: false, reason: "not-due" }; const now = nowSeconds(); const remaining = expiry - now; if (remaining > refreshGraceSeconds()) { return { refreshed: false, reason: "not-due" }; } // Absolute cap: the sliding session must stop here, even if the current token still has life. // A legacy cookie without a recorded cap gets one from the configured absolute TTL. const cap = session.absoluteExpiry ?? now + sessionAbsoluteTtlSeconds(); if (now >= cap) { return { refreshed: false, reason: "absolute-cap" }; } const result = await callMobileApi<{ token?: string | null }>("/api/admin/auth/refresh", { method: "POST", token: session.token, }); if (!result.ok || !result.data?.token) { return { refreshed: false, reason: "upstream-unavailable" }; } await rewriteSessionWithToken(result.data.token, session); return { refreshed: true, token: result.data.token }; }