import "server-only"; import { callMobileApi } from "@/app/lib/server/mobileApi"; import { clearSession, readSession, writeSession } from "@/app/lib/server/session"; import { getSessionPolicy } from "@/app/lib/server/sessionPolicy"; import { endReplacedSession, isSessionReplaced } from "@/app/lib/server/signedInElsewhere"; import { refreshGraceSeconds } from "@/app/lib/server/sessionRefresh"; import { sessionEnded, tokenExpirySeconds, type SessionData } from "@/app/lib/sessionCodec"; // enforce-session-timeouts: the browser checks in once a minute (and on the first input in a minute). This is where // the saved idle limit and cap reach an open session, where activity is recorded, and where an active admin's token // is renewed without a page reload. A session that has ended is cleared. function nowSeconds(): number { return Math.floor(Date.now() / 1000); } /** * Applies the saved policy to the current session. `active` is true only when the browser saw a click, tap or key * press since its last call. Returns false (and clears the cookie) when there is no session or it has ended. */ export async function keepSessionAlive(active: boolean): Promise { const session = await readSession(); if (!session) { await clearSession(); return false; } const now = nowSeconds(); const policy = await getSessionPolicy(session.token); // A cookie from before this change has no times: it starts counting now. const signedInAt = session.signedInAt ?? now; const next: SessionData = { ...session, signedInAt, lastActivity: active ? now : (session.lastActivity ?? now), idleTtl: policy.idleTtlSeconds, absoluteExpiry: signedInAt + policy.absoluteTtlSeconds, }; // The saved limits may be lower than the ones the cookie was written with. if (sessionEnded(next, now)) { await clearSession(); return false; } // one-session-per-account: on a click, ask whether the session is still live, so one ended by a sign-in elsewhere // (or revoked another way) is noticed even when the click itself loads nothing. Unreachable: keep going. if (active) { const check = await callMobileApi("/api/admin/auth/session", { token: next.token }); if (isSessionReplaced(check)) { await endReplacedSession(); return false; } if (!check.ok && check.status === 401) { await clearSession(); return false; } } const expiry = tokenExpirySeconds(next.token); if (expiry != null && expiry - now <= refreshGraceSeconds()) { const result = await callMobileApi<{ token?: string | null }>("/api/admin/auth/refresh", { method: "POST", token: next.token, }); if (result.ok && result.data?.token) { next.token = result.data.token; } else if (isSessionReplaced(result)) { // one-session-per-account: renewal refused because the account signed in elsewhere. await endReplacedSession(); return false; } else if (expiry <= now) { await clearSession(); return false; } } await writeSession(next); return true; }