import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; // host-prefixed-session-cookie (F29): the session cookie is host-only (`__Host-`), so no sibling host can set it. const h = vi.hoisted(() => { const store = new Map(); const setSpy = vi.fn(); return { store, setSpy }; }); vi.mock("next/headers", () => ({ cookies: async () => ({ get: (n: string) => (h.store.has(n) ? { name: n, value: h.store.get(n)! } : undefined), set: (name: string, value: string, opts: unknown) => { h.store.set(name, value); h.setSpy(name, value, opts); }, delete: (n: string) => { h.store.delete(n); }, }), })); import { setSession, readSession, clearSession } from "./session"; import { sealSession } from "@/app/lib/sessionSeal"; import { sessionCookieName } from "@/app/lib/sessionCookieName"; const saved = process.env.SESSION_COOKIE_NAME; beforeEach(() => { h.store.clear(); h.setSpy.mockClear(); delete process.env.SESSION_COOKIE_NAME; }); afterEach(() => { if (saved === undefined) delete process.env.SESSION_COOKIE_NAME; else process.env.SESSION_COOKIE_NAME = saved; }); describe("host-prefixed session cookie", () => { it("names the cookie __Host-bb_admin by default", () => { expect(sessionCookieName()).toBe("__Host-bb_admin"); }); it("prefixes a configured base name exactly once", () => { process.env.SESSION_COOKIE_NAME = "bb_x"; expect(sessionCookieName()).toBe("__Host-bb_x"); process.env.SESSION_COOKIE_NAME = "__Host-bb_x"; expect(sessionCookieName()).toBe("__Host-bb_x"); }); it("sets the prefixed cookie Secure, Path=/ and without a Domain", async () => { await setSession("jwt-xyz"); const [name, , opts] = h.setSpy.mock.calls[0]; expect(name).toBe("__Host-bb_admin"); expect(opts).toMatchObject({ secure: true, path: "/" }); expect(opts).not.toHaveProperty("domain"); }); it("ignores a valid signed cookie under the old un-prefixed name", async () => { h.store.set("bb_admin", await sealSession({ token: "jwt", resetPasswordRequired: false, absoluteExpiry: 4102444800 })); expect(await readSession()).toBeNull(); }); it("expires the cookie on sign-out with Secure and Path=/ (a browser ignores a __Host- deletion without them)", async () => { await setSession("jwt-xyz"); h.setSpy.mockClear(); await clearSession(); expect(h.setSpy).toHaveBeenCalledWith("__Host-bb_admin", "", expect.objectContaining({ secure: true, path: "/", maxAge: 0 })); expect(await readSession()).toBeNull(); }); });