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): support same-origin self-hosted routing (#13757)
Nicholas Tindlec038eb5ee5bc
diff --git a/autogpt_platform/frontend/orval.config.ts b/autogpt_platform/frontend/orval.config.tsindex 9e09467518..55e26d42f2 100644--- a/autogpt_platform/frontend/orval.config.ts+++ b/autogpt_platform/frontend/orval.config.ts@@ -18,7 +18,7 @@ export default defineConfig({indexFiles: false,mock: {type: "msw",- baseUrl: "http://localhost:3000/api/proxy",+ baseUrl: "/api/proxy",generateEachHttpStatus: true,delay: 0,},diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.tsindex 2422f33ec8..288c05a1ed 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts@@ -87,13 +87,14 @@ afterEach(() => {describe("auth callback GET — session handling", () => {it("redirects to the auth-code-error page when there is no session", async () => {+ vi.stubEnv("BETTER_AUTH_URL", "https://autogpt.example.com");getServerSessionMock.mockResolvedValue(null);const response = await GET(makeCallbackRequest());expect(response.status).toBe(307);expect(response.headers.get("location")).toBe(- `${origin}/auth/auth-code-error`,+ "https://autogpt.example.com/auth/auth-code-error",);expect(postV1GetOrCreateUserMock).not.toHaveBeenCalled();});@@ -148,31 +149,51 @@ describe("auth callback GET — account creation tracking", () => {});describe("auth callback GET — redirect target resolution", () => {- it("honors the next query parameter in development without consulting x-forwarded-host", async () => {+ it("uses the canonical HTTPS origin and ignores a malicious forwarded host", async () => {vi.stubEnv("NODE_ENV", "development");+ vi.stubEnv("BETTER_AUTH_URL", "https://autogpt.example.com");loggedInWithCompletedSetup();const response = await GET(makeCallbackRequest("/auth/callback?next=/marketplace", {- "x-forwarded-host": "app.example.com",+ "x-forwarded-host": "evil.example.com",}),);- expect(response.headers.get("location")).toBe(`${origin}/marketplace`);+ expect(response.headers.get("location")).toBe(+ "https://autogpt.example.com/marketplace",+ );+ });++ it("preserves a canonical HTTP origin for LAN deployments", async () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("BETTER_AUTH_URL", "http://192.168.1.20:3000");+ loggedInWithCompletedSetup();++ const response = await GET(+ makeCallbackRequest("/auth/callback?next=/marketplace", {+ "x-forwarded-host": "evil.example.com",+ }),+ );++ expect(response.headers.get("location")).toBe(+ "http://192.168.1.20:3000/marketplace",+ );});- it("redirects through the forwarded host in production", async () => {+ it("falls back to NEXT_PUBLIC_FRONTEND_BASE_URL for the canonical origin", async () => {vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://public.example.com");loggedInWithCompletedSetup();const response = await GET(makeCallbackRequest("/auth/callback?next=/marketplace", {- "x-forwarded-host": "app.example.com",+ "x-forwarded-host": "evil.example.com",}),);expect(response.headers.get("location")).toBe(- "https://app.example.com/marketplace",+ "https://public.example.com/marketplace",);});@@ -187,20 +208,21 @@ describe("auth callback GET — redirect target resolution", () => {expect(response.headers.get("location")).toBe(`${origin}/marketplace`);});- it("ignores an off-site next and cannot open-redirect via the forwarded host", async () => {+ it("ignores an off-site next and cannot open-redirect via forwarded headers", async () => {vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("BETTER_AUTH_URL", "https://autogpt.example.com");loggedInWithCompletedSetup(); // shouldShowOnboarding: false -> /copilotfor (const evil of ["@evil.com", "//evil.com", "https://evil.com"]) {const response = await GET(makeCallbackRequest(`/auth/callback?next=${encodeURIComponent(evil)}`, {- "x-forwarded-host": "app.example.com",+ "x-forwarded-host": "evil.example.com",}),);// sanitizeAuthNext drops the crafted value, so we land on the resolved// in-app target under our own host — never evil.com.expect(response.headers.get("location")).toBe(- "https://app.example.com/copilot",+ "https://autogpt.example.com/copilot",);}});@@ -212,6 +234,7 @@ describe("auth callback GET — user creation failures", () => {});it("redirects to auth-token-invalid when the backend rejects with 401", async () => {+ vi.stubEnv("BETTER_AUTH_URL", "https://autogpt.example.com");postV1GetOrCreateUserMock.mockRejectedValue(new BackendApiErrorStub("Unauthorized", 401),);@@ -219,7 +242,7 @@ describe("auth callback GET — user creation failures", () => {const response = await GET(makeCallbackRequest());expect(response.headers.get("location")).toBe(- `${origin}/error?message=auth-token-invalid`,+ "https://autogpt.example.com/error?message=auth-token-invalid",);});diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.tsindex 9fb8d9e08e..edd7f51f80 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts@@ -15,8 +15,24 @@ import { NextResponse } from "next/server";// cookie, then redirects here because this is the `callbackURL` we hand it in// /api/auth/login/with-provider. So by the time we run, the session already// exists and we only provision the backend user and decide where to send them.+function getPublicOrigin(requestOrigin: string) {+ const configuredURL =+ process.env.BETTER_AUTH_URL || process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;+ if (!configuredURL) return requestOrigin;++ try {+ const url = new URL(configuredURL);+ return url.protocol === "http:" || url.protocol === "https:"+ ? url.origin+ : requestOrigin;+ } catch {+ return requestOrigin;+ }+}+export async function GET(request: Request) {- const { searchParams, origin } = new URL(request.url);+ const { searchParams, origin: requestOrigin } = new URL(request.url);+ const publicOrigin = getPublicOrigin(requestOrigin);let next = "/copilot";@@ -59,14 +75,18 @@ export async function GET(request: Request) {if (apiError.status === 401) {// Authentication issues - token missing/invalidreturn NextResponse.redirect(- `${origin}/error?message=auth-token-invalid`,+ `${publicOrigin}/error?message=auth-token-invalid`,);} else if (apiError.status >= 500) {// Server/database errors- return NextResponse.redirect(`${origin}/error?message=server-error`);+ return NextResponse.redirect(+ `${publicOrigin}/error?message=server-error`,+ );} else if (apiError.status === 429) {// Rate limiting- return NextResponse.redirect(`${origin}/error?message=rate-limited`);+ return NextResponse.redirect(+ `${publicOrigin}/error?message=rate-limited`,+ );}}@@ -75,27 +95,20 @@ export async function GET(request: Request) {createUserError instanceof TypeError &&createUserError.message.includes("fetch")) {- return NextResponse.redirect(`${origin}/error?message=network-error`);+ return NextResponse.redirect(+ `${publicOrigin}/error?message=network-error`,+ );}// Generic user creation failurereturn NextResponse.redirect(- `${origin}/error?message=user-creation-failed`,+ `${publicOrigin}/error?message=user-creation-failed`,);}- const forwardedHost = request.headers.get("x-forwarded-host"); // original origin before load balancer- const isLocalEnv = process.env.NODE_ENV === "development";- if (isLocalEnv) {- // we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host- return NextResponse.redirect(`${origin}${next}`);- } else if (forwardedHost) {- return NextResponse.redirect(`https://${forwardedHost}${next}`);- } else {- return NextResponse.redirect(`${origin}${next}`);- }+ return NextResponse.redirect(`${publicOrigin}${next}`);}// return the user to an error page with instructions- return NextResponse.redirect(`${origin}/auth/auth-code-error`);+ return NextResponse.redirect(`${publicOrigin}/auth/auth-code-error`);}diff --git a/autogpt_platform/frontend/src/app/(platform)/reset-password/__tests__/actions.test.ts b/autogpt_platform/frontend/src/app/(platform)/reset-password/__tests__/actions.test.tsindex 1d5a850707..1df70f8ef4 100644--- a/autogpt_platform/frontend/src/app/(platform)/reset-password/__tests__/actions.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/reset-password/__tests__/actions.test.ts@@ -42,8 +42,9 @@ afterEach(() => {});describe("sendResetEmail", () => {- it("requests a reset link that redirects back to the configured origin", async () => {- vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://platform.agpt.test");+ it("prefers the runtime Better Auth origin for reset links", async () => {+ vi.stubEnv("BETTER_AUTH_URL", "https://runtime.agpt.test");+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://build.agpt.test");requestPasswordResetMock.mockResolvedValue({ status: true });const result = await sendResetEmail("[email protected]");@@ -51,13 +52,29 @@ describe("sendResetEmail", () => {expect(requestPasswordResetMock).toHaveBeenCalledWith({body: {email: "[email protected]",- redirectTo: "https://platform.agpt.test/reset-password",+ redirectTo: "https://runtime.agpt.test/reset-password",},});expect(result).toBeUndefined();});- it("falls back to localhost when no frontend base URL is configured", async () => {+ it("falls back to the frontend base URL without a Better Auth URL", async () => {+ vi.stubEnv("BETTER_AUTH_URL", "");+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://build.agpt.test");+ requestPasswordResetMock.mockResolvedValue({ status: true });++ await sendResetEmail("[email protected]");++ expect(requestPasswordResetMock).toHaveBeenCalledWith({+ body: {+ email: "[email protected]",+ redirectTo: "https://build.agpt.test/reset-password",+ },+ });+ });++ it("falls back to localhost when no public origin is configured", async () => {+ vi.stubEnv("BETTER_AUTH_URL", "");vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "");requestPasswordResetMock.mockResolvedValue({ status: true });@@ -100,7 +117,7 @@ describe("changePassword", () => {const result = await changePassword("new-secure-password", "token-123");expect(resetPasswordMock).toHaveBeenCalledWith({- body: { newPassword: "new-secure-password", token: "token-123" },+ body: { newPassword: "new-secure-password", token: "token-123" }, // pragma: allowlist secret});expect(redirectMock).toHaveBeenCalledWith("/login");expect(result).toBeUndefined();diff --git a/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts b/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.tsindex 07679d6eac..7b2b8cefbc 100644--- a/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/reset-password/actions.ts@@ -10,7 +10,9 @@ export async function sendResetEmail(email: string) {{},async () => {const origin =- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "http://localhost:3000";+ process.env.BETTER_AUTH_URL ||+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL ||+ "http://localhost:3000";try {// Better Auth emails a link that redirects to@@ -18,7 +20,7 @@ export async function sendResetEmail(email: string) {await auth.api.requestPasswordReset({body: {email,- redirectTo: `${origin}/reset-password`,+ redirectTo: new URL("/reset-password", origin).toString(),},});} catch (error) {diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.tsindex 6f6a28e590..170a375bdb 100644--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts@@ -78,6 +78,12 @@ describe("customMutator — impersonation header", () => {expect(headers[IMPERSONATION_HEADER_NAME]).toBeUndefined();});+ it("routes browser requests through the same-origin API proxy", async () => {+ await customMutator("/test", { method: "GET" });++ expect(fetch).toHaveBeenCalledWith("/api/proxy/test", expect.any(Object));+ });+it("coexists with pre-existing caller-supplied headers without overwriting them", async () => {mockGetSystemHeaders.mockReturnValue({[IMPERSONATION_HEADER_NAME]: "impersonated-user-abc",diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.tsindex ddbf53a1a6..5dc9369581 100644--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts@@ -10,17 +10,13 @@ import { getDatafastAttribution } from "@/services/analytics/datafast-attributioimport { environment } from "@/services/environment";import { transformDates } from "./date-transformer";-const FRONTEND_BASE_URL =- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "http://localhost:3000";-const API_PROXY_BASE_URL = `${FRONTEND_BASE_URL}/api/proxy`; // Sending request via nextjs Server--const getBaseUrl = (): string => {+function getBaseURL(): string {if (!environment.isServerSide()) {- return API_PROXY_BASE_URL;+ return "/api/proxy";} else {return environment.getAGPTServerBaseUrl();}-};+}const getBody = async <T>(c: Response | Request): Promise<T> => {// 204 No Content responses (and 200s with Content-Length: 0) have no body.@@ -90,7 +86,7 @@ export const customMutator = async <headers["Content-Type"] = "application/json";}- const baseUrl = getBaseUrl();+ const baseUrl = getBaseURL();// The caching in React Query in our system depends on the url, so the base_url could be different for the server and client sides.// here url also contains encoded query paramsdiff --git a/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.tsindex 14a147d860..ad161f3474 100644--- a/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts+++ b/autogpt_platform/frontend/src/lib/__tests__/direct-upload.test.ts@@ -10,17 +10,21 @@ import {} from "../direct-upload";const getTokenMock = vi.hoisted(() => vi.fn());+const getServerBaseUrlMock = vi.hoisted(() =>+ vi.fn(() => "http://backend.test"),+);vi.mock("@/lib/auth/actions", () => ({getWebSocketToken: getTokenMock,}));beforeEach(() => {getTokenMock.mockResolvedValue({ token: "test-token" });+ getServerBaseUrlMock.mockReturnValue("http://backend.test");});vi.mock("@/services/environment", () => ({environment: {- getAGPTServerBaseUrl: () => "http://backend.test",+ getAGPTServerBaseUrl: getServerBaseUrlMock,},}));@@ -85,6 +89,22 @@ describe("uploadSubmissionMediaDirect", () => {expect(fetchMock.mock.calls[0]?.[1]?.body).toBeInstanceOf(FormData);});+ it("preserves a same-origin backend path prefix", async () => {+ getServerBaseUrlMock.mockReturnValue("http://autogpt.test/_agpt");+ const fetchMock = mockFetchOnce({+ ok: true,+ status: 200,+ json: () => "http://autogpt.test/media/uploaded.png",+ });++ await uploadSubmissionMediaDirect(makeFile(10));++ expect(fetchMock).toHaveBeenCalledWith(+ "http://autogpt.test/_agpt/api/store/submissions/media",+ expect.any(Object),+ );+ });+it("surfaces a clear size message on HTTP 413 instead of a bare status", async () => {mockFetchOnce({ ok: false, status: 413, statusText: "Payload Too Large" });diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/getServerAuthToken.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/getServerAuthToken.test.tsindex b883a139f4..b4fa3df836 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/getServerAuthToken.test.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/__tests__/getServerAuthToken.test.ts@@ -50,7 +50,8 @@ beforeEach(() => {async () => ({ getAll: () => getAllCookiesMock() }) as CookieStore,);vi.stubGlobal("fetch", fetchMock);- vi.stubEnv("BETTER_AUTH_URL", "http://auth.internal:3000");+ vi.stubEnv("BETTER_AUTH_URL", "https://autogpt.example.com");+ vi.stubEnv("BETTER_AUTH_INTERNAL_URL", "http://auth.internal:3000");vi.spyOn(console, "error").mockImplementation(() => undefined);});@@ -121,6 +122,24 @@ describe("getServerAuthToken", () => {);});+ it("falls back to the public Better Auth URL without an internal URL", async () => {+ vi.stubEnv("BETTER_AUTH_INTERNAL_URL", "");+ getAllCookiesMock.mockReturnValue([+ { name: "better-auth.session_token", value: "session-fresh" },+ ]);+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ token: makeJwt(3600) }), { status: 200 }),+ );+ const getServerAuthToken = await importGetServerAuthToken();++ await getServerAuthToken();++ expect(fetchMock).toHaveBeenCalledWith(+ "https://autogpt.example.com/api/auth/token",+ expect.any(Object),+ );+ });+it("recognizes the __Secure-prefixed session cookie", async () => {const jwt = makeJwt(3600);getAllCookiesMock.mockReturnValue([diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.tsindex 3ad69a4ced..4a2dd357e1 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts@@ -159,6 +159,7 @@ export const getServerAuthToken = cache(async (): Promise<string | null> => {.join("; ");const baseURL =+ process.env.BETTER_AUTH_INTERNAL_URL ||process.env.BETTER_AUTH_URL ||process.env.NEXT_PUBLIC_FRONTEND_BASE_URL ||"http://localhost:3000";diff --git a/autogpt_platform/frontend/src/lib/direct-upload.ts b/autogpt_platform/frontend/src/lib/direct-upload.tsindex 7eb3582868..e616a6267e 100644--- a/autogpt_platform/frontend/src/lib/direct-upload.ts+++ b/autogpt_platform/frontend/src/lib/direct-upload.ts@@ -78,7 +78,9 @@ async function postFileToBackend({throw new Error("Authentication error — please sign in again.");}- const url = new URL(path, environment.getAGPTServerBaseUrl());+ const baseURL = new URL(environment.getAGPTServerBaseUrl());+ baseURL.pathname = `${baseURL.pathname.replace(/\/$/, "")}/${path.replace(/^\//, "")}`;+ const url = baseURL;for (const [key, value] of Object.entries(searchParams ?? {})) {url.searchParams.set(key, value);}diff --git a/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.ts b/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.tsindex f16095ef1f..6882295e9a 100644--- a/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.ts+++ b/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.ts@@ -20,18 +20,13 @@ describe("share viewer path builders", () => {});describe("share viewer absolute URL builders", () => {- const ORIGINAL_ENV = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;-beforeEach(() => {- delete process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;+ vi.stubEnv("BETTER_AUTH_URL", "");+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "");});afterEach(() => {- if (ORIGINAL_ENV === undefined) {- delete process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;- } else {- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = ORIGINAL_ENV;- }+ vi.unstubAllEnvs();vi.unstubAllGlobals();});@@ -45,22 +40,39 @@ describe("share viewer absolute URL builders", () => {});test("executionShareUrl uses NEXT_PUBLIC_FRONTEND_BASE_URL when set", () => {- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = "https://shared.example.com";- vi.stubGlobal("window", {- location: { origin: "https://app.example.com" },- });+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://shared.example.com");+ vi.stubGlobal("window", undefined);+expect(executionShareUrl("abc-123")).toBe("https://shared.example.com/share/abc-123",);});- test("chatShareUrl prefers env var over window.location", () => {- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = "https://shared.example.com";+ test("server-generated URLs prefer BETTER_AUTH_URL", () => {+ vi.stubEnv("BETTER_AUTH_URL", "https://runtime.example.com");+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://build.example.com");+ vi.stubGlobal("window", undefined);++ expect(chatShareUrl("abc-123")).toBe(+ "https://runtime.example.com/share/chat/abc-123",+ );+ });++ test("server-generated URLs have a safe local fallback", () => {+ vi.stubGlobal("window", undefined);++ expect(executionShareUrl("abc-123")).toBe(+ "http://localhost:3000/share/abc-123",+ );+ });++ test("browser URLs use the live origin instead of a build-time value", () => {+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://build.example.com");vi.stubGlobal("window", {location: { origin: "https://app.example.com" },});- expect(chatShareUrl("abc-123")).toBe(- "https://shared.example.com/share/chat/abc-123",+ expect(executionShareUrl("abc-123")).toBe(+ "https://app.example.com/share/abc-123",);});});diff --git a/autogpt_platform/frontend/src/lib/share/routes.ts b/autogpt_platform/frontend/src/lib/share/routes.tsindex b858d6bdd2..1fcd0efabd 100644--- a/autogpt_platform/frontend/src/lib/share/routes.ts+++ b/autogpt_platform/frontend/src/lib/share/routes.ts@@ -4,15 +4,14 @@// joins the platform, add functions here and grep won't find anything// else to touch.-function getBaseUrl(): string {- // ``NEXT_PUBLIC_FRONTEND_BASE_URL`` lets the backend's share URL and- // the frontend's share URL match in environments where Next.js is- // proxied behind a different host than its window.location. Falls- // back to the current origin in dev.- if (typeof window === "undefined") {- return process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "";- }- return process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || window.location.origin;+function getBaseURL(): string {+ if (typeof window !== "undefined") return window.location.origin;++ return (+ process.env.BETTER_AUTH_URL ||+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL ||+ "http://localhost:3000"+ );}export function executionSharePath(token: string): string {@@ -24,11 +23,11 @@ export function chatSharePath(token: string): string {}export function executionShareUrl(token: string): string {- return `${getBaseUrl()}${executionSharePath(token)}`;+ return `${getBaseURL()}${executionSharePath(token)}`;}export function chatShareUrl(token: string): string {- return `${getBaseUrl()}${chatSharePath(token)}`;+ return `${getBaseURL()}${chatSharePath(token)}`;}// ---------- Per-share file download URL + matcher --------------------------diff --git a/autogpt_platform/frontend/src/services/environment/__tests__/index.test.ts b/autogpt_platform/frontend/src/services/environment/__tests__/index.test.tsnew file mode 100644index 0000000000..412ecadbe7--- /dev/null+++ b/autogpt_platform/frontend/src/services/environment/__tests__/index.test.ts@@ -0,0 +1,72 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { environment } from "../index";++afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});++describe("AutoGPT server URL resolution", () => {+ it("resolves a relative browser API URL against an HTTP origin", () => {+ vi.stubGlobal("window", {+ location: { origin: "http://autogpt.local:3000" },+ });+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/backend/api");++ expect(environment.getAGPTServerApiUrl()).toBe(+ "http://autogpt.local:3000/backend/api",+ );+ expect(environment.getAGPTServerBaseUrl()).toBe(+ "http://autogpt.local:3000/backend",+ );+ });++ it("resolves a relative browser API URL against an HTTPS origin", () => {+ vi.stubGlobal("window", {+ location: { origin: "https://autogpt.example.com" },+ });+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/backend/api");++ expect(environment.getAGPTServerApiUrl()).toBe(+ "https://autogpt.example.com/backend/api",+ );+ });++ it("resolves a relative browser WebSocket URL using ws over HTTP", () => {+ vi.stubGlobal("window", {+ location: { origin: "http://autogpt.local:3000" },+ });+ vi.stubEnv("NEXT_PUBLIC_AGPT_WS_SERVER_URL", "/backend/ws");++ expect(environment.getAGPTWsServerUrl()).toBe(+ "ws://autogpt.local:3000/backend/ws",+ );+ });++ it("resolves a relative browser WebSocket URL using wss over HTTPS", () => {+ vi.stubGlobal("window", {+ location: { origin: "https://autogpt.example.com" },+ });+ vi.stubEnv("NEXT_PUBLIC_AGPT_WS_SERVER_URL", "/backend/ws");++ expect(environment.getAGPTWsServerUrl()).toBe(+ "wss://autogpt.example.com/backend/ws",+ );+ });++ it("leaves explicit server-side backend URLs untouched", () => {+ vi.stubGlobal("window", undefined);+ vi.stubEnv("AGPT_SERVER_URL", "http://backend.internal:8006/api");+ vi.stubEnv("AGPT_WS_SERVER_URL", "ws://backend.internal:8001/ws");+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/backend/api");+ vi.stubEnv("NEXT_PUBLIC_AGPT_WS_SERVER_URL", "/backend/ws");++ expect(environment.getAGPTServerApiUrl()).toBe(+ "http://backend.internal:8006/api",+ );+ expect(environment.getAGPTWsServerUrl()).toBe(+ "ws://backend.internal:8001/ws",+ );+ });+});diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.tsindex dd2d70f9c7..40b4d2049a 100644--- a/autogpt_platform/frontend/src/services/environment/index.ts+++ b/autogpt_platform/frontend/src/services/environment/index.ts@@ -29,7 +29,9 @@ function getAGPTServerApiUrl() {return process.env.AGPT_SERVER_URL;}- return process.env.NEXT_PUBLIC_AGPT_SERVER_URL || "http://localhost:8006/api";+ const url =+ process.env.NEXT_PUBLIC_AGPT_SERVER_URL || "http://localhost:8006/api";+ return resolveBrowserURL(url);}function getAGPTServerBaseUrl() {@@ -41,7 +43,19 @@ function getAGPTWsServerUrl() {return process.env.AGPT_WS_SERVER_URL;}- return process.env.NEXT_PUBLIC_AGPT_WS_SERVER_URL || "ws://localhost:8001/ws";+ const configuredURL =+ process.env.NEXT_PUBLIC_AGPT_WS_SERVER_URL || "ws://localhost:8001/ws";+ if (environment.isServerSide()) return configuredURL;++ const url = new URL(configuredURL, window.location.origin);+ if (url.protocol === "http:") url.protocol = "ws:";+ if (url.protocol === "https:") url.protocol = "wss:";+ return url.toString();+}++function resolveBrowserURL(url: string) {+ if (environment.isServerSide()) return url;+ return new URL(url, window.location.origin).toString();}function getEnvironmentStr() {