#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import {
UIProvider,
useUI,
type LinkModalMode,
} from "@editor/portal/contexts/UIContext";
import { PortalTestProviders } from "@editor/portal/test/TestQueryProvider";
import { HttpError } from "@editor/portal/api/http";
import { readPendingConnect } from "@editor/portal/auth/pendingConnect";
/** The step machine: what drives each step, and what must not skip or repeat one. */
const { startConnect, startReauth, fetchWallet, EMAIL } = vi.hoisted(() => ({
startConnect: vi.fn(),
startReauth: vi.fn(),
fetchWallet: vi.fn(),
EMAIL: "[email protected]",
}));
vi.mock("@processor/hooks/useFreeTierBalance", () => ({
useFreeTierBalance: () => ({
data: {
grantUnits: 500,
remainingUnits: 0,
periodEnd: "2026-10-01T00:00:00",
},
}),
}));
vi.mock("@editor/ui", async () => ({
...(await import("@editor/ui/Button")),
...(await import("@editor/ui/Banner")),
...(await import("@editor/ui/Modal")),
...(await import("@editor/ui/Skeleton")),
...(await import("@editor/ui/Spinner")),
}));
vi.mock("@editor/portal/api/link", () => ({ startConnect, startReauth }));
vi.mock("@editor/portal/api/billing", () => ({ fetchWallet }));
vi.mock("@editor/portal/auth/saasSupabase", () => ({
isSaasSupabaseConfigured: true,
// Step 3 reads the connected account's email off this session.
ensureSaasSupabase: () => ({
auth: {
onAuthStateChange: () => ({
data: { subscription: { unsubscribe: () => {} } },
}),
getSession: () =>
Promise.resolve({ data: { session: { user: { email: EMAIL } } } }),
},
}),
}));
import {
clearAccountLinkBlock,
reportFreeTierExhausted,
} from "@editor/services/accountLinkBlock";
import {
LinkAccountModal,
LinkAccountModalHost,
} from "@editor/portal/components/account-link/LinkAccountModal";
import type { ConnectOutcome } from "@editor/portal/components/account-link/ConnectCallbackView";
import { freeWallet } from "@editor/portal/components/billing/walletFixtures";
const ownership = vi.hoisted(() => ({ isAdmin: true, orgOwner: true }));
vi.mock("@editor/auth", () => ({
useAuth: () => ({
...ownership,
user: { orgOwner: ownership.orgOwner },
loading: false,
}),
}));
function HostedModal() {
const { openLinkModal } = useUI();
return (
<>
<button onClick={() => openLinkModal("reauth")}>
Open billing renewal
</button>
<LinkAccountModalHost />
</>
);
}
const AUTHORIZE = "http://localhost:5174/link?request=req-1";
const deployment = vi.hoisted(() => ({ basePath: "" }));
vi.mock("@editor/constants/app", async (importOriginal) => ({
...(await importOriginal<typeof import("@editor/constants/app")>()),
withBasePath: (path: string) => `${deployment.basePath}${path}`,
}));
const BENEFITS = "Add more users with a paid Team plan";
const GHOST = /Opening Stirling sign-in/;
const CONNECT = /Connect Stirling account/;
function renderModal(
mode?: LinkModalMode,
outcome: ConnectOutcome | null = null,
entry = "/processor/usage",
) {
return render(
<PortalTestProviders>
<MemoryRouter initialEntries={[entry]}>
<UIProvider>
<LinkAccountModal
open
onClose={() => {}}
mode={mode}
outcome={outcome}
/>
</UIProvider>
</MemoryRouter>
</PortalTestProviders>,
);
}
function click(label: string | RegExp) {
act(() => screen.getByRole("button", { name: label }).click());
}
/** Read off the body because the dialog portals out; the badge itself is uninterpolated here. */
function filledSteps(): number {
return document.body.querySelectorAll(
".portal-stepmodal__progress .is-filled",
).length;
}
describe("LinkAccountModal", () => {
let assign: ReturnType<typeof vi.fn>;
it("omits pipeline controls for a banner prompt even after a pipeline failure", () => {
clearAccountLinkBlock();
reportFreeTierExhausted({
pipelineId: "rotate",
trigger: "upload",
});
renderModal("exhausted");
expect(screen.getByRole("dialog")).toBeTruthy();
expect(screen.queryByText("Active pipelines")).toBeNull();
expect(
screen.queryByRole("button", { name: "Open pipeline settings" }),
).toBeNull();
clearAccountLinkBlock();
});
it("returns keyboard focus to the trigger when the dialog unmounts", () => {
const trigger = document.createElement("button");
document.body.append(trigger);
trigger.focus();
const view = renderModal("exhausted");
view.unmount();
expect(document.activeElement).toBe(trigger);
trigger.remove();
});
beforeEach(() => {
vi.clearAllMocks();
ownership.isAdmin = true;
ownership.orgOwner = true;
sessionStorage.clear();
localStorage.setItem("stirling.portalSaasOwner", "owner");
deployment.basePath = "";
fetchWallet.mockResolvedValue(freeWallet);
startConnect.mockResolvedValue({
phase: "PENDING",
authorizeUrl: AUTHORIZE,
secondsRemaining: 900,
teamId: null,
});
startReauth.mockResolvedValue({
phase: "PENDING",
authorizeUrl: AUTHORIZE,
secondsRemaining: 900,
teamId: null,
});
assign = vi.fn();
Object.defineProperty(window, "location", {
configurable: true,
value: {
origin: "http://localhost:5173",
hostname: "localhost",
pathname: "/processor/pipelines",
href: "http://localhost:5173/app",
search: "",
assign,
},
});
});
it.each([
{ isAdmin: true, orgOwner: false },
{ isAdmin: false, orgOwner: true },
])(
"does not mount a requested renewal for $isAdmin admin / $orgOwner owner",
(auth) => {
Object.assign(ownership, auth);
render(
<PortalTestProviders>
<MemoryRouter>
<UIProvider>
<HostedModal />
</UIProvider>
</MemoryRouter>
</PortalTestProviders>,
);
click("Open billing renewal");
expect(screen.queryByRole("dialog")).toBeNull();
expect(startReauth).not.toHaveBeenCalled();
expect(startConnect).not.toHaveBeenCalled();
},
);
it.each([
{ state: "expired" as const, sessionRestored: false },
{ state: "linked" as const, sessionRestored: false },
])(
"shows a failed renewal retry after $state and lets the owner retry again",
async (outcome) => {
startReauth.mockRejectedValueOnce(new Error("offline"));
renderModal("reauth", outcome);
click(/Try again/);
expect(await screen.findByText(/outbound network access/)).toBeTruthy();
expect(assign).not.toHaveBeenCalled();
expect(screen.queryByText(GHOST)).toBeNull();
click(/Sign in again/);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
expect(startReauth).toHaveBeenCalledTimes(2);
expect(startConnect).not.toHaveBeenCalled();
},
);
it("shows callback configuration guidance when retrying a partial session fails", async () => {
startReauth.mockResolvedValue({
phase: "CALLBACK_MISMATCH",
authorizeUrl: null,
});
renderModal("reauth", { state: "linked", sessionRestored: false });
click(/Try again/);
expect(
await screen.findByText(/configured frontend address does not match/),
).toBeTruthy();
expect(screen.getByRole("button", { name: /Sign in again/ })).toBeTruthy();
expect(assign).not.toHaveBeenCalled();
});
it("opens on the pitch, and asks nothing of the backend until told", () => {
renderModal();
expect(screen.getByText(BENEFITS)).toBeTruthy();
expect(screen.getByRole("button", { name: CONNECT })).toBeTruthy();
expect(filledSteps()).toBe(1);
expect(startConnect).not.toHaveBeenCalled();
});
it("starts renewal on HTTP hosts without crypto.randomUUID", async () => {
const original = crypto.randomUUID;
Object.defineProperty(crypto, "randomUUID", {
configurable: true,
value: undefined,
});
try {
renderModal("reauth");
click(/Sign in again/);
await waitFor(() => expect(startReauth).toHaveBeenCalled(), {
timeout: 500,
});
expect(startReauth.mock.calls[0][0]).toMatch(/state=.+/);
} finally {
Object.defineProperty(crypto, "randomUUID", {
configurable: true,
value: original,
});
}
});
it("does not redirect if the renewal dialog closes while the request is pending", async () => {
let resolve!: (value: unknown) => void;
startReauth.mockReturnValue(
new Promise((done) => {
resolve = done;
}),
);
const view = renderModal("reauth");
click(/Sign in again/);
view.unmount();
await act(async () => {
resolve({ phase: "PENDING", authorizeUrl: AUTHORIZE });
});
expect(assign).not.toHaveBeenCalled();
});
it("keeps credential fields out of the portaled connection dialog", async () => {
renderModal();
const dialog = screen.getByRole("dialog");
expect(dialog).toBeVisible();
expect(
dialog.querySelector('input[type="password"], input[type="email"]'),
).toBeNull();
click(CONNECT);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
expect(
dialog.querySelector('input[type="password"], input[type="email"]'),
).toBeNull();
});
it("retains the Enterprise request when leaving for account approval", async () => {
const entry = "/settings/billing?source=sales&procurement=start";
renderModal("link", null, entry);
click(CONNECT);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
expect(readPendingConnect()?.returnTo).toBe(entry);
});
it("hands over on the first click, showing the ghost while it goes", async () => {
renderModal();
click(CONNECT);
await waitFor(() => expect(startConnect).toHaveBeenCalled());
expect(screen.getByText(GHOST)).toBeTruthy();
expect(filledSteps()).toBe(2);
// The backend checks this against the request's Origin header.
expect(startConnect).toHaveBeenCalledWith(
"http://localhost:5173",
expect.stringMatching(
/^http:\/\/localhost:5173\/account-link\/callback\?state=/,
),
);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
expect(startReauth).not.toHaveBeenCalled();
});
it("uses the reauth endpoint, with no pitch and no steps", async () => {
renderModal("reauth");
// A server that is already connected is not sold anything.
expect(screen.queryByText(BENEFITS)).toBeNull();
expect(screen.queryByText(/Step 1 of 3/)).toBeNull();
click(/Sign in again/);
// A different endpoint: reauth presents the credential, so the team is pinned server-side.
await waitFor(() =>
expect(startReauth).toHaveBeenCalledWith(
expect.stringMatching(
/^http:\/\/localhost:5173\/account-link\/callback\?state=/,
),
),
);
expect(startConnect).not.toHaveBeenCalled();
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
});
it("names a new connection using its deployment URL without the current route or query", async () => {
deployment.basePath = "/pdf";
window.location.href =
"http://localhost:5173/pdf/settings/account-link?view=account#details";
renderModal();
click(CONNECT);
await waitFor(() =>
expect(startConnect).toHaveBeenCalledWith(
"http://localhost:5173/pdf",
expect.stringMatching(
/^http:\/\/localhost:5173\/pdf\/account-link\/callback\?state=/,
),
),
);
});
it("falls back to step 1 with the reason when the handshake cannot start", async () => {
startConnect.mockRejectedValue(new Error("offline"));
renderModal();
click(CONNECT);
await waitFor(() => expect(startConnect).toHaveBeenCalled());
expect(assign).not.toHaveBeenCalled();
// The ghost unmounts when the request settles, so the reason lands on step 1.
expect(await screen.findByText(/outbound network access/)).toBeTruthy();
expect(screen.getByText(BENEFITS)).toBeTruthy();
expect(filledSteps()).toBe(1);
});
it("explains a pending ownership transfer and allows linking after it is resolved", async () => {
startConnect.mockRejectedValueOnce(new HttpError(409, "Conflict", {}));
renderModal();
click(CONNECT);
expect(
await screen.findByText(/Settings → Users to finish or cancel/),
).toBeTruthy();
expect(screen.queryByText(/outbound network access/)).toBeNull();
expect(assign).not.toHaveBeenCalled();
expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();
expect(filledSteps()).toBe(1);
click(CONNECT);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
});
it.each(["link", "reauth"] as const)(
"explains a callback address mismatch during %s and allows retry after correction",
async (mode) => {
const start = mode === "reauth" ? startReauth : startConnect;
const button = mode === "reauth" ? /Sign in again/ : CONNECT;
start.mockResolvedValue({
phase: "CALLBACK_MISMATCH",
authorizeUrl: null,
secondsRemaining: null,
teamId: null,
});
renderModal(mode);
click(button);
expect(
await screen.findByText(/configured frontend address does not match/),
).toBeTruthy();
expect(assign).not.toHaveBeenCalled();
expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();
expect(screen.queryByText(GHOST)).toBeNull();
start.mockResolvedValue({
phase: "PENDING",
authorizeUrl: AUTHORIZE,
secondsRemaining: 900,
teamId: null,
});
click(button);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
const callbackUrl = start.mock.calls[1][mode === "reauth" ? 0 : 1];
const pending = JSON.parse(
sessionStorage.getItem("stirling.portalConnect")!,
);
expect(pending.browserState).toBe(
new URL(callbackUrl).searchParams.get("state"),
);
expect(pending.mode).toBe(mode);
},
);
it("does not navigate when there is nothing to navigate to", async () => {
// Already linked: the backend reports status without an authorize URL.
startConnect.mockResolvedValue({
phase: "LINKED",
authorizeUrl: null,
secondsRemaining: null,
teamId: 7,
});
renderModal();
click(CONNECT);
await waitFor(() => expect(startConnect).toHaveBeenCalled());
expect(assign).not.toHaveBeenCalled();
});
/** Busy is never cleared on success, because the page was meant to be gone. */
describe("coming back from a hand-off that never completed", () => {
it("clears the in-flight flag when the page is shown again", async () => {
renderModal();
click(CONNECT);
await waitFor(() => expect(screen.getByText(GHOST)).toBeTruthy());
act(() => {
window.dispatchEvent(new Event("pageshow"));
});
expect(screen.getByText(BENEFITS)).toBeTruthy();
expect(filledSteps()).toBe(1);
});
it("dismisses a pending renewal and opens a fresh attempt through the real host", async () => {
let finish!: (value: unknown) => void;
startReauth.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
}),
);
render(
<PortalTestProviders>
<MemoryRouter>
<UIProvider>
<HostedModal />
</UIProvider>
</MemoryRouter>
</PortalTestProviders>,
);
click("Open billing renewal");
click(/Sign in again/);
expect(screen.getByText(GHOST)).toBeVisible();
act(() =>
within(screen.getByRole("dialog"))
.getAllByRole("button", { name: "Close" })[0]
.click(),
);
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
await act(async () =>
finish({ phase: "PENDING", authorizeUrl: AUTHORIZE }),
);
expect(assign).not.toHaveBeenCalled();
expect(sessionStorage.getItem("stirling.portalConnect")).toBeNull();
click("Open billing renewal");
expect(screen.queryByText(GHOST)).toBeNull();
click(/Sign in again/);
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
expect(startReauth).toHaveBeenCalledTimes(2);
});
});
describe("resuming after the round trip", () => {
it("renews missing browser access after an exhausted free-tier link succeeds", async () => {
renderModal("exhausted", {
state: "linked",
sessionRestored: false,
});
expect(screen.getByText("Renew billing access")).toBeTruthy();
expect(filledSteps()).toBe(0);
click(/Try again/);
await waitFor(() => expect(startReauth).toHaveBeenCalledTimes(1));
expect(startConnect).not.toHaveBeenCalled();
});
it("keeps the normal completion after an exhausted free-tier link restores access", async () => {
renderModal("exhausted", { state: "linked", sessionRestored: true });
expect(
await screen.findByText(/now runs against your Stirling account/),
).toBeTruthy();
expect(filledSteps()).toBe(3);
expect(startReauth).not.toHaveBeenCalled();
});
it("keeps a renewal success to one step without the link onboarding", async () => {
renderModal("reauth", {
mode: "reauth",
state: "linked",
sessionRestored: true,
});
expect(
await screen.findByText(/billing access has been renewed/),
).toBeTruthy();
expect(screen.queryByText("Invite your team")).toBeNull();
expect(filledSteps()).toBe(0);
});
it("retries expired renewal with reauth rather than registering again", async () => {
renderModal("reauth", {
mode: "reauth",
state: "expired",
sessionRestored: false,
});
click(/Try again/);
await waitFor(() => expect(startReauth).toHaveBeenCalledTimes(1));
expect(startConnect).not.toHaveBeenCalled();
});
it("lands on step 3 rather than restarting the pitch", async () => {
renderModal("link", { state: "linked", sessionRestored: true });
expect(
await screen.findByText(/now runs against your Stirling account/),
).toBeTruthy();
expect(screen.queryByText(BENEFITS)).toBeNull();
// Left on 2 of 3, arrived on 3: the whole reason the bar spans the redirect.
expect(filledSteps()).toBe(3);
expect(await screen.findByText(EMAIL)).toBeTruthy();
expect(await screen.findByText("Invite your team")).toBeTruthy();
});
it("opens a fresh handshake for a spent one, showing the ghost again", async () => {
renderModal("link", { state: "expired", sessionRestored: false });
expect(await screen.findByText("Request expired")).toBeTruthy();
click(/Try again/);
await waitFor(() => expect(startConnect).toHaveBeenCalled());
// Busy outranks the stale outcome, or they sit on "Request expired" until the browser goes.
expect(screen.getByText(GHOST)).toBeTruthy();
});
it("offers no retry while the claim is still in flight", async () => {
renderModal("link", { state: "working", sessionRestored: false });
expect(await screen.findByText(/Finishing the connection/)).toBeTruthy();
expect(screen.queryByRole("button", { name: /Try again/ })).toBeNull();
});
it("does not offer a retry for a response it could not read", async () => {
renderModal("link", { state: "malformed", sessionRestored: false });
expect(
await screen.findByText(/Could not read the response/),
).toBeTruthy();
expect(screen.queryByRole("button", { name: /Try again/ })).toBeNull();
});
});
it("leads with credits and explains which benefits need a paid plan", async () => {
renderModal("exhausted");
expect(screen.getByText("Keep your workflows running")).toBeTruthy();
expect(screen.getByText(BENEFITS)).toBeTruthy();
expect(screen.queryByText(/Linking does not start a paid plan/)).toBeNull();
expect(
screen.queryByText(/Manual PDF tools are still available/),
).toBeNull();
expect(screen.queryByText("500 free per month")).toBeNull();
expect(filledSteps()).toBe(0);
click("Link account for more credits");
await waitFor(() => expect(assign).toHaveBeenCalledWith(AUTHORIZE));
});
it.each([
{ isAdmin: false, orgOwner: false },
{ isAdmin: true, orgOwner: false },
])("offers non-owners guidance without a handshake: %j", (roles) => {
Object.assign(ownership, roles);
renderModal("exhausted");
expect(screen.getByText(/open Usage & billing/)).toBeTruthy();
expect(
screen.getByRole("button", { name: "Copy message for administrator" }),
).toBeTruthy();
expect(
screen.queryByRole("button", { name: "Link account for more credits" }),
).toBeNull();
expect(startConnect).not.toHaveBeenCalled();
});
});