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(platform): resolve authentication performance bottlenecks and improve reliability (#11028)

Zamil Majdy047f01152044
diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.py
index 52f74f00b1..2b9389fbde 100644
--- a/autogpt_platform/backend/backend/data/onboarding.py
+++ b/autogpt_platform/backend/backend/data/onboarding.py
@@ -4,6 +4,7 @@ from typing import Any, Optional
import prisma
import pydantic
+from autogpt_libs.utils.cache import cached
from prisma.enums import OnboardingStep
from prisma.models import UserOnboarding
from prisma.types import UserOnboardingCreateInput, UserOnboardingUpdateInput
@@ -374,8 +375,13 @@ async def get_recommended_agents(user_id: str) -> list[StoreAgentDetails]:
]
+@cached(maxsize=1, ttl_seconds=300) # Cache for 5 minutes since this rarely changes
async def onboarding_enabled() -> bool:
+ """
+ Check if onboarding should be enabled based on store agent count.
+ Cached to prevent repeated slow database queries.
+ """
+ # Use a more efficient query that stops counting after finding enough agents
count = await prisma.models.StoreAgent.prisma().count(take=MIN_AGENT_COUNT + 1)
-
- # Onboading is enabled if there are at least 2 agents in the store
+ # Onboarding is enabled if there are at least 2 agents in the store
return count >= MIN_AGENT_COUNT
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
index 62e324761e..094f01e2fe 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
@@ -11,14 +11,45 @@ async function shouldShowOnboarding() {
);
}
-// Validate redirect URL to prevent open redirect attacks
+// Default redirect path - matches the home page redirect destination
+const DEFAULT_REDIRECT_PATH = "/marketplace";
+
+// Validate redirect URL to prevent open redirect attacks and malformed URLs
function validateRedirectUrl(url: string): string {
- // Only allow relative URLs that start with /
- if (url.startsWith("/") && !url.startsWith("//")) {
- return url;
+ try {
+ const cleanUrl = url.trim();
+
+ // Check for completely invalid patterns that suggest URL corruption
+ if (
+ cleanUrl.includes(",") || // Any comma suggests concatenated URLs
+ cleanUrl.includes(" ") // Spaces in URLs are problematic
+ ) {
+ console.warn(
+ "Detected corrupted redirect URL (likely race condition):",
+ cleanUrl,
+ );
+ return DEFAULT_REDIRECT_PATH;
+ }
+
+ // Only allow relative URLs that start with /
+ if (!cleanUrl.startsWith("/") || cleanUrl.startsWith("//")) {
+ console.warn("Invalid redirect URL format:", cleanUrl);
+ return DEFAULT_REDIRECT_PATH;
+ }
+
+ // Additional safety checks
+ if (cleanUrl.split("/").length > 5) {
+ // Reasonable path depth limit
+ console.warn("Suspiciously deep redirect URL:", cleanUrl);
+ return DEFAULT_REDIRECT_PATH;
+ }
+
+ // For now, allow any valid relative path (can be restricted later if needed)
+ return cleanUrl;
+ } catch (error) {
+ console.error("Error validating redirect URL:", error);
+ return DEFAULT_REDIRECT_PATH;
}
- // Default to home page for any invalid URLs
- return "/";
}
// Handle the callback to complete the user session login
diff --git a/autogpt_platform/frontend/src/hooks/useOnboardingTimezoneDetection.ts b/autogpt_platform/frontend/src/hooks/useOnboardingTimezoneDetection.ts
index d8b63effe4..f1f22138b1 100644
--- a/autogpt_platform/frontend/src/hooks/useOnboardingTimezoneDetection.ts
+++ b/autogpt_platform/frontend/src/hooks/useOnboardingTimezoneDetection.ts
@@ -1,17 +1,34 @@
import { useEffect, useRef } from "react";
+import { usePathname } from "next/navigation";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { usePostV1UpdateUserTimezone } from "@/app/api/__generated__/endpoints/auth/auth";
/**
- * Hook to silently detect and set user's timezone during onboarding
- * This version doesn't show any toast notifications
+ * Hook to silently detect and set user's timezone ONLY during actual onboarding flow
+ * This prevents unnecessary timezone API calls during authentication and platform usage
* @returns void
*/
export const useOnboardingTimezoneDetection = () => {
const updateTimezone = usePostV1UpdateUserTimezone();
const hasAttemptedDetection = useRef(false);
+ const pathname = usePathname();
+ const { user, isUserLoading } = useSupabase();
+
+ // Check if we're on onboarding route (computed outside useEffect to avoid re-computing)
+ const isOnOnboardingRoute = pathname.startsWith("/onboarding");
useEffect(() => {
- // Only attempt once
+ // Only run during actual onboarding routes - prevents running on every auth
+ if (!isOnOnboardingRoute) {
+ return;
+ }
+
+ // Wait for proper authentication state instead of using arbitrary timeout
+ if (isUserLoading || !user) {
+ return;
+ }
+
+ // Only attempt once per session
if (hasAttemptedDetection.current) {
return;
}
@@ -30,13 +47,13 @@ export const useOnboardingTimezoneDetection = () => {
return;
}
- // Silently update the timezone in the backend
- await updateTimezone.mutateAsync({
+ // Fire-and-forget timezone update - we don't need to wait for response
+ updateTimezone.mutate({
data: { timezone: browserTimezone } as any,
});
- console.log(
- `Timezone automatically set to ${browserTimezone} during onboarding`,
+ console.info(
+ `Timezone automatically set to ${browserTimezone} during onboarding flow`,
);
} catch (error) {
console.error(
@@ -47,11 +64,6 @@ export const useOnboardingTimezoneDetection = () => {
}
};
- // Small delay to ensure user is created
- const timer = setTimeout(() => {
- detectAndSetTimezone();
- }, 1000);
-
- return () => clearTimeout(timer);
- }, []); // Run once on mount
+ detectAndSetTimezone();
+ }, [isOnOnboardingRoute, updateTimezone, user, isUserLoading]); // Use computed boolean to reduce re-renders
};
diff --git a/autogpt_platform/frontend/src/hooks/useTimezoneDetection.ts b/autogpt_platform/frontend/src/hooks/useTimezoneDetection.ts
index f3e411f4fb..090d08fe1b 100644
--- a/autogpt_platform/frontend/src/hooks/useTimezoneDetection.ts
+++ b/autogpt_platform/frontend/src/hooks/useTimezoneDetection.ts
@@ -27,8 +27,8 @@ export const useTimezoneDetection = (currentTimezone?: string) => {
return;
}
- // Update the timezone in the backend
- await updateTimezone.mutateAsync({
+ // Fire-and-forget timezone update - we don't need to wait for response
+ updateTimezone.mutate({
data: { timezone: browserTimezone } as any,
});
diff --git a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
index 8540bb139d..fe632f2f84 100644
--- a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
@@ -82,14 +82,28 @@ export default function OnboardingProvider({
// Automatically detect and set timezone for new users during onboarding
useOnboardingTimezoneDetection();
+ const isOnOnboardingRoute = pathname.startsWith("/onboarding");
+
useEffect(() => {
+ // Only run heavy onboarding API calls if user is logged in and not loading
+ if (isUserLoading || !user) {
+ return;
+ }
+
const fetchOnboarding = async () => {
try {
- const enabled = await api.isOnboardingEnabled();
- if (!enabled && pathname.startsWith("/onboarding")) {
- router.push("/marketplace");
- return;
+ // For non-onboarding routes, we still need basic onboarding state for step completion
+ // but we can skip the expensive isOnboardingEnabled() check
+ if (isOnOnboardingRoute) {
+ // Only check if onboarding is enabled when user is actually on onboarding routes
+ const enabled = await api.isOnboardingEnabled();
+ if (!enabled) {
+ router.push("/marketplace");
+ return;
+ }
}
+
+ // Always fetch user onboarding state for step completion functionality
const onboarding = await api.getUserOnboarding();
// Only update state if onboarding data is valid
@@ -108,15 +122,17 @@ export default function OnboardingProvider({
...prev,
}));
- // Redirect outside onboarding if completed
- // If user did CONGRATS step, that means they completed introductory onboarding
- if (
- onboarding.completedSteps &&
- onboarding.completedSteps.includes("CONGRATS") &&
- pathname.startsWith("/onboarding") &&
- !pathname.startsWith("/onboarding/reset")
- ) {
- router.push("/marketplace");
+ // Only handle onboarding redirects when user is on onboarding routes
+ if (isOnOnboardingRoute) {
+ // Redirect outside onboarding if completed
+ // If user did CONGRATS step, that means they completed introductory onboarding
+ if (
+ onboarding.completedSteps &&
+ onboarding.completedSteps.includes("CONGRATS") &&
+ !pathname.startsWith("/onboarding/reset")
+ ) {
+ router.push("/marketplace");
+ }
}
}
} catch (error) {
@@ -124,11 +140,9 @@ export default function OnboardingProvider({
// Don't update state on error to prevent null access issues
}
};
- if (isUserLoading || !user) {
- return;
- }
+
fetchOnboarding();
- }, [api, pathname, router, user, isUserLoading]);
+ }, [api, isOnOnboardingRoute, router, user, isUserLoading]);
const updateState = useCallback(
(newState: Omit<Partial<UserOnboarding>, "rewardedFor">) => {