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.

feat(frontend): enforce auth through httpOnly cookies (#10201)

Ubbe2af9d75decf4
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index 5d8f2f4463..c0af255deb 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -4,7 +4,6 @@
"private": true,
"scripts": {
"dev": "next dev --turbo",
- "dev:test": "NODE_ENV=test && next dev --turbo",
"build": "pnpm run generate:api-client && SKIP_STORYBOOK_TESTS=true next build",
"start": "next start",
"start:standalone": "cd .next/standalone && node server.js",
diff --git a/autogpt_platform/frontend/playwright.config.ts b/autogpt_platform/frontend/playwright.config.ts
index fddf03eeb9..607f3e15f4 100644
--- a/autogpt_platform/frontend/playwright.config.ts
+++ b/autogpt_platform/frontend/playwright.config.ts
@@ -34,7 +34,15 @@ export default defineConfig({
bypassCSP: true,
},
/* Maximum time one test can run for */
- timeout: 60000,
+ timeout: 30000,
+
+ /* Configure web server to start automatically */
+ webServer: {
+ command: "NEXT_PUBLIC_PW_TEST=true pnpm start",
+ url: "http://localhost:3000",
+ reuseExistingServer: !process.env.CI,
+ timeout: 120 * 1000,
+ },
/* Configure projects for major browsers */
projects: [
@@ -73,15 +81,4 @@ export default defineConfig({
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
-
- /* Run your local server before starting the tests */
- webServer: {
- command: "pnpm start",
- url: "http://localhost:3000/",
- reuseExistingServer: !process.env.CI,
- timeout: 10 * 1000,
- env: {
- NODE_ENV: "test",
- },
- },
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx b/autogpt_platform/frontend/src/app/(platform)/login/page.tsx
index b605cba124..4ce4aab9a9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/login/page.tsx
@@ -1,4 +1,14 @@
"use client";
+import {
+ AuthBottomText,
+ AuthButton,
+ AuthCard,
+ AuthFeedback,
+ AuthHeader,
+ GoogleOAuthButton,
+ PasswordInput,
+ Turnstile,
+} from "@/components/auth";
import {
Form,
FormControl,
@@ -8,19 +18,9 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
-import Link from "next/link";
import LoadingBox from "@/components/ui/loading";
-import {
- AuthCard,
- AuthHeader,
- AuthButton,
- AuthFeedback,
- AuthBottomText,
- GoogleOAuthButton,
- PasswordInput,
- Turnstile,
-} from "@/components/auth";
import { getBehaveAs } from "@/lib/utils";
+import Link from "next/link";
import { useLoginPage } from "./useLoginPage";
export default function LoginPage() {
@@ -100,7 +100,7 @@ export default function LoginPage() {
<FormLabel className="flex w-full items-center justify-between">
<span>Password</span>
<Link
- href="/reset_password"
+ href="/reset-password"
className="text-sm font-normal leading-normal text-black underline"
>
Forgot your password?
diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts b/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts
similarity index 96%
rename from autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts
rename to autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts
index 7cc4da5189..0ee4e4e7cc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts
@@ -1,8 +1,8 @@
"use server";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
-import { redirect } from "next/navigation";
-import * as Sentry from "@sentry/nextjs";
import { verifyTurnstileToken } from "@/lib/turnstile";
+import * as Sentry from "@sentry/nextjs";
+import { redirect } from "next/navigation";
export async function sendResetEmail(email: string, turnstileToken: string) {
return await Sentry.withServerActionInstrumentation(
@@ -19,14 +19,14 @@ export async function sendResetEmail(email: string, turnstileToken: string) {
// Verify Turnstile token if provided
const success = await verifyTurnstileToken(
turnstileToken,
- "reset_password",
+ "reset-password",
);
if (!success) {
return "CAPTCHA verification failed. Please try again.";
}
const { error } = await supabase.auth.resetPasswordForEmail(email, {
- redirectTo: `${origin}/reset_password`,
+ redirectTo: `${origin}/reset-password`,
});
if (error) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx b/autogpt_platform/frontend/src/app/(platform)/reset-password/page.tsx
similarity index 99%
rename from autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx
rename to autogpt_platform/frontend/src/app/(platform)/reset-password/page.tsx
index 5a8e04290f..304d3d452c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/reset-password/page.tsx
@@ -1,9 +1,9 @@
"use client";
import {
- AuthCard,
- AuthHeader,
AuthButton,
+ AuthCard,
AuthFeedback,
+ AuthHeader,
PasswordInput,
Turnstile,
} from "@/components/auth";
@@ -17,16 +17,16 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
+import LoadingBox from "@/components/ui/loading";
+import { useTurnstile } from "@/hooks/useTurnstile";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { sendEmailFormSchema, changePasswordFormSchema } from "@/types/auth";
+import { getBehaveAs } from "@/lib/utils";
+import { changePasswordFormSchema, sendEmailFormSchema } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { changePassword, sendResetEmail } from "./actions";
-import LoadingBox from "@/components/ui/loading";
-import { getBehaveAs } from "@/lib/utils";
-import { useTurnstile } from "@/hooks/useTurnstile";
export default function ResetPasswordPage() {
const { supabase, user, isUserLoading } = useSupabase();
diff --git a/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx b/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
index ad45fd93b7..c27035b622 100644
--- a/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
+++ b/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
@@ -1,24 +1,21 @@
"use client";
-import * as React from "react";
import { useState } from "react";
import Image from "next/image";
-import { Button } from "./Button";
import { IconPersonFill } from "@/components/ui/icons";
-import { ProfileDetails } from "@/lib/autogpt-server-api/types";
import { Separator } from "@/components/ui/separator";
-import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { ProfileDetails } from "@/lib/autogpt-server-api/types";
+import { Button } from "./Button";
-export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {
+export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [profileData, setProfileData] = useState<ProfileDetails>(profile);
- const { supabase } = useSupabase();
const api = useBackendAPI();
- const submitForm = async () => {
+ async function submitForm() {
try {
setIsSubmitting(true);
@@ -39,48 +36,12 @@ export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {
} finally {
setIsSubmitting(false);
}
- };
+ }
- const handleImageUpload = async (file: File) => {
+ async function handleImageUpload(file: File) {
try {
- // Create FormData and append file
- const formData = new FormData();
- formData.append("file", file);
-
- // Get auth token
- if (!supabase) {
- throw new Error("Supabase client not initialized");
- }
-
- const {
- data: { session },
- } = await supabase.auth.getSession();
- const token = session?.access_token;
-
- if (!token) {
- throw new Error("No authentication token found");
- }
-
- // Make upload request
- const response = await fetch(
- `${process.env.NEXT_PUBLIC_AGPT_SERVER_URL}/store/submissions/media`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${token}`,
- },
- body: formData,
- },
- );
-
- if (!response.ok) {
- throw new Error(`Upload failed: ${response.statusText}`);
- }
-
- // Get media URL from response
- const mediaUrl = await response.json();
+ const mediaUrl = await api.uploadStoreSubmissionMedia(file);
- // Update profile with new avatar URL
const updatedProfile = {
...profileData,
avatar_url: mediaUrl,
@@ -91,7 +52,7 @@ export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {
} catch (error) {
console.error("Error uploading image:", error);
}
- };
+ }
return (
<div className="w-full min-w-[800px] px-4 sm:px-8">
@@ -261,4 +222,4 @@ export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {
</div>
</div>
);
-};
+}
diff --git a/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx b/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
index 0f49bbdc75..8edb6be32f 100644
--- a/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
+++ b/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
@@ -1,7 +1,17 @@
"use client";
-import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { OnboardingStep, UserOnboarding } from "@/lib/autogpt-server-api";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
createContext,
@@ -11,16 +21,6 @@ import {
useEffect,
useState,
} from "react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogFooter,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import Link from "next/link";
const OnboardingContext = createContext<
| {
@@ -106,8 +106,6 @@ export default function OnboardingProvider({
const updateState = useCallback(
(newState: Omit<Partial<UserOnboarding>, "rewardedFor">) => {
setState((prev) => {
- api.updateUserOnboarding(newState);
-
if (!prev) {
// Handle initial state
return {
@@ -127,8 +125,15 @@ export default function OnboardingProvider({
}
return { ...prev, ...newState };
});
+
+ // Make the API call asynchronously to not block render
+ setTimeout(() => {
+ api.updateUserOnboarding(newState).catch((error) => {
+ console.error("Failed to update user onboarding:", error);
+ });
+ }, 0);
},
- [api, setState],
+ [api],
);
const completeStep = useCallback(
@@ -153,7 +158,7 @@ export default function OnboardingProvider({
completedSteps: [...state.completedSteps, "RUN_AGENTS"],
}),
});
- }, [api, state]);
+ }, [state, updateState]);
return (
<OnboardingContext.Provider
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 498a2ee39b..5636626279 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -1,6 +1,8 @@
+import { getWebSocketToken } from "@/lib/supabase/actions";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { createBrowserClient } from "@supabase/ssr";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { proxyApiRequest, proxyFileUpload } from "./proxy-action";
import type {
AddUserCreditsResponse,
AnalyticsDetails,
@@ -761,50 +763,25 @@ export default class BackendAPI {
return this._request("GET", path, query);
}
- private async _uploadFile(path: string, file: File): Promise<string> {
- // Get session with retry logic
- let token = "no-token-found";
- let retryCount = 0;
- const maxRetries = 3;
-
- while (retryCount < maxRetries) {
- const supabaseClient = await this.getSupabaseClient();
- const {
- data: { session },
- } = (await supabaseClient?.auth.getSession()) || {
- data: { session: null },
- };
-
- if (session?.access_token) {
- token = session.access_token;
- break;
- }
+ private async getAuthToken(): Promise<string> {
+ // Only try client-side session (for WebSocket connections)
+ // This will return "no-token-found" with httpOnly cookies, which is expected
+ const supabaseClient = await this.getSupabaseClient();
+ const {
+ data: { session },
+ } = (await supabaseClient?.auth.getSession()) || {
+ data: { session: null },
+ };
- retryCount++;
- if (retryCount < maxRetries) {
- await new Promise((resolve) => setTimeout(resolve, 100 * retryCount));
- }
- }
+ return session?.access_token || "no-token-found";
+ }
- // Create a FormData object and append the file
+ private async _uploadFile(path: string, file: File): Promise<string> {
const formData = new FormData();
formData.append("file", file);
- const response = await fetch(this.baseUrl + path, {
- method: "POST",
- headers: {
- ...(token && { Authorization: `Bearer ${token}` }),
- },
- body: formData,
- });
-
- if (!response.ok) {
- throw new Error(`Error uploading file: ${response.statusText}`);
- }
-
- // Parse the response appropriately
- const media_url = await response.text();
- return media_url;
+ // Use proxy server action for secure file upload
+ return await proxyFileUpload(path, formData, this.baseUrl);
}
private async _request(
@@ -816,103 +793,13 @@ export default class BackendAPI {
console.debug(`${method} ${path} payload:`, payload);
}
- // Get session with retry logic
- let token = "no-token-found";
- let retryCount = 0;
- const maxRetries = 3;
-
- while (retryCount < maxRetries) {
- const supabaseClient = await this.getSupabaseClient();
- const {
- data: { session },
- } = (await supabaseClient?.auth.getSession()) || {
- data: { session: null },
- };
-
- if (session?.access_token) {
- token = session.access_token;
- break;
- }
-
- retryCount++;
- if (retryCount < maxRetries) {
- await new Promise((resolve) => setTimeout(resolve, 100 * retryCount));
- }
- }
-
- let url = this.baseUrl + path;
- const payloadAsQuery = ["GET", "DELETE"].includes(method);
- if (payloadAsQuery && payload) {
- // For GET requests, use payload as query
- const queryParams = new URLSearchParams(payload);
- url += `?${queryParams.toString()}`;
- }
-
- const hasRequestBody = !payloadAsQuery && payload !== undefined;
- const response = await fetch(url, {
+ // Always use proxy server action to not expose any auth tokens to the browser
+ return await proxyApiRequest({
method,
- headers: {
- ...(hasRequestBody && { "Content-Type": "application/json" }),
- ...(token && { Authorization: `Bearer ${token}` }),
- },
- body: hasRequestBody ? JSON.stringify(payload) : undefined,
+ path,
+ payload,
+ baseUrl: this.baseUrl,
});
-
- if (!response.ok) {
- console.warn(`${method} ${path} returned non-OK response:`, response);
-
- // console.warn("baseClient is attempting to redirect by changing window location")
- // if (
- // response.status === 403 &&
- // response.statusText === "Not authenticated" &&
- // typeof window !== "undefined" // Check if in browser environment
- // ) {
- // window.location.href = "/login";
- // }
-
- let errorDetail;
- try {
- const errorData = await response.json();
- if (
- Array.isArray(errorData.detail) &&
- errorData.detail.length > 0 &&
- errorData.detail[0].loc
- ) {
- // This appears to be a Pydantic validation error
- const errors = errorData.detail.map(
- (err: _PydanticValidationError) => {
- const location = err.loc.join(" -> ");
- return `${location}: ${err.msg}`;
- },
- );
- errorDetail = errors.join("\n");
- } else {
- errorDetail = errorData.detail || response.statusText;
- }
- } catch {
- errorDetail = response.statusText;
- }
-
- throw new Error(errorDetail);
- }
-
- // Handle responses with no content (like DELETE requests)
- if (
- response.status === 204 ||
- response.headers.get("Content-Length") === "0"
- ) {
- return null;
- }
-
- try {
- return await response.json();
- } catch (e) {
- if (e instanceof SyntaxError) {
- console.warn(`${method} ${path} returned invalid JSON:`, e);
- return null;
- }
- throw e;
- }
}
////////////////////////////////////////
@@ -1000,10 +887,19 @@ export default class BackendAPI {
async connectWebSocket(): Promise<void> {
return (this.wsConnecting ??= new Promise(async (resolve, reject) => {
try {
- const supabaseClient = await this.getSupabaseClient();
- const token =
- (await supabaseClient?.auth.getSession())?.data.session
- ?.access_token || "";
+ let token = "";
+ try {
+ const { token: serverToken, error } = await getWebSocketToken();
+ if (serverToken && !error) {
+ token = serverToken;
+ } else if (error) {
+ console.warn("Failed to get WebSocket token from server:", error);
+ }
+ } catch (error) {
+ console.warn("Failed to get token for WebSocket connection:", error);
+ // Continue with empty token, connection might still work
+ }
+
const wsUrlWithToken = `${this.wsUrl}?token=${token}`;
this.webSocket = new WebSocket(wsUrlWithToken);
this.webSocket.state = "connecting";
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts
new file mode 100644
index 0000000000..c9ee05d0e3
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts
@@ -0,0 +1,236 @@
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
+
+export function buildRequestUrl(
+ baseUrl: string,
+ path: string,
+ method: string,
+ payload?: Record<string, any>,
+): string {
+ let url = baseUrl + path;
+ const payloadAsQuery = ["GET", "DELETE"].includes(method);
+
+ if (payloadAsQuery && payload) {
+ const queryParams = new URLSearchParams(payload);
+ url += `?${queryParams.toString()}`;
+ }
+
+ return url;
+}
+
+export async function getServerAuthToken(): Promise<string> {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ throw new Error("Supabase client not available");
+ }
+
+ try {
+ const {
+ data: { session },
+ error,
+ } = await supabase.auth.getSession();
+
+ if (error || !session?.access_token) {
+ return "no-token-found";
+ }
+
+ return session.access_token;
+ } catch (error) {
+ console.error("Failed to get auth token:", error);
+ return "no-token-found";
+ }
+}
+
+export function createRequestHeaders(
+ token: string,
+ hasRequestBody: boolean,
+ contentType: string = "application/json",
+): Record<string, string> {
+ const headers: Record<string, string> = {};
+
+ if (hasRequestBody) {
+ headers["Content-Type"] = contentType;
+ }
+
+ if (token && token !== "no-token-found") {
+ headers["Authorization"] = `Bearer ${token}`;
+ }
+
+ return headers;
+}
+
+export function serializeRequestBody(
+ payload: any,
+ contentType: string = "application/json",
+): string {
+ switch (contentType) {
+ case "application/json":
+ return JSON.stringify(payload);
+ case "application/x-www-form-urlencoded":
+ return new URLSearchParams(payload).toString();
+ default:
+ // For custom content types, assume payload is already properly formatted
+ return typeof payload === "string" ? payload : JSON.stringify(payload);
+ }
+}
+
+export async function parseApiError(response: Response): Promise<string> {
+ try {
+ const errorData = await response.json();
+
+ if (
+ Array.isArray(errorData.detail) &&
+ errorData.detail.length > 0 &&
+ errorData.detail[0].loc
+ ) {
+ // Pydantic validation error
+ const errors = errorData.detail.map((err: any) => {
+ const location = err.loc.join(" -> ");
+ return `${location}: ${err.msg}`;
+ });
+ return errors.join("\n");
+ }
+
+ return errorData.detail || response.statusText;
+ } catch {
+ return response.statusText;
+ }
+}
+
+export async function parseApiResponse(response: Response): Promise<any> {
+ // Handle responses with no content
+ if (
+ response.status === 204 ||
+ response.headers.get("Content-Length") === "0"
+ ) {
+ return null;
+ }
+
+ try {
+ return await response.json();
+ } catch (e) {
+ if (e instanceof SyntaxError) {
+ return null;
+ }
+ throw e;
+ }
+}
+
+function isAuthenticationError(
+ response: Response,
+ errorDetail: string,
+): boolean {
+ return (
+ response.status === 401 ||
+ response.status === 403 ||
+ errorDetail.toLowerCase().includes("not authenticated") ||
+ errorDetail.toLowerCase().includes("unauthorized") ||
+ errorDetail.toLowerCase().includes("authentication failed")
+ );
+}
+
+function isLogoutInProgress(): boolean {
+ if (typeof window === "undefined") return false;
+
+ try {
+ // Check if logout was recently triggered
+ const logoutTimestamp = window.localStorage.getItem("supabase-logout");
+ if (logoutTimestamp) {
+ const timeDiff = Date.now() - parseInt(logoutTimestamp);
+ // Consider logout in progress for 5 seconds after trigger
+ return timeDiff < 5000;
+ }
+
+ // Check if we're being redirected to login
+ return (
+ window.location.pathname.includes("/login") ||
+ window.location.pathname.includes("/logout")
+ );
+ } catch {
+ return false;
+ }
+}
+
+export async function makeAuthenticatedRequest(
+ method: string,
+ url: string,
+ payload?: Record<string, any>,
+ contentType: string = "application/json",
+): Promise<any> {
+ const token = await getServerAuthToken();
+ const payloadAsQuery = ["GET", "DELETE"].includes(method);
+ const hasRequestBody = !payloadAsQuery && payload !== undefined;
+
+ const response = await fetch(url, {
+ method,
+ headers: createRequestHeaders(token, hasRequestBody, contentType),
+ body: hasRequestBody
+ ? serializeRequestBody(payload, contentType)
+ : undefined,
+ });
+
+ if (!response.ok) {
+ const errorDetail = await parseApiError(response);
+
+ // Handle authentication errors gracefully during logout
+ if (isAuthenticationError(response, errorDetail)) {
+ if (isLogoutInProgress()) {
+ // Silently return null during logout to prevent error noise
+ console.debug(
+ "Authentication request failed during logout, ignoring:",
+ errorDetail,
+ );
+ return null;
+ }
+
+ // For authentication errors outside logout, log but don't throw
+ // This prevents crashes when session expires naturally
+ console.warn("Authentication failed:", errorDetail);
+ return null;
+ }
+
+ // For other errors, throw as normal
+ throw new Error(errorDetail);
+ }
+
+ return parseApiResponse(response);
+}
+
+export async function makeAuthenticatedFileUpload(
+ url: string,
+ formData: FormData,
+): Promise<string> {
+ const token = await getServerAuthToken();
+
+ const headers: Record<string, string> = {};
+ if (token && token !== "no-token-found") {
+ headers["Authorization"] = `Bearer ${token}`;
+ }
+
+ // Don't set Content-Type for FormData - let the browser set it with boundary
+ const response = await fetch(url, {
+ method: "POST",
+ headers,
+ body: formData,
+ });
+
+ if (!response.ok) {
+ // Handle authentication errors gracefully for file uploads too
+ const errorMessage = `Error uploading file: ${response.statusText}`;
+
+ if (response.status === 401 || response.status === 403) {
+ if (isLogoutInProgress()) {
+ console.debug(
+ "File upload authentication failed during logout, ignoring",
+ );
+ return "";
+ }
+ console.warn("File upload authentication failed:", errorMessage);
+ return "";
+ }
+
+ throw new Error(errorMessage);
+ }
+
+ return await response.text();
+}
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/proxy-action.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/proxy-action.ts
new file mode 100644
index 0000000000..74a5d3de91
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/proxy-action.ts
@@ -0,0 +1,51 @@
+"use server";
+
+import * as Sentry from "@sentry/nextjs";
+import {
+ buildRequestUrl,
+ makeAuthenticatedFileUpload,
+ makeAuthenticatedRequest,
+} from "./helpers";
+
+const DEFAULT_BASE_URL = "http://localhost:8006/api";
+
+export interface ProxyRequestOptions {
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
+ path: string;
+ payload?: Record<string, any>;
+ baseUrl?: string;
+ contentType?: string;
+}
+
+export async function proxyApiRequest({
+ method,
+ path,
+ payload,
+ baseUrl = process.env.NEXT_PUBLIC_AGPT_SERVER_URL || DEFAULT_BASE_URL,
+ contentType = "application/json",
+}: ProxyRequestOptions) {
+ return await Sentry.withServerActionInstrumentation(
+ "proxyApiRequest",
+ {},
+ async () => {
+ const url = buildRequestUrl(baseUrl, path, method, payload);
+ return makeAuthenticatedRequest(method, url, payload, contentType);
+ },
+ );
+}
+
+export async function proxyFileUpload(
+ path: string,
+ formData: FormData,
+ baseUrl = process.env.NEXT_PUBLIC_AGPT_SERVER_URL ||
+ "http://localhost:8006/api",
+): Promise<string> {
+ return await Sentry.withServerActionInstrumentation(
+ "proxyFileUpload",
+ {},
+ async () => {
+ const url = baseUrl + path;
+ return makeAuthenticatedFileUpload(url, formData);
+ },
+ );
+}
diff --git a/autogpt_platform/frontend/src/lib/supabase/SESSION_VALIDATION.md b/autogpt_platform/frontend/src/lib/supabase/SESSION_VALIDATION.md
new file mode 100644
index 0000000000..482ceb27fc
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/supabase/SESSION_VALIDATION.md
@@ -0,0 +1,180 @@
+# Server-Side Session Validation with httpOnly Cookies
+
+This implementation ensures that Supabase session validation is always performed on the server side using httpOnly cookies for improved security.
+
+## Key Features
+
+- **httpOnly Cookies**: Session cookies are inaccessible to client-side JavaScript, preventing XSS attacks
+- **Server-Side Authentication**: All API requests are authenticated on the server using httpOnly cookies
+- **Automatic Request Proxying**: All BackendAPI requests are automatically proxied through server actions
+- **File Upload Support**: File uploads work seamlessly with httpOnly cookie authentication
+- **Zero Code Changes**: Existing BackendAPI usage continues to work without modifications
+- **Cross-Tab Logout**: Logout events are still synchronized across browser tabs
+
+## How It Works
+
+All API requests made through `BackendAPI` are automatically proxied through server actions that:
+
+1. Retrieve the JWT token from server-side httpOnly cookies
+2. Make the authenticated request to the backend API
+3. Return the response to the client
+
+This includes both regular API calls and file uploads, all handled transparently!
+
+## Usage
+
+### Client Components
+
+No changes needed! The existing `useSupabase` hook and `useBackendAPI` continue to work:
+
+```tsx
+"use client";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+
+function MyComponent() {
+ const { user, isLoggedIn, isUserLoading, logOut } = useSupabase();
+ const api = useBackendAPI();
+
+ if (isUserLoading) return <div>Loading...</div>;
+ if (!isLoggedIn) return <div>Please log in</div>;
+
+ // Regular API calls use secure server-side authentication
+ const handleGetGraphs = async () => {
+ const graphs = await api.listGraphs();
+ console.log(graphs);
+ };
+
+ // File uploads also work with secure authentication
+ const handleFileUpload = async (file: File) => {
+ try {
+ const mediaUrl = await api.uploadStoreSubmissionMedia(file);
+ console.log("Uploaded:", mediaUrl);
+ } catch (error) {
+ console.error("Upload failed:", error);
+ }
+ };
+
+ return (
+ <div>
+ <p>Welcome, {user?.email}!</p>
+ <button onClick={handleGetGraphs}>Get Graphs</button>
+ <input
+ type="file"
+ onChange={(e) =>
+ e.target.files?.[0] && handleFileUpload(e.target.files[0])
+ }
+ />
+ <button onClick={logOut}>Log Out</button>
+ </div>
+ );
+}
+```
+
+### Server Components
+
+No changes needed! Server components continue to work as before:
+
+```tsx
+import { validateSession, getCurrentUser } from "@/lib/supabase/actions";
+import { redirect } from "next/navigation";
+
+async function MyServerComponent() {
+ const { user, error } = await getCurrentUser();
+
+ if (error || !user) {
+ redirect("/login");
+ }
+
+ return <div>Welcome, {user.email}!</div>;
+}
+```
+
+### Server Actions
+
+No changes needed! Server actions continue to work as before:
+
+```tsx
+"use server";
+import { validateSession } from "@/lib/supabase/actions";
+import BackendAPI from "@/lib/autogpt-server-api";
+import { redirect } from "next/navigation";
+
+export async function myServerAction() {
+ const { user, isValid } = await validateSession("/current-path");
+
+ if (!isValid || !user) {
+ redirect("/login");
+ return;
+ }
+
+ // This automatically uses secure server-side authentication
+ const api = new BackendAPI();
+ const graphs = await api.listGraphs();
+
+ return graphs;
+}
+```
+
+### API Calls and File Uploads
+
+All operations use the same simple code everywhere:
+
+```tsx
+// Works the same in both client and server contexts
+const api = new BackendAPI();
+
+// Regular API requests
+const graphs = await api.listGraphs();
+const user = await api.createUser();
+const onboarding = await api.getUserOnboarding();
+
+// File uploads
+const file = new File(["content"], "example.txt", { type: "text/plain" });
+const mediaUrl = await api.uploadStoreSubmissionMedia(file);
+```
+
+## Available Server Actions
+
+- `validateSession(currentPath)` - Validates the current session and returns user data
+- `getCurrentUser()` - Gets the current user without path validation
+- `serverLogout()` - Logs out the user server-side
+- `refreshSession()` - Refreshes the current session
+
+## Internal Architecture
+
+### Request Flow
+
+All API requests (including file uploads) follow this flow:
+
+1. **Any API call**: `api.listGraphs()` or `api.uploadStoreSubmissionMedia(file)`
+2. **Proxy server action**: `proxyApiRequest()` or `proxyFileUpload()` handles the request
+3. **Server authentication**: Gets JWT from httpOnly cookies
+4. **Backend request**: Makes authenticated request to backend API
+5. **Response**: Returns data to the calling code
+
+### File Upload Implementation
+
+File uploads are handled through a dedicated `proxyFileUpload` server action that:
+
+- Receives the file data as FormData on the server
+- Retrieves authentication tokens from httpOnly cookies
+- Forwards the authenticated upload request to the backend
+- Returns the upload result to the client
+
+## Security Benefits
+
+1. **XSS Protection**: httpOnly cookies can't be accessed by malicious scripts
+2. **CSRF Protection**: Combined with SameSite cookie settings
+3. **Server-Side Validation**: Session validation always happens on the trusted server
+4. **Zero Token Exposure**: JWT tokens never exposed to client-side JavaScript
+5. **Zero Attack Surface**: No client-side session manipulation possible
+6. **Secure File Uploads**: File uploads maintain the same security model
+
+## Migration Notes
+
+- **No code changes required** - all existing BackendAPI usage continues to work
+- File uploads now work seamlessly with httpOnly cookies
+- Cross-tab logout functionality is preserved
+- WebSocket connections may need reconnection after session changes
+- All requests now have consistent security behavior
diff --git a/autogpt_platform/frontend/src/lib/supabase/actions.ts b/autogpt_platform/frontend/src/lib/supabase/actions.ts
new file mode 100644
index 0000000000..2cf49a2447
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/supabase/actions.ts
@@ -0,0 +1,223 @@
+"use server";
+import * as Sentry from "@sentry/nextjs";
+import type { User } from "@supabase/supabase-js";
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { getRedirectPath } from "./helpers";
+import { getServerSupabase } from "./server/getServerSupabase";
+
+export interface SessionValidationResult {
+ user: User | null;
+ isValid: boolean;
+ redirectPath?: string;
+}
+
+export async function validateSession(
+ currentPath: string,
+): Promise<SessionValidationResult> {
+ return await Sentry.withServerActionInstrumentation(
+ "validateSession",
+ {},
+ async () => {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ return {
+ user: null,
+ isValid: false,
+ redirectPath: getRedirectPath(currentPath) || undefined,
+ };
+ }
+
+ try {
+ const {
+ data: { user },
+ error,
+ } = await supabase.auth.getUser();
+
+ if (error || !user) {
+ const redirectPath = getRedirectPath(currentPath);
+ return {
+ user: null,
+ isValid: false,
+ redirectPath: redirectPath || undefined,
+ };
+ }
+
+ return {
+ user,
+ isValid: true,
+ };
+ } catch (error) {
+ console.error("Session validation error:", error);
+ const redirectPath = getRedirectPath(currentPath);
+ return {
+ user: null,
+ isValid: false,
+ redirectPath: redirectPath || undefined,
+ };
+ }
+ },
+ );
+}
+
+export async function getCurrentUser(): Promise<{
+ user: User | null;
+ error?: string;
+}> {
+ return await Sentry.withServerActionInstrumentation(
+ "getCurrentUser",
+ {},
+ async () => {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ return {
+ user: null,
+ error: "Supabase client not available",
+ };
+ }
+
+ try {
+ const {
+ data: { user },
+ error,
+ } = await supabase.auth.getUser();
+
+ if (error) {
+ return {
+ user: null,
+ error: error.message,
+ };
+ }
+
+ return { user };
+ } catch (error) {
+ console.error("Get current user error:", error);
+ return {
+ user: null,
+ error: error instanceof Error ? error.message : "Unknown error",
+ };
+ }
+ },
+ );
+}
+
+export async function getWebSocketToken(): Promise<{
+ token: string | null;
+ error?: string;
+}> {
+ return await Sentry.withServerActionInstrumentation(
+ "getWebSocketToken",
+ {},
+ async () => {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ return {
+ token: null,
+ error: "Supabase client not available",
+ };
+ }
+
+ try {
+ const {
+ data: { session },
+ error,
+ } = await supabase.auth.getSession();
+
+ if (error) {
+ return {
+ token: null,
+ error: error.message,
+ };
+ }
+
+ return { token: session?.access_token || null };
+ } catch (error) {
+ console.error("Get WebSocket token error:", error);
+ return {
+ token: null,
+ error: error instanceof Error ? error.message : "Unknown error",
+ };
+ }
+ },
+ );
+}
+
+export type ServerLogoutOptions = {
+ globalLogout?: boolean;
+};
+
+export async function serverLogout(options: ServerLogoutOptions = {}) {
+ return await Sentry.withServerActionInstrumentation(
+ "serverLogout",
+ {},
+ async () => {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ redirect("/login");
+ return;
+ }
+
+ try {
+ const { error } = await supabase.auth.signOut({
+ scope: options.globalLogout ? "global" : "local",
+ });
+
+ if (error) {
+ console.error("Error logging out:", error);
+ }
+ } catch (error) {
+ console.error("Logout error:", error);
+ }
+
+ // Clear all cached data and redirect
+ revalidatePath("/", "layout");
+ redirect("/login");
+ },
+ );
+}
+
+export async function refreshSession() {
+ return await Sentry.withServerActionInstrumentation(
+ "refreshSession",
+ {},
+ async () => {
+ const supabase = await getServerSupabase();
+
+ if (!supabase) {
+ return {
+ user: null,
+ error: "Supabase client not available",
+ };
+ }
+
+ try {
+ const {
+ data: { user },
+ error,
+ } = await supabase.auth.refreshSession();
+
+ if (error) {
+ return {
+ user: null,
+ error: error.message,
+ };
+ }
+
+ // Revalidate the layout to update server components
+ revalidatePath("/", "layout");
+
+ return { user };
+ } catch (error) {
+ console.error("Refresh session error:", error);
+ return {
+ user: null,
+ error: error instanceof Error ? error.message : "Unknown error",
+ };
+ }
+ },
+ );
+}
diff --git a/autogpt_platform/frontend/src/lib/supabase/helpers.ts b/autogpt_platform/frontend/src/lib/supabase/helpers.ts
index 4d44c1ab07..2118b0e474 100644
--- a/autogpt_platform/frontend/src/lib/supabase/helpers.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/helpers.ts
@@ -1,4 +1,7 @@
-// Session management constants and utilities
+import { type CookieOptions } from "@supabase/ssr";
+
+// Detect if we're in a Playwright test environment
+const isTest = process.env.NEXT_PUBLIC_PW_TEST === "true";
export const PROTECTED_PAGES = [
"/monitor",
@@ -15,6 +18,20 @@ export const STORAGE_KEYS = {
LOGOUT: "supabase-logout",
} as const;
+export function getCookieSettings(): Partial<CookieOptions> {
+ if (isTest)
+ return {
+ secure: false,
+ sameSite: "lax",
+ };
+
+ return {
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax",
+ httpOnly: true,
+ } as const;
+}
+
// Page protection utilities
export function isProtectedPage(pathname: string): boolean {
return PROTECTED_PAGES.some((page) => pathname.startsWith(page));
diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts
index 55cfab6544..333b535fbd 100644
--- a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts
@@ -1,8 +1,15 @@
"use client";
-import { useEffect, useMemo, useState, useRef } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { User } from "@supabase/supabase-js";
-import { useRouter } from "next/navigation";
+import { usePathname, useRouter } from "next/navigation";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ getCurrentUser,
+ refreshSession,
+ serverLogout,
+ ServerLogoutOptions,
+ validateSession,
+} from "../actions";
import {
broadcastLogout,
getRedirectPath,
@@ -12,16 +19,23 @@ import {
export function useSupabase() {
const router = useRouter();
+ const pathname = usePathname();
const [user, setUser] = useState<User | null>(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const lastValidationRef = useRef<number>(0);
+ const isValidatingRef = useRef(false);
const supabase = useMemo(() => {
try {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
- { isSingleton: true },
+ {
+ isSingleton: true,
+ auth: {
+ persistSession: false, // Don't persist session on client with httpOnly cookies
+ },
+ },
);
} catch (error) {
console.error("Error creating Supabase client", error);
@@ -29,75 +43,92 @@ export function useSupabase() {
}
}, []);
- async function logOut() {
- if (!supabase) return;
-
+ async function logOut(options: ServerLogoutOptions = {}) {
broadcastLogout();
- const { error } = await supabase.auth.signOut({
- scope: "global",
- });
- if (error) console.error("Error logging out:", error);
-
- router.push("/login");
+ try {
+ await serverLogout(options);
+ } catch (error) {
+ console.error("Error logging out:", error);
+ router.push("/login");
+ }
}
- async function validateSession() {
- if (!supabase) return false;
+ async function validateSessionServer() {
+ // Prevent concurrent validation calls
+ if (isValidatingRef.current) return true;
// Simple debounce - only validate if 2 seconds have passed
const now = Date.now();
if (now - lastValidationRef.current < 2000) {
return true;
}
+
+ isValidatingRef.current = true;
lastValidationRef.current = now;
try {
- const {
- data: { user: apiUser },
- error,
- } = await supabase.auth.getUser();
+ const result = await validateSession(pathname);
- if (error || !apiUser) {
- // Session is invalid, clear local state
+ if (!result.isValid) {
setUser(null);
- const redirectPath = getRedirectPath(window.location.pathname);
- if (redirectPath) {
- router.push(redirectPath);
+ if (result.redirectPath) {
+ router.push(result.redirectPath);
}
return false;
}
- // Update local state if we have a valid user but no local user
- if (apiUser && !user) {
- setUser(apiUser);
+ // Update local state with server user data
+ if (result.user) {
+ setUser((currentUser) => {
+ // Only update if user actually changed to prevent unnecessary re-renders
+ if (currentUser?.id !== result.user?.id) {
+ return result.user;
+ }
+ return currentUser;
+ });
}
return true;
} catch (error) {
console.error("Session validation error:", error);
setUser(null);
- const redirectPath = getRedirectPath(window.location.pathname);
+ const redirectPath = getRedirectPath(pathname);
if (redirectPath) {
router.push(redirectPath);
}
return false;
+ } finally {
+ isValidatingRef.current = false;
}
}
- function handleCrossTabLogout(e: StorageEvent) {
- if (!isLogoutEvent(e)) return;
+ async function getUserFromServer() {
+ try {
+ const { user: serverUser, error } = await getCurrentUser();
+
+ if (error || !serverUser) {
+ setUser(null);
+ return null;
+ }
- // Clear the Supabase session first
- if (supabase) {
- supabase.auth.signOut({ scope: "global" }).catch(console.error);
+ setUser(serverUser);
+ return serverUser;
+ } catch (error) {
+ console.error("Get user error:", error);
+ setUser(null);
+ return null;
}
+ }
+
+ function handleCrossTabLogout(e: StorageEvent) {
+ if (!isLogoutEvent(e)) return;
// Clear local state immediately
setUser(null);
router.refresh();
- const redirectPath = getRedirectPath(window.location.pathname);
+ const redirectPath = getRedirectPath(pathname);
if (redirectPath) {
router.push(redirectPath);
}
@@ -105,36 +136,20 @@ export function useSupabase() {
function handleVisibilityChange() {
if (document.visibilityState === "visible") {
- validateSession();
+ validateSessionServer();
}
}
function handleFocus() {
- validateSession();
+ validateSessionServer();
}
useEffect(() => {
- if (!supabase) {
- setIsUserLoading(false);
- return;
- }
-
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((_, session) => {
- const newUser = session?.user ?? null;
-
- // Only update if user actually changed to prevent unnecessary re-renders
- setUser((currentUser) => {
- if (currentUser?.id !== newUser?.id) {
- return newUser;
- }
- return currentUser;
- });
-
+ getUserFromServer().finally(() => {
setIsUserLoading(false);
});
+ // Set up event listeners for cross-tab logout, focus, and visibility change
const eventListeners = setupSessionEventListeners(
handleVisibilityChange,
handleFocus,
@@ -142,17 +157,17 @@ export function useSupabase() {
);
return () => {
- subscription.unsubscribe();
eventListeners.cleanup();
};
- }, [supabase]);
+ }, []);
return {
- supabase,
+ supabase, // Available for non-auth operations like real-time subscriptions
user,
isLoggedIn: !isUserLoading ? !!user : null,
isUserLoading,
logOut,
- validateSession,
+ validateSession: validateSessionServer,
+ refreshSession,
};
}
diff --git a/autogpt_platform/frontend/src/lib/supabase/middleware.ts b/autogpt_platform/frontend/src/lib/supabase/middleware.ts
index 0710daea71..0d5607abb2 100644
--- a/autogpt_platform/frontend/src/lib/supabase/middleware.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/middleware.ts
@@ -1,6 +1,6 @@
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
-import { isAdminPage, isProtectedPage } from "./helpers";
+import { getCookieSettings, isAdminPage, isProtectedPage } from "./helpers";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -32,9 +32,12 @@ export async function updateSession(request: NextRequest) {
supabaseResponse = NextResponse.next({
request,
});
- cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options),
- );
+ cookiesToSet.forEach(({ name, value, options }) => {
+ supabaseResponse.cookies.set(name, value, {
+ ...options,
+ ...getCookieSettings(),
+ });
+ });
},
},
},
diff --git a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
index da85a5195a..e0acc6a600 100644
--- a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
@@ -1,4 +1,5 @@
import { createServerClient, type CookieOptions } from "@supabase/ssr";
+import { getCookieSettings } from "../helpers";
type Cookies = { name: string; value: string; options?: CookieOptions }[];
@@ -19,9 +20,12 @@ export async function getServerSupabase() {
},
setAll(cookiesToSet: Cookies) {
try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options),
- );
+ cookiesToSet.forEach(({ name, value, options }) => {
+ cookieStore.set(name, value, {
+ ...options,
+ ...getCookieSettings(),
+ });
+ });
} catch {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing