import { StrictMode, type ReactNode } from "react"; import { act, renderHook, waitFor } from "@testing-library/react"; import { afterEach, expect, test, vi } from "vitest"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { z } from "zod"; import { PlatformProvider, usePlatform } from "../src/lib/platform"; import { useIdempotentCommand } from "../src/lib/use-idempotent-command"; import { adjustmentInput, ledger } from "../src/lib/commerce"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; const me = { userId: id, organizationId: id, sessionId: id, permissions: ["users.read"], }; const session = { accessToken: "test-opaque", tokenType: "Bearer", expiresAt: new Date(Date.now() + 3600000).toISOString(), }; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); }); function harness() { localStorage.setItem("mani.organization", id); const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); return { client, ...renderHook(() => usePlatform(), { wrapper }) }; } test("private PDF responses arriving after sign-out are discarded", async () => { const pdf = "%PDF-1.7\n%%EOF"; let finish: ((response: Response) => void) | undefined; let downloadSignal: AbortSignal | null | undefined; vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => { if (url.endsWith("/auth/login")) return json(session); if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["supplier_document.read"] }); if (url.endsWith("/auth/logout")) return new Response(null, { status: 204 }); if (url.endsWith("/download")) { downloadSignal = options?.signal; return new Promise((resolve) => { finish = resolve; }); } throw new Error(`Unexpected request ${url}`); })); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password")); const pending = h.result.current.downloadPdf(id, pdf.length).catch((error) => error); await waitFor(() => expect(finish).toBeDefined()); await act(() => h.result.current.signOut()); expect(downloadSignal?.aborted).toBe(true); finish?.(new Response(pdf, { headers: { "Content-Type": "application/pdf" } })); expect(await pending).toMatchObject({ code: "SESSION_CHANGED" }); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); }); test("old-session intent callbacks cannot erase a newer session's command", async () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/logout") ? new Response(null, { status: 204 }) : json(me), ), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); const old = h.result.current; await act(() => old.signOut()); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); const next = { idempotencyKey: "new-key", cartVersion: 2 }; h.result.current.saveIntent("checkout", next); old.clearIntent("checkout", "new-key"); old.saveIntent("checkout", { idempotencyKey: "old-key" }); expect(h.result.current.getIntent("checkout")).toEqual(next); h.result.current.clearIntent("checkout", "wrong-key"); expect(h.result.current.getIntent("checkout")).toEqual(next); h.result.current.clearIntent("checkout", "new-key"); expect(h.result.current.getIntent("checkout")).toBeUndefined(); }); test("absolute expiry removes private data and pending commands", async () => { vi.useFakeTimers(); vi.stubGlobal( "fetch", vi.fn(async (url: string) => url.endsWith("/auth/login") ? json({ ...session, expiresAt: new Date(Date.now() + 60000).toISOString(), }) : json(me), ), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); h.client.setQueryData( ["private", h.result.current.scope, "/orders"], [{ private: "order" }], ); h.result.current.saveIntent("checkout", { idempotencyKey: id }); await act(async () => { vi.advanceTimersByTime(61000); }); expect(h.result.current.principal).toBeNull(); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); expect(h.result.current.getIntent("checkout")).toBeUndefined(); }); test("permission-change cancellation preserves a submitted stock command for exact replay", async () => { let principalReads = 0, finish: (response: Response) => void = () => { throw new Error("Not submitted"); }; const attempts: unknown[] = []; vi.stubGlobal( "fetch", vi.fn(async (url: string, options?: RequestInit) => { if (url.endsWith("/auth/login")) return json(session); if (url.endsWith("/auth/me")) return json({ ...me, permissions: ++principalReads === 1 ? ["users.read", "inventory.adjust"] : ["inventory.adjust"], }); if (url.endsWith("/users")) return json({ message: "Denied" }, 403); attempts.push(JSON.parse(String(options?.body))); if (attempts.length === 1) return new Promise((resolve) => { finish = resolve; }); return json({ id, delta: -1, reason: "Test", createdAt: new Date().toISOString(), }); }), ); localStorage.setItem("mani.organization", id); const client = new QueryClient(); const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); const h = renderHook( () => ({ platform: usePlatform(), command: useIdempotentCommand( "/inventory/adjustments", adjustmentInput, ledger, id, ), }), { wrapper }, ); await act(() => h.result.current.platform.signIn("staff@example.com", "test password"), ); let pending: Promise; act(() => { pending = h.result.current.command .run({ stockItemId: id, delta: -1, reason: "Test" }) .catch((error) => error); }); await act(async () => { await h.result.current.platform .request("/users", z.unknown()) .catch((error) => error); }); await act(async () => { finish( json({ id, delta: -1, reason: "Test", createdAt: new Date().toISOString(), }), ); await pending; }); expect(h.result.current.command.uncertain).toBe(true); expect( h.result.current.platform.getIntent(`/inventory/adjustments:${id}`), ).toEqual(attempts[0]); await act(() => h.result.current.command.run({ stockItemId: id, delta: 999, reason: "Changed", }), ); expect(attempts[1]).toEqual(attempts[0]); expect(h.result.current.command.uncertain).toBe(false); }); test("logout network failure clears auth and private caches immediately", async () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => { if (url.endsWith("/auth/login")) return json(session); if (url.endsWith("/auth/me")) return json(me); throw new Error("Offline"); }), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); h.client.setQueryData( ["private", id, "/addresses"], [{ private: "address" }], ); await act(async () => { await expect(h.result.current.signOut()).rejects.toThrow( "signed out locally", ); }); expect(h.result.current.principal).toBeNull(); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); }); test("authenticated 401 clears the matching session but not a later login", async () => { let finish: (response: Response) => void = () => { throw new Error("Request not started"); }; vi.stubGlobal( "fetch", vi.fn(async (url: string) => { if (url.endsWith("/auth/login")) return json(session); if (url.endsWith("/auth/me")) return json(me); return new Promise((resolve) => { finish = resolve; }); }), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); let pending: Promise; act(() => { pending = h.result.current .request("/addresses", z.array(z.unknown())) .catch((error) => error); }); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); await act(async () => { finish(json({ message: "Expired" }, 401)); await pending; }); expect(h.result.current.principal).not.toBeNull(); let denied: Promise; act(() => { denied = h.result.current .request("/addresses", z.array(z.unknown())) .catch((error) => error); }); await act(async () => { finish(json({ message: "Expired" }, 401)); await denied; }); expect(h.result.current.principal).toBeNull(); }); test("403 refreshes effective permissions without retaining the denied action", async () => { let calls = 0; vi.stubGlobal( "fetch", vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/me") ? json({ ...me, permissions: ++calls === 1 ? ["users.read"] : [] }) : json({ message: "Denied" }, 403), ), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); const oldScope = h.result.current.scope; h.client.setQueryData( ["private", oldScope, "/users"], [{ private: "staff record" }], ); await act(async () => { await expect( h.result.current.request("/users", z.array(z.unknown())), ).rejects.toThrow("Denied"); }); expect(h.result.current.can("users.read")).toBe(false); expect(h.result.current.scope).not.toBe(oldScope); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); }); test("organization change cancels private scope and removes cached data", async () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : json(me), ), ); const h = harness(); await act(() => h.result.current.signIn("staff@example.com", "test password"), ); h.client.setQueryData(["private", id, "/orders"], [{ private: "order" }]); act(() => h.result.current.setOrganization("f66c798a-f764-4b88-8d13-ace328ff1010"), ); await waitFor(() => expect(h.result.current.scope).toBe("")); expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]); });