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): prevent unauthenticated credit/subscription API calls (#14223)
Nicholas Tindle32a43d005c0c
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsxindex 43ac443cb7..d96891c87d 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx@@ -33,7 +33,7 @@ export function PaywallGate({ children }: { children: ReactNode }) {select: (res) => (res.status === 200 ? res.data : null),// Skip the call entirely when the flag is off — beta cohort never hits// the paywall, no need to read /credits/subscription on every page load.- enabled: isPaymentEnabled === true,+ enabled: isPaymentEnabled === true && isLoggedIn,},});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsxindex 0230860ef5..54da99fa5f 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx@@ -27,8 +27,12 @@ let mockSubscriptionResult: {data: MockSubscription | null | undefined;isLoading: boolean;} = { data: null, isLoading: false };+let subscriptionQueryEnabled: boolean | undefined;vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({- useGetSubscriptionStatus: () => mockSubscriptionResult,+ useGetSubscriptionStatus: (options: { query?: { enabled?: boolean } }) => {+ subscriptionQueryEnabled = options.query?.enabled;+ return mockSubscriptionResult;+ },}));// Mock environment — default to cloud so the gate logic is exercised; flip to@@ -54,6 +58,7 @@ describe("PaywallGate", () => {mockIsLoggedIn = true;mockIsPaymentEnabled = false;mockSubscriptionResult = { data: null, isLoading: false };+ subscriptionQueryEnabled = undefined;mockIsLocal = false;});@@ -92,6 +97,7 @@ describe("PaywallGate", () => {);expect(screen.getByText("protected")).toBeDefined();expect(screen.queryByTestId("paywall-modal")).toBeNull();+ expect(subscriptionQueryEnabled).toBe(false);});it("does not render modal in local dev even when paid cohort + tier is NO_TIER", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsxindex 3235eabd5b..37be039cd7 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx@@ -17,6 +17,10 @@ import { Key } from "@/services/storage/local-storage";import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";import LibraryPage from "../page";+vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),+}));+// Billing must be on for the provider to derive `isOutOfCredits`; keep the real// `Flag` enum so other flags the page reads (e.g. AGENT_BRIEFING) resolve.vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsxindex 23bc810736..87a79531a1 100644--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx@@ -1,8 +1,9 @@"use client";-import { ReactNode, useState } from "react";+import { ReactNode, useEffect, useState } from "react";import useCredits from "@/hooks/useCredits";+import { useAuth } from "@/lib/auth/hooks/useAuth";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { DailyTopUpAutoOpener } from "./DailyTopUpAutoOpener";@@ -14,10 +15,13 @@ interface Props {}export function TopUpPromptProvider({ children }: Props) {+ const { user, isLoggedIn } = useAuth();+ const identityKey = user?.id ?? null;const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);const { credits, autoTopUpConfig } = useCredits({- fetchInitialCredits: true,- fetchInitialAutoTopUpConfig: true,+ identityKey,+ fetchInitialCredits: isLoggedIn,+ fetchInitialAutoTopUpConfig: isLoggedIn,});// Backend treats amount === 0 as disabled, so auto-refill only actually@@ -38,6 +42,10 @@ export function TopUpPromptProvider({ children }: Props) {const [isOpen, setIsOpen] = useState(false);+ useEffect(() => {+ setIsOpen(false);+ }, [identityKey]);+function openTopUp() {setIsOpen(true);}diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsxindex 1080f243d9..c7f8a3dbc3 100644--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx@@ -15,10 +15,21 @@ import { Key } from "@/services/storage/local-storage";import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";import { LowCreditBanner } from "@/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner";import { useTopUpPrompt } from "@/components/layout/TopUpPrompt/useTopUpPrompt";+import { useState } from "react";// Billing must be on for the provider to derive `isOutOfCredits`; keep the real// `Flag` enum and let each test toggle whether the flag resolves true.let isBillingEnabled = true;+let authenticatedUserId: string | null = "user-a";++// Simulate an authenticated user so that fetchInitialCredits and+// fetchInitialAutoTopUpConfig are enabled (they gate on isLoggedIn).+vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: authenticatedUserId ? { id: authenticatedUserId } : null,+ isLoggedIn: Boolean(authenticatedUserId),+ }),+}));vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {const actual =@@ -58,22 +69,36 @@ function setupCredits(args: {};}-function renderProvider() {- return render(+function providerTree() {+ return (<TopUpPromptProvider><div>ready</div>+ <StatefulChild /><LowCreditBanner />- </TopUpPromptProvider>,+ </TopUpPromptProvider>+ );+}++function StatefulChild() {+ const [value, setValue] = useState(0);+ return (+ <button onClick={() => setValue(value + 1)}>page state {value}</button>);}+function renderProvider() {+ return render(providerTree());+}+beforeEach(() => {localStorage.clear();+ authenticatedUserId = "user-a";isBillingEnabled = true;});afterEach(() => {localStorage.clear();+ vi.restoreAllMocks();});describe("TopUpPromptProvider daily auto-opener", () => {@@ -157,6 +182,57 @@ describe("useTopUpPrompt without a provider", () => {});describe("TopUpPromptProvider out-of-credits suppression", () => {+ test("does not fetch billing data when logged out", async () => {+ authenticatedUserId = null;+ let creditsRequested = false;+ let autoTopUpRequested = false;+ server.use(+ getGetV1GetUserCreditsMockHandler(() => {+ creditsRequested = true;+ return { credits: 0 };+ }),+ getGetV1GetAutoTopUpMockHandler(() => {+ autoTopUpRequested = true;+ return { amount: 0, threshold: 0 };+ }),+ );++ renderProvider();+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(creditsRequested).toBe(false);+ expect(autoTopUpRequested).toBe(false);+ });++ test("resets and refetches billing state when the authenticated user changes", async () => {+ let credits = 0;+ let creditRequests = 0;+ server.use(+ getGetV1GetUserCreditsMockHandler(() => {+ creditRequests += 1;+ return { credits };+ }),+ getGetV1GetAutoTopUpMockHandler({ amount: 0, threshold: 0 }),+ );++ const view = renderProvider();++ const banner = await screen.findByRole("alert");+ expect(banner.textContent).toMatch(/out of automation credits/i);+ expect(creditRequests).toBe(1);+ fireEvent.click(screen.getByText("page state 0"));++ credits = 500;+ authenticatedUserId = "user-b";+ view.rerender(providerTree());++ await waitFor(() => expect(creditRequests).toBe(2));+ expect(screen.getByText("page state 1")).toBeDefined();+ await waitFor(() =>+ expect(screen.queryByText(/out of automation credits/i)).toBeNull(),+ );+ });+test("suppresses dialog and banner when auto-refill is enabled", async () => {const { waitForCreditsFetch } = setupCredits({credits: 0,diff --git a/autogpt_platform/frontend/src/hooks/useCredits.ts b/autogpt_platform/frontend/src/hooks/useCredits.tsindex cad6631273..de029901b4 100644--- a/autogpt_platform/frontend/src/hooks/useCredits.ts+++ b/autogpt_platform/frontend/src/hooks/useCredits.ts@@ -3,15 +3,17 @@ import {RefundRequest,TransactionHistory,} from "@/lib/autogpt-server-api/types";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useRouter } from "next/navigation";export default function useCredits({+ identityKey,fetchInitialCredits = false,fetchInitialAutoTopUpConfig = false,fetchInitialTransactionHistory = false,fetchInitialRefundRequests = false,}: {+ identityKey?: string | null;fetchInitialCredits?: boolean;fetchInitialAutoTopUpConfig?: boolean;fetchInitialTransactionHistory?: boolean;@@ -35,14 +37,25 @@ export default function useCredits({amount: number;threshold: number;} | null>(null);+ const identityKeyRef = useRef(identityKey);+ const [stateIdentityKey, setStateIdentityKey] = useState(identityKey);++ useEffect(() => {+ identityKeyRef.current = identityKey;+ setStateIdentityKey(identityKey);+ setCredits(null);+ setAutoTopUpConfig(null);+ }, [identityKey]);const api = useMemo(() => new AutoGPTServerAPI(), []);const router = useRouter();const fetchCredits = useCallback(async () => {+ const requestIdentityKey = identityKey;const response = await api.getUserCredit();+ if (identityKeyRef.current !== requestIdentityKey) return;setCredits(response.credits ?? null);- }, [api]);+ }, [api, identityKey]);useEffect(() => {if (!fetchInitialCredits) return;@@ -50,9 +63,11 @@ export default function useCredits({}, [fetchCredits, fetchInitialCredits]);const fetchAutoTopUpConfig = useCallback(async () => {+ const requestIdentityKey = identityKey;const response = await api.getAutoTopUpConfig();+ if (identityKeyRef.current !== requestIdentityKey) return;setAutoTopUpConfig(response);- }, [api]);+ }, [api, identityKey]);useEffect(() => {if (!fetchInitialAutoTopUpConfig) return;@@ -135,11 +150,11 @@ export default function useCredits({}, []);return {- credits,+ credits: stateIdentityKey === identityKey ? credits : null,fetchCredits,requestTopUp,refundTopUp,- autoTopUpConfig,+ autoTopUpConfig: stateIdentityKey === identityKey ? autoTopUpConfig : null,fetchAutoTopUpConfig,updateAutoTopUpConfig,transactionHistory,