π OpenHands: AI-Driven Development
Fix authentication (#4686)
Robert Brennan456998175fe8
diff --git a/frontend/src/api/open-hands.ts b/frontend/src/api/open-hands.tsindex 93bbb1af46..6f004862c2 100644--- a/frontend/src/api/open-hands.ts+++ b/frontend/src/api/open-hands.ts@@ -1,4 +1,4 @@-import { getValidFallbackHost } from "#/utils/get-valid-fallback-host";+import { request } from "#/services/api";import {SaveFileSuccessResponse,FileUploadSuccessResponse,@@ -9,36 +9,13 @@ import {GetConfigResponse,} from "./open-hands.types";-/**- * Generate the base URL of the OpenHands API- * @returns Base URL of the OpenHands API- */-const generateBaseURL = () => {- const fallback = getValidFallbackHost();- const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || fallback;-- if (typeof window === "undefined") {- return `http://${baseUrl}`;- }- return `${window.location.protocol}//${baseUrl}`;-};--/**- * Class to interact with the OpenHands API- */class OpenHands {- /**- * Base URL of the OpenHands API- */- static BASE_URL = generateBaseURL();-/*** Retrieve the list of models available* @returns List of models available*/static async getModels(): Promise<string[]> {- const response = await fetch(`${OpenHands.BASE_URL}/api/options/models`);- return response.json();+ return request("/api/options/models");}/**@@ -46,8 +23,7 @@ class OpenHands {* @returns List of agents available*/static async getAgents(): Promise<string[]> {- const response = await fetch(`${OpenHands.BASE_URL}/api/options/agents`);- return response.json();+ return request(`/api/options/agents`);}/**@@ -55,175 +31,118 @@ class OpenHands {* @returns List of security analyzers available*/static async getSecurityAnalyzers(): Promise<string[]> {- const response = await fetch(- `${OpenHands.BASE_URL}/api/options/security-analyzers`,- );- return response.json();+ return request(`/api/options/security-analyzers`);}static async getConfig(): Promise<GetConfigResponse> {- const response = await fetch("config.json", {- headers: {- "Cache-Control": "no-cache",- },- });- return response.json();+ return request("/config.json");}/*** Retrieve the list of files available in the workspace- * @param token User token provided by the server* @param path Path to list files from* @returns List of files available in the given path. If path is not provided, it lists all the files in the workspace*/- static async getFiles(token: string, path?: string): Promise<string[]> {- const url = new URL(`${OpenHands.BASE_URL}/api/list-files`);- if (path) url.searchParams.append("path", path);-- const response = await fetch(url.toString(), {- headers: {- Authorization: `Bearer ${token}`,- },- });-- return response.json();+ static async getFiles(path?: string): Promise<string[]> {+ let url = "/api/list-files";+ if (path) url += `?path=${encodeURIComponent(path)}`;+ return request(url);}/*** Retrieve the content of a file- * @param token User token provided by the server* @param path Full path of the file to retrieve* @returns Content of the file*/- static async getFile(token: string, path: string): Promise<string> {- const url = new URL(`${OpenHands.BASE_URL}/api/select-file`);- url.searchParams.append("file", path);- const response = await fetch(url.toString(), {- headers: {- Authorization: `Bearer ${token}`,- },- });-- const data = await response.json();+ static async getFile(path: string): Promise<string> {+ const url = `/api/select-file?file=${encodeURIComponent(path)}`;+ const data = await request(url);return data.code;}/*** Save the content of a file- * @param token User token provided by the server* @param path Full path of the file to save* @param content Content to save in the file* @returns Success message or error message*/static async saveFile(- token: string,path: string,content: string,): Promise<SaveFileSuccessResponse | ErrorResponse> {- const response = await fetch(`${OpenHands.BASE_URL}/api/save-file`, {+ return request(`/api/save-file`, {method: "POST",body: JSON.stringify({ filePath: path, content }),headers: {- Authorization: `Bearer ${token}`,"Content-Type": "application/json",},});-- return response.json();}/*** Upload a file to the workspace- * @param token User token provided by the server* @param file File to upload* @returns Success message or error message*/static async uploadFiles(- token: string,file: File[],): Promise<FileUploadSuccessResponse | ErrorResponse> {const formData = new FormData();file.forEach((f) => formData.append("files", f));- const response = await fetch(`${OpenHands.BASE_URL}/api/upload-files`, {+ return request(`/api/upload-files`, {method: "POST",body: formData,- headers: {- Authorization: `Bearer ${token}`,- },});-- return response.json();}/*** Get the blob of the workspace zip- * @param token User token provided by the server* @returns Blob of the workspace zip*/- static async getWorkspaceZip(token: string): Promise<Blob> {- const response = await fetch(`${OpenHands.BASE_URL}/api/zip-directory`, {- headers: {- Authorization: `Bearer ${token}`,- },- });-+ static async getWorkspaceZip(): Promise<Blob> {+ const response = await request(`/api/zip-directory`, {}, false, true);return response.blob();}/*** Send feedback to the server- * @param token User token provided by the server* @param data Feedback data* @returns The stored feedback data*/- static async sendFeedback(- token: string,- data: Feedback,- ): Promise<FeedbackResponse> {- const response = await fetch(`${OpenHands.BASE_URL}/api/submit-feedback`, {+ static async submitFeedback(data: Feedback): Promise<FeedbackResponse> {+ return request(`/api/submit-feedback`, {method: "POST",body: JSON.stringify(data),headers: {- Authorization: `Bearer ${token}`,"Content-Type": "application/json",},});-- return response.json();}/**- * Get the GitHub access token* @param code Code provided by GitHub* @returns GitHub access token*/static async getGitHubAccessToken(code: string,): Promise<GitHubAccessTokenResponse> {- const response = await fetch(`${OpenHands.BASE_URL}/api/github/callback`, {+ return request(`/api/github/callback`, {method: "POST",body: JSON.stringify({ code }),headers: {"Content-Type": "application/json",},});-- return response.json();}/*** Authenticate with GitHub token- * @param token The GitHub access token* @returns Response with authentication status and user info if successful*/- static async authenticate(token: string): Promise<Response> {- return fetch(`${OpenHands.BASE_URL}/api/authenticate`, {+ static async authenticate(): Promise<Response> {+ return request(`/api/authenticate`, {method: "POST",- headers: {- "Content-Type": "application/json",- "X-GitHub-Token": token,- },});}}diff --git a/frontend/src/components/feedback-form.tsx b/frontend/src/components/feedback-form.tsxindex 4e1ddde635..078e4b0ccc 100644--- a/frontend/src/components/feedback-form.tsx+++ b/frontend/src/components/feedback-form.tsx@@ -1,8 +1,8 @@import React from "react";import hotToast from "react-hot-toast";import ModalButton from "./buttons/ModalButton";-import { request } from "#/services/api";import { Feedback } from "#/api/open-hands.types";+import OpenHands from "#/api/open-hands";const FEEDBACK_VERSION = "1.0";const VIEWER_PAGE = "https://www.all-hands.dev/share";@@ -71,13 +71,7 @@ export function FeedbackForm({ onClose, polarity }: FeedbackFormProps) {token: "",};- const response = await request("/api/submit-feedback", {- method: "POST",- body: JSON.stringify(feedback),- headers: {- "Content-Type": "application/json",- },- });+ const response = await OpenHands.submitFeedback(feedback);const { message, feedback_id, password } = response.body; // eslint-disable-lineconst link = `${VIEWER_PAGE}?share_id=${feedback_id}`;shareFeedbackToast(message, link, password);diff --git a/frontend/src/components/file-explorer/FileExplorer.tsx b/frontend/src/components/file-explorer/FileExplorer.tsxindex c61990b4d6..8db4460b1a 100644--- a/frontend/src/components/file-explorer/FileExplorer.tsx+++ b/frontend/src/components/file-explorer/FileExplorer.tsx@@ -118,52 +118,47 @@ function FileExplorer({ error, isOpen, onToggle }: FileExplorerProps) {return;}dispatch(setRefreshID(Math.random()));- // TODO: Get token from data loader- const token = localStorage.getItem("token");- if (token) OpenHands.getFiles(token).then(setPaths);+ OpenHands.getFiles().then(setPaths);revalidate();};const uploadFileData = async (files: FileList) => {try {- const token = localStorage.getItem("token");- if (token) {- const result = await OpenHands.uploadFiles(token, Array.from(files));+ const result = await OpenHands.uploadFiles(Array.from(files));- if (isOpenHandsErrorResponse(result)) {- // Handle error response- toast.error(- `upload-error-${new Date().getTime()}`,- result.error || t(I18nKey.EXPLORER$UPLOAD_ERROR_MESSAGE),- );- return;- }+ if (isOpenHandsErrorResponse(result)) {+ // Handle error response+ toast.error(+ `upload-error-${new Date().getTime()}`,+ result.error || t(I18nKey.EXPLORER$UPLOAD_ERROR_MESSAGE),+ );+ return;+ }- const uploadedCount = result.uploaded_files.length;- const skippedCount = result.skipped_files.length;+ const uploadedCount = result.uploaded_files.length;+ const skippedCount = result.skipped_files.length;- if (uploadedCount > 0) {- toast.success(- `upload-success-${new Date().getTime()}`,- t(I18nKey.EXPLORER$UPLOAD_SUCCESS_MESSAGE, {- count: uploadedCount,- }),- );- }-- if (skippedCount > 0) {- const message = t(I18nKey.EXPLORER$UPLOAD_PARTIAL_SUCCESS_MESSAGE, {- count: skippedCount,- });- toast.info(message);- }+ if (uploadedCount > 0) {+ toast.success(+ `upload-success-${new Date().getTime()}`,+ t(I18nKey.EXPLORER$UPLOAD_SUCCESS_MESSAGE, {+ count: uploadedCount,+ }),+ );+ }- if (uploadedCount === 0 && skippedCount === 0) {- toast.info(t(I18nKey.EXPLORER$NO_FILES_UPLOADED_MESSAGE));- }+ if (skippedCount > 0) {+ const message = t(I18nKey.EXPLORER$UPLOAD_PARTIAL_SUCCESS_MESSAGE, {+ count: skippedCount,+ });+ toast.info(message);+ }- refreshWorkspace();+ if (uploadedCount === 0 && skippedCount === 0) {+ toast.info(t(I18nKey.EXPLORER$NO_FILES_UPLOADED_MESSAGE));}++ refreshWorkspace();} catch (e) {// Handle unexpected errors (network issues, etc.)toast.error(diff --git a/frontend/src/components/file-explorer/TreeNode.tsx b/frontend/src/components/file-explorer/TreeNode.tsxindex fd44cd88cd..b3aa3c2833 100644--- a/frontend/src/components/file-explorer/TreeNode.tsx+++ b/frontend/src/components/file-explorer/TreeNode.tsx@@ -59,14 +59,11 @@ function TreeNode({ path, defaultOpen = false }: TreeNodeProps) {return;}- const token = localStorage.getItem("token");- if (token) {- try {- const newChildren = await OpenHands.getFiles(token, path);- setChildren(newChildren);- } catch (error) {- toast.error("Failed to fetch files");- }+ try {+ const newChildren = await OpenHands.getFiles(path);+ setChildren(newChildren);+ } catch (error) {+ toast.error("Failed to fetch files");}};@@ -77,15 +74,13 @@ function TreeNode({ path, defaultOpen = false }: TreeNodeProps) {}, [refreshID, isOpen]);const handleClick = async () => {- const token = localStorage.getItem("token");-if (isDirectory) {setIsOpen((prev) => !prev);- } else if (token) {+ } else {const code = modifiedFiles[path] || files[path];try {- const fetchedCode = await OpenHands.getFile(token, path);+ const fetchedCode = await OpenHands.getFile(path);setSelectedPath(path);if (!code || fetchedCode !== files[path]) {setFileContent(path, fetchedCode);diff --git a/frontend/src/context/socket.tsx b/frontend/src/context/socket.tsxindex 1c3b42a93c..14c6cfeefe 100644--- a/frontend/src/context/socket.tsx+++ b/frontend/src/context/socket.tsx@@ -1,7 +1,6 @@import React from "react";import { Data } from "ws";import EventLogger from "#/utils/event-logger";-import { getValidFallbackHost } from "#/utils/get-valid-fallback-host";interface WebSocketClientOptions {token: string | null;@@ -46,8 +45,8 @@ function SocketProvider({ children }: SocketProviderProps) {);}- const fallback = getValidFallbackHost();- const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || fallback;+ const baseUrl =+ import.meta.env.VITE_BACKEND_BASE_URL || window?.location.host;const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";const sessionToken = options?.token || "NO_JWT"; // not allowed to be empty or duplicatedconst ghToken = localStorage.getItem("ghToken") || "NO_GITHUB";diff --git a/frontend/src/routes/_oh.app._index/code-editor-component.tsx b/frontend/src/routes/_oh.app._index/code-editor-component.tsxindex 9288fc225e..8182805193 100644--- a/frontend/src/routes/_oh.app._index/code-editor-component.tsx+++ b/frontend/src/routes/_oh.app._index/code-editor-component.tsx@@ -36,8 +36,7 @@ function CodeEditorCompoonent({if (content) {try {- const token = localStorage.getItem("token")?.toString();- if (token) await OpenHands.saveFile(token, selectedPath, content);+ await OpenHands.saveFile(selectedPath, content);} catch (error) {toast.error("Failed to save file");}diff --git a/frontend/src/routes/_oh.app._index/route.tsx b/frontend/src/routes/_oh.app._index/route.tsxindex 7f63350f12..6ef5f5762a 100644--- a/frontend/src/routes/_oh.app._index/route.tsx+++ b/frontend/src/routes/_oh.app._index/route.tsx@@ -1,6 +1,6 @@import React from "react";import { useSelector } from "react-redux";-import { json, useLoaderData, useRouteError } from "@remix-run/react";+import { json, useRouteError } from "@remix-run/react";import toast from "react-hot-toast";import { editor } from "monaco-editor";import { EditorProps } from "@monaco-editor/react";@@ -8,7 +8,6 @@ import { RootState } from "#/store";import AgentState from "#/types/AgentState";import FileExplorer from "#/components/file-explorer/FileExplorer";import OpenHands from "#/api/open-hands";-import { useSocket } from "#/context/socket";import CodeEditorCompoonent from "./code-editor-component";import { useFiles } from "#/context/files";import { EditorActions } from "#/components/editor-actions";@@ -30,8 +29,7 @@ export function ErrorBoundary() {}function CodeEditor() {- const { token } = useLoaderData<typeof clientLoader>();- const { runtimeActive } = useSocket();+ const { curAgentState } = useSelector((state: RootState) => state.agent);const {setPaths,selectedPath,@@ -70,15 +68,14 @@ function CodeEditor() {);React.useEffect(() => {- // only retrieve files if connected to WS to prevent requesting before runtime is ready- if (runtimeActive && token) {- OpenHands.getFiles(token)+ if (curAgentState === AgentState.INIT) {+ OpenHands.getFiles().then(setPaths).catch(() => {setErrors({ getFiles: "Failed to retrieve files" });});}- }, [runtimeActive, token]);+ }, [curAgentState]);// Code editing is only allowed when the agent is paused, finished, or awaiting user input (server rules)const isEditingAllowed = React.useMemo(@@ -92,9 +89,9 @@ function CodeEditor() {const handleSave = async () => {if (selectedPath) {const content = modifiedFiles[selectedPath];- if (content && token) {+ if (content) {try {- await OpenHands.saveFile(token, selectedPath, content);+ await OpenHands.saveFile(selectedPath, content);saveNewFileContent(selectedPath);} catch (error) {toast.error("Failed to save file");diff --git a/frontend/src/routes/_oh.app.tsx b/frontend/src/routes/_oh.app.tsxindex 43659724d5..a2a4067b56 100644--- a/frontend/src/routes/_oh.app.tsx+++ b/frontend/src/routes/_oh.app.tsx@@ -72,9 +72,8 @@ const isAgentStateChange = (export const clientLoader = async () => {const ghToken = localStorage.getItem("ghToken");-try {- const isAuthed = await userIsAuthenticated(ghToken);+ const isAuthed = await userIsAuthenticated();if (!isAuthed) {clearSession();return redirect("/");@@ -290,21 +289,21 @@ function App() {React.useEffect(() => {(async () => {- if (runtimeActive && token && importedProjectZip) {+ if (runtimeActive && importedProjectZip) {// upload files actiontry {const blob = base64ToBlob(importedProjectZip);const file = new File([blob], "imported-project.zip", {type: blob.type,});- await OpenHands.uploadFiles(token, [file]);+ await OpenHands.uploadFiles([file]);dispatch(setImportedProjectZip(null));} catch (error) {toast.error("Failed to upload project files.");}}})();- }, [runtimeActive, token, importedProjectZip]);+ }, [runtimeActive, importedProjectZip]);const {isOpen: securityModalIsOpen,diff --git a/frontend/src/routes/_oh.tsx b/frontend/src/routes/_oh.tsxindex b4b1b35cb0..97f71da7a6 100644--- a/frontend/src/routes/_oh.tsx+++ b/frontend/src/routes/_oh.tsx@@ -10,6 +10,7 @@ import {Outlet,ClientLoaderFunctionArgs,} from "@remix-run/react";+import { useDispatch } from "react-redux";import { retrieveGitHubUser, isGitHubErrorReponse } from "#/api/github";import OpenHands from "#/api/open-hands";import CogTooth from "#/assets/cog-tooth";@@ -28,6 +29,8 @@ import DocsIcon from "#/assets/docs.svg?react";import { userIsAuthenticated } from "#/utils/user-is-authenticated";import { generateGitHubAuthUrl } from "#/utils/generate-github-auth-url";import { WaitlistModal } from "#/components/waitlist-modal";+import { setCurrentAgentState } from "#/state/agentSlice";+import AgentState from "#/types/AgentState";export const clientLoader = async ({ request }: ClientLoaderFunctionArgs) => {try {@@ -46,7 +49,7 @@ export const clientLoader = async ({ request }: ClientLoaderFunctionArgs) => {let githubAuthUrl: string | null = null;try {- isAuthed = await userIsAuthenticated(ghToken);+ isAuthed = await userIsAuthenticated();if (!isAuthed && window.__GITHUB_CLIENT_ID__) {const requestUrl = new URL(request.url);githubAuthUrl = generateGitHubAuthUrl(@@ -135,6 +138,7 @@ export default function MainApp() {} = useLoaderData<typeof clientLoader>();const logoutFetcher = useFetcher({ key: "logout" });const endSessionFetcher = useFetcher({ key: "end-session" });+ const dispatch = useDispatch();const [accountSettingsModalOpen, setAccountSettingsModalOpen] =React.useState(false);@@ -204,6 +208,7 @@ export default function MainApp() {const handleEndSession = () => {setStartNewProjectModalIsOpen(false);+ dispatch(setCurrentAgentState(AgentState.LOADING));// call new session action and redirect to '/'endSessionFetcher.submit(new FormData(), {method: "POST",diff --git a/frontend/src/routes/oauth.github.callback.tsx b/frontend/src/routes/oauth.github.callback.tsxindex 1dee5c06ba..9232d9e222 100644--- a/frontend/src/routes/oauth.github.callback.tsx+++ b/frontend/src/routes/oauth.github.callback.tsx@@ -14,15 +14,16 @@ export const clientLoader = async ({ request }: ClientLoaderFunctionArgs) => {const { access_token: accessToken } =await OpenHands.getGitHubAccessToken(code);- const authResponse = await OpenHands.authenticate(accessToken);+ localStorage.setItem("ghToken", accessToken);+ const authResponse = await OpenHands.authenticate();if (!authResponse.ok) {+ localStorage.removeItem("ghToken");return json({ error: "Failed to authenticate with GitHub" },{ status: authResponse.status },);}- localStorage.setItem("ghToken", accessToken);return redirect("/");}diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex 79746a6b14..dd67e2daf1 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -3,12 +3,23 @@ import toast from "#/utils/toast";const WAIT_FOR_AUTH_DELAY_MS = 500;+const UNAUTHED_ROUTE_PREFIXES = [+ "/api/authenticate",+ "/api/options/",+ "/config.json",+];+export async function request(url: string,options: RequestInit = {},disableToast: boolean = false,+ returnResponse: boolean = false,+ maxRetries: number = 3,/* eslint-disable-next-line @typescript-eslint/no-explicit-any */): Promise<any> {+ if (maxRetries < 0) {+ throw new Error("Max retries exceeded");+ }const onFail = (msg: string) => {if (!disableToast) {toast.error("api", msg);@@ -16,13 +27,17 @@ export async function request(throw new Error(msg);};- const needsAuth = !url.startsWith("/api/options/");+ const needsAuth = !UNAUTHED_ROUTE_PREFIXES.some((prefix) =>+ url.startsWith(prefix),+ );const token = getToken();const githubToken = getGitHubToken();if (!token && needsAuth) {return new Promise((resolve) => {setTimeout(() => {- resolve(request(url, options, disableToast));+ resolve(+ request(url, options, disableToast, returnResponse, maxRetries - 1),+ );}, WAIT_FOR_AUTH_DELAY_MS);});}@@ -56,6 +71,10 @@ export async function request(onFail(`Error fetching ${url}: ${response?.statusText}`);}+ if (returnResponse) {+ return response;+ }+try {return await (response && response.json());} catch (e) {diff --git a/frontend/src/utils/download-workspace.ts b/frontend/src/utils/download-workspace.tsindex 1bbf30612d..dc79141d5f 100644--- a/frontend/src/utils/download-workspace.ts+++ b/frontend/src/utils/download-workspace.ts@@ -4,12 +4,7 @@ import OpenHands from "#/api/open-hands";* Downloads the current workspace as a .zip file.*/export const downloadWorkspace = async () => {- const token = localStorage.getItem("token");- if (!token) {- throw new Error("No token found");- }-- const blob = await OpenHands.getWorkspaceZip(token);+ const blob = await OpenHands.getWorkspaceZip();const url = URL.createObjectURL(blob);const link = document.createElement("a");diff --git a/frontend/src/utils/get-valid-fallback-host.ts b/frontend/src/utils/get-valid-fallback-host.tsdeleted file mode 100644index 6b1482520e..0000000000--- a/frontend/src/utils/get-valid-fallback-host.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * Get the valid fallback host. Returns the host unless it is localhost, in which case it returns localhost:3000- * @returns Valid fallback host- *- * @example- * // If the host is localhost (e.g., localhost:5173), it returns localhost:3000- * const host = getValidFallbackHost(); // localhost:3000- *- * // If the host is not localhost, it returns the host- * const host = getValidFallbackHost(); // sub.example.com- */-export const getValidFallbackHost = () => {- if (typeof window !== "undefined") {- return window.location.host;- }-- // Fallback is localhost:3000 because that is the default port for the server- return "localhost:3000";-};diff --git a/frontend/src/utils/user-is-authenticated.ts b/frontend/src/utils/user-is-authenticated.tsindex 26f044fea7..137b866ad5 100644--- a/frontend/src/utils/user-is-authenticated.ts+++ b/frontend/src/utils/user-is-authenticated.ts@@ -1,9 +1,10 @@import OpenHands from "#/api/open-hands";-export const userIsAuthenticated = async (ghToken: string | null) => {- if (window.__APP_MODE__ !== "saas") return true;- if (!ghToken) return false;-- const authResponse = await OpenHands.authenticate(ghToken);- return authResponse.ok;+export const userIsAuthenticated = async () => {+ try {+ await OpenHands.authenticate();+ return true;+ } catch (error) {+ return false;+ }};