import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() })); vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); import { getSessionPolicy, cachedSessionPolicy, resetSessionPolicyCache } from "./sessionPolicy"; beforeEach(() => { resetSessionPolicyCache(); mocks.callMobileApi.mockReset(); vi.useFakeTimers(); vi.setSystemTime(new Date("2026-11-20T00:00:00Z")); delete process.env.SESSION_IDLE_TTL; delete process.env.SESSION_ABSOLUTE_TTL; }); afterEach(() => vi.useRealTimers()); describe("session policy (enforce-session-timeouts)", () => { it("reads the saved admin limits with the caller's token", async () => { mocks.callMobileApi.mockResolvedValue({ ok: true, data: { idleTtlSeconds: 900, absoluteTtlSeconds: 7200 } }); expect(await getSessionPolicy("jwt")).toEqual({ idleTtlSeconds: 900, absoluteTtlSeconds: 7200 }); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/session-policy", { token: "jwt" }); }); it("caches for 60 seconds, then reads again", async () => { mocks.callMobileApi.mockResolvedValue({ ok: true, data: { idleTtlSeconds: 900, absoluteTtlSeconds: 7200 } }); await getSessionPolicy("jwt"); vi.advanceTimersByTime(59_000); await getSessionPolicy("jwt"); expect(mocks.callMobileApi).toHaveBeenCalledTimes(1); vi.advanceTimersByTime(2_000); await getSessionPolicy("jwt"); expect(mocks.callMobileApi).toHaveBeenCalledTimes(2); }); it("falls back to the env values when the policy cannot be read", async () => { process.env.SESSION_IDLE_TTL = "1200"; process.env.SESSION_ABSOLUTE_TTL = "3600"; mocks.callMobileApi.mockResolvedValue({ ok: false, status: 503 }); expect(await getSessionPolicy("jwt")).toEqual({ idleTtlSeconds: 1200, absoluteTtlSeconds: 3600 }); }); it("ignores a malformed answer", async () => { mocks.callMobileApi.mockResolvedValue({ ok: true, data: { idleTtlSeconds: "x", absoluteTtlSeconds: -1 } }); expect(await getSessionPolicy("jwt")).toEqual({ idleTtlSeconds: 3600, absoluteTtlSeconds: 28800 }); }); it("cachedSessionPolicy never calls out: the last good value, else the env values", async () => { expect(cachedSessionPolicy()).toEqual({ idleTtlSeconds: 3600, absoluteTtlSeconds: 28800 }); mocks.callMobileApi.mockResolvedValue({ ok: true, data: { idleTtlSeconds: 900, absoluteTtlSeconds: 7200 } }); await getSessionPolicy("jwt"); expect(cachedSessionPolicy()).toEqual({ idleTtlSeconds: 900, absoluteTtlSeconds: 7200 }); expect(mocks.callMobileApi).toHaveBeenCalledTimes(1); }); });