import { describe, expect, test } from "vitest"; import { screen, waitFor } from "@testing-library/react"; import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts"; import { calls, fail, route } from "../fetch.ts"; import { makeSession, page, wire } from "../fixtures.ts"; import { currentPath, renderPage } from "../render.tsx"; /** Opens the callback, in a tab that started the sign-in of state `s`. */ function open(query: string, started = "s") { sessionStorage.setItem("federationState", started); renderPage(`/federation/callback${query}`); } describe("FederationCallback", () => { test("finishes the sign-in once and lands home signed in", async () => { route( "POST /api/federation/sessions", () => wire(makeSession({ username: "alice@home.example" })), ); route("GET /api/dumps", () => page([])); open("?code=c&state=s&iss=https%3A%2F%2Fhome.example"); await waitFor(() => expect(currentPath()).toBe("/")); expect(calls("POST /api/federation/sessions").map((c) => c.body)).toEqual( [{ code: "c", state: "s" }], ); expect(JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY)!).user.username) .toBe("alice@home.example"); }); test("a refusal is shown, with the way back", async () => { route( "POST /api/federation/sessions", () => fail("This sign-in has expired, start again"), ); open("?code=c&state=s"); expect(await screen.findByText("This sign-in has expired, start again")) .toBeInTheDocument(); expect(screen.getByRole("link", { name: "Back to the login page" })) .toHaveAttribute("href", "/login"); }); test("a sign-in this tab didn't start is refused", async () => { open("?code=c&state=theirs"); expect( await screen.findByText( "This sign-in was started elsewhere. Start again from the login page.", ), ).toBeInTheDocument(); expect(calls("POST /api/federation/sessions")).toHaveLength(0); }); test("a link without its code says so", async () => { open("?state=s"); expect(await screen.findByText("This sign-in link is incomplete.")) .toBeInTheDocument(); expect(calls("POST /api/federation/sessions")).toHaveLength(0); }); });