import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextResponse } from "next/server"; const h = vi.hoisted(() => ({ set: vi.fn() })); vi.mock("next/headers", () => ({ cookies: async () => ({ set: h.set, get: () => undefined }) })); import { isSessionReplaced, markReplacedOn, clearMarkerOn, endReplacedSession } from "./signedInElsewhere"; import { SIGNED_IN_ELSEWHERE_COOKIE } from "@/app/lib/signedInElsewhere"; import { sessionCookieName } from "@/app/lib/sessionCookieName"; beforeEach(() => h.set.mockReset()); describe("isSessionReplaced", () => { it("is true only for mobile-api's 401 SESSION_REPLACED", () => { expect(isSessionReplaced({ ok: false, error: "x", status: 401, code: "SESSION_REPLACED" })).toBe(true); expect(isSessionReplaced({ ok: false, error: "x", status: 401 })).toBe(false); expect(isSessionReplaced({ ok: false, error: "x", status: 403, code: "SESSION_REPLACED" })).toBe(false); expect(isSessionReplaced({ ok: true, data: null })).toBe(false); }); }); describe("markReplacedOn", () => { it("clears the session cookie and sets the marker for five minutes", () => { const res = markReplacedOn(NextResponse.json({}, { status: 401 })); const session = res.cookies.get(sessionCookieName()); const marker = res.cookies.get(SIGNED_IN_ELSEWHERE_COOKIE); expect(session?.value).toBe(""); expect(marker?.value).toBe("1"); const setCookie = res.headers.getSetCookie().join("\n"); expect(setCookie).toMatch(new RegExp(`${SIGNED_IN_ELSEWHERE_COOKIE}=1;[^\\n]*Max-Age=300`)); expect(setCookie).toMatch(new RegExp(`${SIGNED_IN_ELSEWHERE_COOKIE}=1;[^\\n]*Secure`)); }); }); describe("clearMarkerOn", () => { it("expires the marker", () => { const res = clearMarkerOn(NextResponse.json({})); expect(res.headers.getSetCookie().join("\n")).toMatch(new RegExp(`${SIGNED_IN_ELSEWHERE_COOKIE}=;[^\\n]*Max-Age=0`)); }); }); describe("endReplacedSession", () => { it("clears the session cookie and sets the marker", async () => { await endReplacedSession(); expect(h.set).toHaveBeenCalledWith(sessionCookieName(), "", expect.objectContaining({ maxAge: 0 })); expect(h.set).toHaveBeenCalledWith(SIGNED_IN_ELSEWHERE_COOKIE, "1", expect.objectContaining({ maxAge: 300, secure: true })); }); });