Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): harden paywall flows for half-dead sessions (#13333)

Ubbe4de3e7c8d0e6
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx
index 70edf397b7..3717fb95d9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx
@@ -16,6 +16,8 @@ export function PaywallModal() {
const {
isLoading,
plans,
+ retryLoadPlans,
+ isRetryingPlans,
country,
isYearly,
selectedCycle,
@@ -34,15 +36,22 @@ export function PaywallModal() {
<Dialog forceOpen controlled={{ isOpen: true, set: () => {} }}>
<Dialog.Content>
<div className="relative flex w-full flex-col items-center gap-4 px-2 py-2">
- <Button
- variant="ghost"
- size="small"
- onClick={handleLogout}
- leftIcon={<SignOutIcon size={16} />}
- className="absolute right-0 top-0 text-zinc-500 hover:text-zinc-700"
- >
- Log out
- </Button>
+ {/* Sticky (not absolute) so the button pins to the top of the
+ dialog's scroll viewport instead of getting clipped or scrolled
+ away when the plan cards overflow on short screens. The negative
+ margin collapses the row's layout space so the title keeps its
+ position. */}
+ <div className="sticky top-0 z-10 -mb-[3.25rem] flex w-full justify-end">
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={handleLogout}
+ leftIcon={<SignOutIcon size={16} />}
+ className="bg-white/90 text-zinc-500 hover:text-zinc-700"
+ >
+ Log out
+ </Button>
+ </div>
<div className="flex flex-col items-center gap-1 text-center">
<Text
variant="h3"
@@ -101,10 +110,20 @@ export function PaywallModal() {
<Skeleton className="h-[26rem] rounded-2xl" />
</div>
) : plans.length === 0 ? (
- <p className="text-center text-sm text-zinc-500">
- Subscriptions are temporarily unavailable. Please try again
- shortly.
- </p>
+ <div className="flex flex-col items-center gap-3">
+ <p className="text-center text-sm text-zinc-500">
+ Subscriptions are temporarily unavailable. Please try again
+ shortly.
+ </p>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={retryLoadPlans}
+ loading={isRetryingPlans}
+ >
+ Retry
+ </Button>
+ </div>
) : (
<div
className={cn(
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
index 20daec88c1..d741f34c41 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
@@ -39,6 +39,14 @@ vi.mock("@/components/molecules/Dialog/Dialog", () => ({
Dialog: MockDialog,
}));
+const mockValidateSession = vi.fn().mockResolvedValue(true);
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({
+ validateSession: mockValidateSession,
+ isLoggedIn: true,
+ }),
+}));
+
const mockReplace = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({
@@ -54,6 +62,7 @@ vi.mock("next/navigation", () => ({
useParams: () => ({}),
}));
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { PaywallModal } from "../PaywallModal";
interface SubscriptionShape {
@@ -68,23 +77,28 @@ interface SubscriptionShape {
function setupMocks({
subscription,
isLoading = false,
+ isFetching = false,
mutateFn = vi.fn().mockResolvedValue({ status: 200, data: { url: "" } }),
isPending = false,
}: {
subscription: SubscriptionShape | null;
isLoading?: boolean;
+ isFetching?: boolean;
mutateFn?: ReturnType<typeof vi.fn>;
isPending?: boolean;
}) {
+ const refetchFn = vi.fn();
mockUseGetSubscriptionStatus.mockReturnValue({
data: subscription,
isLoading,
+ isFetching,
+ refetch: refetchFn,
});
mockUseUpdateSubscriptionTier.mockReturnValue({
mutateAsync: mutateFn,
isPending,
});
- return { mutateFn };
+ return { mutateFn, refetchFn };
}
afterEach(() => {
@@ -315,6 +329,90 @@ describe("PaywallModal — upgrade mutation", () => {
expect(mutateFn).not.toHaveBeenCalled();
});
+ it("re-validates the session when the paywall mounts", () => {
+ setupMocks({
+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000 } },
+ });
+
+ render(<PaywallModal />);
+
+ expect(mockValidateSession).toHaveBeenCalledTimes(1);
+ });
+
+ it("sends the current page as cancel_url so backing out of Stripe re-gates", async () => {
+ stubLocation();
+ Object.assign(window.location, { href: "https://app.test/copilot" });
+ const { mutateFn } = setupMocks({
+ subscription: {
+ tier: "NO_TIER",
+ tier_costs: { PRO: 5000, MAX: 32000 },
+ },
+ });
+
+ render(<PaywallModal />);
+
+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));
+
+ await waitFor(() => {
+ expect(mutateFn).toHaveBeenCalledTimes(1);
+ });
+ const [args] = mutateFn.mock.calls[0];
+ expect(args.data.cancel_url).toBe("https://app.test/copilot");
+ expect(args.data.success_url).toBe(
+ "https://app.test/profile/credits?subscription=success",
+ );
+ });
+
+ it("401 from updateTier routes to /login instead of toasting a dead-end error", async () => {
+ stubLocation();
+ const mutateFn = vi
+ .fn()
+ .mockRejectedValue(
+ new ApiError("Authorization header is missing", 401, null),
+ );
+ setupMocks({
+ subscription: {
+ tier: "NO_TIER",
+ tier_costs: { PRO: 5000, MAX: 32000 },
+ },
+ mutateFn,
+ });
+
+ render(<PaywallModal />);
+
+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));
+
+ await waitFor(() => {
+ expect(mockReplace).toHaveBeenCalledWith("/login");
+ });
+ expect(mockToast).not.toHaveBeenCalled();
+ expect(window.location.href).toBe("");
+ });
+
+ it("non-401 ApiError surfaces a toast and stays on the paywall", async () => {
+ stubLocation();
+ const mutateFn = vi
+ .fn()
+ .mockRejectedValue(new ApiError("Forbidden", 403, null));
+ setupMocks({
+ subscription: {
+ tier: "NO_TIER",
+ tier_costs: { PRO: 5000, MAX: 32000 },
+ },
+ mutateFn,
+ });
+
+ render(<PaywallModal />);
+
+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));
+
+ await waitFor(() => {
+ expect(mockToast).toHaveBeenCalledTimes(1);
+ });
+ expect(mockReplace).not.toHaveBeenCalled();
+ expect(window.location.href).toBe("");
+ });
+
it("422 from updateTier surfaces a toast and does not redirect", async () => {
stubLocation();
const mutateFn = vi
@@ -457,6 +555,39 @@ describe("PaywallModal — empty / loading states", () => {
expect(screen.queryByRole("button", { name: /upgrade to/i })).toBeNull();
});
+ it("Retry in the unavailable fallback refetches the subscription status", () => {
+ const { refetchFn } = setupMocks({
+ subscription: {
+ tier: "NO_TIER",
+ tier_costs: {},
+ },
+ });
+
+ render(<PaywallModal />);
+
+ fireEvent.click(screen.getByRole("button", { name: /retry/i }));
+
+ expect(refetchFn).toHaveBeenCalledTimes(1);
+ });
+
+ it("Retry is disabled while the refetch is in flight", () => {
+ const { refetchFn } = setupMocks({
+ subscription: {
+ tier: "NO_TIER",
+ tier_costs: {},
+ },
+ isFetching: true,
+ });
+
+ render(<PaywallModal />);
+
+ const retryButton = screen.getByRole("button", { name: /retry/i });
+ expect(retryButton.hasAttribute("disabled")).toBe(true);
+
+ fireEvent.click(retryButton);
+ expect(refetchFn).not.toHaveBeenCalled();
+ });
+
it("renders skeletons while subscription status is loading", () => {
setupMocks({ subscription: null, isLoading: true });
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
index 02256fed23..5a6456dc30 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
@@ -8,6 +8,9 @@ import {
} from "@/app/api/__generated__/endpoints/credits/credits";
import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { useMountEffect } from "@/hooks/useMountEffect";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { COUNTRIES } from "@/components/molecules/PlanCard/countries";
import {
type BackendTierKey,
@@ -51,11 +54,26 @@ function deriveAvailablePlans(
}
export function usePaywallModal() {
- const { data: subscription, isLoading } = useGetSubscriptionStatus({
+ const {
+ data: subscription,
+ isLoading,
+ isFetching,
+ refetch: refetchSubscription,
+ } = useGetSubscriptionStatus({
query: { select: (res) => (res.status === 200 ? res.data : null) },
});
const { mutateAsync: updateTier, isPending } = useUpdateSubscriptionTier();
+ const { validateSession } = useSupabase();
const router = useRouter();
+
+ // The paywall can outlive the session that mounted it (failed logout,
+ // history restore, expired cookies). Re-check the session server-side on
+ // mount: an invalid one clears the user — unmounting the gate — and
+ // redirects to /login instead of leaving a zombie paywall whose checkout
+ // calls can only 401.
+ useMountEffect(() => {
+ void validateSession();
+ });
const [selectedCycle, setSelectedCycle] = useState<"monthly" | "yearly">(
"yearly",
);
@@ -82,12 +100,15 @@ export function usePaywallModal() {
async function fireUpdate(tier: string) {
setSelectedTier(tier);
try {
- const baseUrl = `${window.location.origin}/profile/credits`;
const result = await updateTier({
data: {
tier: tier as SubscriptionTierRequestTier,
- success_url: `${baseUrl}?subscription=success`,
- cancel_url: `${baseUrl}?subscription=cancelled`,
+ success_url: `${window.location.origin}/profile/credits?subscription=success`,
+ // Backing out of Stripe Checkout must return to the page the user
+ // was on so the paywall re-gates immediately. /profile/* is
+ // paywall-exempt — landing there let users wander an app that
+ // looks unlocked until the next non-exempt navigation.
+ cancel_url: window.location.href,
billing_cycle: isYearly ? "yearly" : "monthly",
},
});
@@ -96,6 +117,12 @@ export function usePaywallModal() {
window.location.href = url;
}
} catch (error) {
+ // 401 means the paywall outlived its session: checkout can never
+ // succeed, so route to login instead of toasting a dead-end error.
+ if (error instanceof ApiError && error.status === 401) {
+ router.replace("/login");
+ return;
+ }
toast({
title: "Couldn't start checkout",
description:
@@ -152,9 +179,15 @@ export function usePaywallModal() {
? (PLAN_LABEL[pendingTier] ?? pendingTier)
: null;
+ function retryLoadPlans() {
+ void refetchSubscription();
+ }
+
return {
isLoading,
plans,
+ retryLoadPlans,
+ isRetryingPlans: isFetching,
country,
isYearly,
selectedCycle,
diff --git a/autogpt_platform/frontend/src/lib/supabase/__tests__/actions.test.ts b/autogpt_platform/frontend/src/lib/supabase/__tests__/actions.test.ts
new file mode 100644
index 0000000000..4b2be6282e
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/supabase/__tests__/actions.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { cookieJar, mockSignOut } = vi.hoisted(() => ({
+ cookieJar: new Map<string, string>(),
+ mockSignOut: vi.fn(),
+}));
+
+vi.mock("next/headers", () => ({
+ cookies: async () => ({
+ getAll: () =>
+ [...cookieJar.keys()].map((name) => ({
+ name,
+ value: cookieJar.get(name) ?? "",
+ })),
+ delete: (name: string) => {
+ cookieJar.delete(name);
+ },
+ }),
+}));
+
+vi.mock("../server/getServerSupabase", () => ({
+ getServerSupabase: async () => ({ auth: { signOut: mockSignOut } }),
+}));
+
+vi.mock("@sentry/nextjs", () => ({
+ withServerActionInstrumentation: (
+ _name: string,
+ _options: unknown,
+ fn: () => unknown,
+ ) => fn(),
+}));
+
+import { serverLogout } from "../actions";
+
+function seedCookies() {
+ cookieJar.set("sb-abc-auth-token", "session");
+ cookieJar.set("sb-abc-auth-token.0", "chunk-0");
+ cookieJar.set("sb-abc-auth-token.1", "chunk-1");
+ cookieJar.set("unrelated-cookie", "keep-me");
+}
+
+beforeEach(() => {
+ cookieJar.clear();
+ seedCookies();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("serverLogout", () => {
+ it("clears all sb-* auth cookies on successful sign-out", async () => {
+ mockSignOut.mockResolvedValue({ error: null });
+
+ const result = await serverLogout();
+
+ expect(result).toEqual({ success: true });
+ expect([...cookieJar.keys()]).toEqual(["unrelated-cookie"]);
+ });
+
+ it("clears auth cookies even when signOut returns an error, so the dead session cannot resurrect", async () => {
+ mockSignOut.mockResolvedValue({
+ error: { message: "session_not_found" },
+ });
+
+ const result = await serverLogout();
+
+ expect(result).toEqual({ success: true });
+ expect([...cookieJar.keys()]).toEqual(["unrelated-cookie"]);
+ });
+
+ it("clears auth cookies even when signOut throws", async () => {
+ mockSignOut.mockRejectedValue(new Error("network down"));
+
+ const result = await serverLogout();
+
+ expect(result).toEqual({ success: true });
+ expect([...cookieJar.keys()]).toEqual(["unrelated-cookie"]);
+ });
+
+ it("passes the global scope through to signOut", async () => {
+ mockSignOut.mockResolvedValue({ error: null });
+
+ await serverLogout({ globalLogout: true });
+
+ expect(mockSignOut).toHaveBeenCalledWith({ scope: "global" });
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/supabase/actions.ts b/autogpt_platform/frontend/src/lib/supabase/actions.ts
index 23ad50d84a..6722ffe0cb 100644
--- a/autogpt_platform/frontend/src/lib/supabase/actions.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/actions.ts
@@ -1,6 +1,7 @@
"use server";
import * as Sentry from "@sentry/nextjs";
import type { User } from "@supabase/supabase-js";
+import { cookies } from "next/headers";
import { getRedirectPath } from "./helpers";
import { getServerSupabase } from "./server/getServerSupabase";
@@ -165,16 +166,18 @@ export async function serverLogout(options: ServerLogoutOptions = {}) {
if (error) {
console.error("Error logging out:", error);
- return { success: false, error: error.message };
}
} catch (error) {
console.error("Logout error:", error);
- return {
- success: false,
- error: error instanceof Error ? error.message : "Unknown error",
- };
}
+ // Always expire the auth cookies, even when signOut() fails (revoked or
+ // already-rotated refresh token, Supabase API hiccup). If they survive,
+ // the middleware still sees a session and bounces the user from /login
+ // straight back into the app with a half-dead session: the paywall
+ // re-mounts while every API call fails with a 401.
+ await clearSupabaseAuthCookies();
+
// No `revalidatePath`: `/` is a client-only spinner that redirects to
// `/copilot`, so there is no RSC payload to invalidate. The cross-tab
// storage listener calls `router.refresh()` for any visible page, and
@@ -184,6 +187,17 @@ export async function serverLogout(options: ServerLogoutOptions = {}) {
);
}
+// Supabase SSR stores the session in `sb-<project-ref>-auth-token` cookies
+// (chunked as `.0`, `.1`, ... when large), all `sb-`-prefixed.
+async function clearSupabaseAuthCookies() {
+ const cookieStore = await cookies();
+ for (const cookie of cookieStore.getAll()) {
+ if (cookie.name.startsWith("sb-")) {
+ cookieStore.delete(cookie.name);
+ }
+ }
+}
+
export async function refreshSession() {
return await Sentry.withServerActionInstrumentation(
"refreshSession",
diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts
index 4731a0f2e4..a363f2abe8 100644
--- a/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/__tests__/useSupabaseStore.test.ts
@@ -22,6 +22,8 @@ vi.mock("../helpers", () => ({
validateSession: vi.fn(),
}));
+import type { User } from "@supabase/supabase-js";
+import { validateSession as validateSessionHelper } from "../helpers";
import { useSupabaseStore } from "../useSupabaseStore";
function makeRouter() {
@@ -119,3 +121,61 @@ describe("useSupabaseStore.setCurrentRequestContext", () => {
expect(after.currentPath).toBe(next.path ?? basePath);
});
});
+
+describe("useSupabaseStore.validateSession", () => {
+ afterEach(() => {
+ useSupabaseStore.setState({
+ user: null,
+ hasLoadedUser: false,
+ isUserLoading: false,
+ isValidating: false,
+ lastValidation: 0,
+ });
+ vi.clearAllMocks();
+ });
+
+ it("clears the user and redirects when the server says the session is invalid", async () => {
+ const router = makeRouter();
+ vi.mocked(validateSessionHelper).mockResolvedValue({
+ user: null,
+ isValid: false,
+ redirectPath: "/login?next=%2Fbuild",
+ shouldUpdateUser: false,
+ });
+ useSupabaseStore.setState({
+ user: { id: "user-1" } as User,
+ hasLoadedUser: true,
+ });
+
+ const stillValid = await useSupabaseStore.getState().validateSession({
+ router,
+ path: "/build",
+ force: true,
+ });
+
+ expect(stillValid).toBe(false);
+ expect(useSupabaseStore.getState().user).toBeNull();
+ expect(router.push).toHaveBeenCalledWith("/login?next=%2Fbuild");
+ });
+
+ it("keeps the user and does not redirect when the session is valid", async () => {
+ const router = makeRouter();
+ const user = { id: "user-1" } as User;
+ vi.mocked(validateSessionHelper).mockResolvedValue({
+ user,
+ isValid: true,
+ shouldUpdateUser: false,
+ });
+ useSupabaseStore.setState({ user, hasLoadedUser: true });
+
+ const stillValid = await useSupabaseStore.getState().validateSession({
+ router,
+ path: "/build",
+ force: true,
+ });
+
+ expect(stillValid).toBe(true);
+ expect(useSupabaseStore.getState().user).toBe(user);
+ expect(router.push).not.toHaveBeenCalled();
+ });
+});