Skip to content

🙌 OpenHands: AI-Driven Development

feat: Add OAuth 2.0 Device Flow authentication for OpenHands Cloud backends (#381)

Rohit Malhotra2281f20f3eb4
diff --git a/.pr/pr-278/agent-run.gif b/.pr/pr-278/agent-run.gif
deleted file mode 100644
index 081097b934..0000000000
Binary files a/.pr/pr-278/agent-run.gif and /dev/null differ
diff --git a/__tests__/api/device-flow-client.test.ts b/__tests__/api/device-flow-client.test.ts
new file mode 100644
index 0000000000..806b21d260
--- /dev/null
+++ b/__tests__/api/device-flow-client.test.ts
@@ -0,0 +1,506 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ startDeviceFlow,
+ pollForToken,
+ isOpenHandsCloudHost,
+ DeviceFlowError,
+} from "../../src/api/device-flow-client";
+
+// Mock the backend registry to avoid import issues
+vi.mock("../../src/api/backend-registry/active-store", () => ({
+ getEffectiveLocalBackend: () => ({
+ host: "http://localhost:18000",
+ apiKey: "test-api-key",
+ }),
+}));
+
+vi.mock("../../src/api/backend-registry/auth", () => ({
+ buildAuthHeaders: () => ({ "X-Session-API-Key": "test-api-key" }),
+}));
+
+const TEST_HOST_URL = "https://app.all-hands.dev";
+
+describe("device-flow-client", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ describe("isOpenHandsCloudHost", () => {
+ it("returns true for all-hands.dev domains", () => {
+ expect(isOpenHandsCloudHost("https://app.all-hands.dev")).toBe(true);
+ expect(isOpenHandsCloudHost("https://staging.all-hands.dev")).toBe(true);
+ expect(isOpenHandsCloudHost("app.all-hands.dev")).toBe(true);
+ expect(isOpenHandsCloudHost("ALL-HANDS.DEV")).toBe(true);
+ expect(isOpenHandsCloudHost("all-hands.dev")).toBe(true);
+ });
+
+ it("returns true for openhands.dev domains", () => {
+ expect(isOpenHandsCloudHost("https://app.openhands.dev")).toBe(true);
+ expect(isOpenHandsCloudHost("openhands.dev")).toBe(true);
+ });
+
+ it("returns false for other domains", () => {
+ expect(isOpenHandsCloudHost("https://localhost:8000")).toBe(false);
+ expect(isOpenHandsCloudHost("http://127.0.0.1")).toBe(false);
+ expect(isOpenHandsCloudHost("https://example.com")).toBe(false);
+ expect(isOpenHandsCloudHost("https://my-openhands-server.com")).toBe(
+ false,
+ );
+ });
+
+ it("prevents substring matching attacks", () => {
+ // These should NOT be treated as trusted hosts
+ expect(isOpenHandsCloudHost("https://all-hands.dev.evil.com")).toBe(
+ false,
+ );
+ expect(isOpenHandsCloudHost("https://malicious-all-hands.dev")).toBe(
+ false,
+ );
+ expect(isOpenHandsCloudHost("https://evil.com/all-hands.dev")).toBe(
+ false,
+ );
+ });
+
+ it("returns false for invalid URLs", () => {
+ expect(isOpenHandsCloudHost("")).toBe(false);
+ expect(isOpenHandsCloudHost("not-a-url")).toBe(false);
+ });
+ });
+
+ describe("startDeviceFlow", () => {
+ it("returns device authorization response on success", async () => {
+ const mockResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: `${TEST_HOST_URL}/device`,
+ verification_uri_complete: `${TEST_HOST_URL}/device?user_code=USER-1234`,
+ expires_in: 600,
+ interval: 5,
+ };
+
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(mockResponse),
+ });
+
+ const result = await startDeviceFlow(TEST_HOST_URL);
+
+ expect(result).toEqual(mockResponse);
+ // Should call the local proxy endpoint
+ expect(fetch).toHaveBeenCalledWith(
+ "http://localhost:18000/api/cloud-proxy",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.objectContaining({
+ "Content-Type": "application/json",
+ "X-Session-API-Key": "test-api-key",
+ }),
+ }),
+ );
+ });
+
+ it("normalizes host URL by removing trailing slashes", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ device_code: "dc",
+ user_code: "uc",
+ verification_uri: "v",
+ verification_uri_complete: "vc",
+ expires_in: 600,
+ interval: 5,
+ }),
+ });
+
+ await startDeviceFlow(`${TEST_HOST_URL}///`);
+
+ // Verify the proxy body contains the normalized host
+ const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
+ const body = JSON.parse(fetchCall[1].body);
+ expect(body.host).toBe(TEST_HOST_URL);
+ });
+
+ it("throws DeviceFlowError on HTTP error", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 500,
+ text: () => Promise.resolve("Internal Server Error"),
+ });
+
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ DeviceFlowError,
+ );
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ /Failed to start device flow.*500/,
+ );
+ });
+
+ it("throws DeviceFlowError on missing required fields", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ device_code: "dc",
+ // Missing other required fields
+ }),
+ });
+
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ DeviceFlowError,
+ );
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ /missing required fields/,
+ );
+ });
+
+ it("throws DeviceFlowError on network error", async () => {
+ global.fetch = vi.fn().mockRejectedValue(new Error("Network failed"));
+
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ DeviceFlowError,
+ );
+ await expect(startDeviceFlow(TEST_HOST_URL)).rejects.toThrow(
+ /Network failed/,
+ );
+ });
+ });
+
+ describe("pollForToken", () => {
+ it("returns token response on immediate success", async () => {
+ const mockTokenResponse = {
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(mockTokenResponse),
+ });
+
+ const result = await pollForToken(TEST_HOST_URL, "device123", {
+ interval: 5,
+ });
+
+ expect(result).toEqual(mockTokenResponse);
+ // Should call the local proxy endpoint
+ expect(fetch).toHaveBeenCalledWith(
+ "http://localhost:18000/api/cloud-proxy",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.objectContaining({
+ "Content-Type": "application/json",
+ "X-Session-API-Key": "test-api-key",
+ }),
+ }),
+ );
+ });
+
+ it("polls until authorization is complete", async () => {
+ const pendingResponse = {
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "authorization_pending",
+ error_description: "User hasn't authorized yet",
+ }),
+ };
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ global.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(pendingResponse)
+ .mockResolvedValueOnce(successResponse);
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 1,
+ });
+
+ // Advance past the first poll interval
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("increases interval on slow_down error", async () => {
+ const slowDownResponse = {
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "slow_down",
+ interval: 10,
+ }),
+ };
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ global.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(slowDownResponse)
+ .mockResolvedValueOnce(successResponse);
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 5,
+ });
+
+ // Advance by new interval (10 seconds)
+ await vi.advanceTimersByTimeAsync(10000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ });
+
+ it("throws on expired_token error", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "expired_token",
+ }),
+ });
+
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", { interval: 1 }),
+ ).rejects.toThrow(DeviceFlowError);
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", { interval: 1 }),
+ ).rejects.toThrow(/expired/i);
+ });
+
+ it("throws on access_denied error", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "access_denied",
+ }),
+ });
+
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", { interval: 1 }),
+ ).rejects.toThrow(DeviceFlowError);
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", { interval: 1 }),
+ ).rejects.toThrow(/denied/i);
+ });
+
+ it("respects abort signal", async () => {
+ vi.useRealTimers(); // Use real timers for this test
+ const controller = new AbortController();
+
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "authorization_pending",
+ }),
+ });
+
+ // Pre-abort the controller
+ controller.abort();
+
+ // Now the promise should reject immediately with cancelled
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", {
+ interval: 1,
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow(/cancelled/i);
+ });
+
+ it("times out after specified duration", async () => {
+ vi.useRealTimers(); // Use real timers for this test
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "authorization_pending",
+ }),
+ });
+
+ // Use very short timeout
+ await expect(
+ pollForToken(TEST_HOST_URL, "device123", {
+ interval: 0.01, // 10ms interval
+ timeout: 50, // 50ms timeout
+ }),
+ ).rejects.toThrow(/timeout/i);
+ }, 10000);
+
+ it("caps slow_down interval at 30 seconds (DoS protection)", async () => {
+ const slowDownResponse = {
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "slow_down",
+ interval: 999999, // Malicious server tries to DoS
+ }),
+ };
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ global.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(slowDownResponse)
+ .mockResolvedValueOnce(successResponse);
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 5,
+ });
+
+ // Should use 30s max, not 999999s
+ await vi.advanceTimersByTimeAsync(30000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects non-numeric slow_down interval (type confusion protection)", async () => {
+ const slowDownResponse = {
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "slow_down",
+ interval: "pwned", // Non-numeric value
+ }),
+ };
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ global.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(slowDownResponse)
+ .mockResolvedValueOnce(successResponse);
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 5,
+ });
+
+ // With invalid interval, should use RFC 8628 default: current + 5s
+ // Starting interval is 5s, so next should be 10s (5000 + 5000 = 10000ms)
+ await vi.advanceTimersByTimeAsync(10000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ });
+
+ it("increments interval by 5 seconds per RFC 8628 when slow_down has no interval", async () => {
+ const slowDownResponse = {
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({
+ error: "slow_down",
+ // No interval field - RFC 8628 mandates +5s increment
+ }),
+ };
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ global.fetch = vi
+ .fn()
+ .mockResolvedValueOnce(slowDownResponse)
+ .mockResolvedValueOnce(successResponse);
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 5, // 5 seconds initial
+ });
+
+ // RFC 8628: must increment by 5 seconds, so 5s -> 10s
+ await vi.advanceTimersByTimeAsync(10000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ });
+
+ it("continues polling on network errors instead of failing immediately", async () => {
+ const networkError = new Error("Network failed");
+ const successResponse = {
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ }),
+ };
+
+ // First call fails with network error, second succeeds
+ global.fetch = vi
+ .fn()
+ .mockRejectedValueOnce(networkError)
+ .mockResolvedValueOnce(successResponse);
+
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {
+ interval: 1,
+ });
+
+ // Advance past the retry interval
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const result = await pollPromise;
+ expect(result.access_token).toBe("api-key-123");
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Network error during polling, retrying:",
+ networkError,
+ );
+
+ consoleSpy.mockRestore();
+ });
+ });
+});
diff --git a/__tests__/hooks/use-device-flow.test.ts b/__tests__/hooks/use-device-flow.test.ts
new file mode 100644
index 0000000000..3ad1dec09e
--- /dev/null
+++ b/__tests__/hooks/use-device-flow.test.ts
@@ -0,0 +1,302 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { renderHook, act, waitFor } from "@testing-library/react";
+import { useDeviceFlow } from "../../src/hooks/use-device-flow";
+import * as deviceFlowClient from "../../src/api/device-flow-client";
+
+vi.mock("../../src/api/device-flow-client", () => ({
+ startDeviceFlow: vi.fn(),
+ pollForToken: vi.fn(),
+ DeviceFlowError: class DeviceFlowError extends Error {
+ code?: string;
+ constructor(message: string, code?: string) {
+ super(message);
+ this.name = "DeviceFlowError";
+ this.code = code;
+ }
+ },
+}));
+
+describe("useDeviceFlow", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("initializes with idle state", () => {
+ const { result } = renderHook(() => useDeviceFlow());
+
+ expect(result.current.status).toBe("idle");
+ expect(result.current.verificationUrl).toBeNull();
+ expect(result.current.userCode).toBeNull();
+ expect(result.current.apiKey).toBeNull();
+ expect(result.current.error).toBeNull();
+ });
+
+ it("transitions through states on successful auth", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete:
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ const mockTokenResponse = {
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ };
+
+ // Make startDeviceFlow resolve after a tick to allow observing states
+ let resolveStart: (value: typeof mockAuthResponse) => void;
+ const startPromise = new Promise<typeof mockAuthResponse>((resolve) => {
+ resolveStart = resolve;
+ });
+
+ let resolvePoll: (value: typeof mockTokenResponse) => void;
+ const pollPromise = new Promise<typeof mockTokenResponse>((resolve) => {
+ resolvePoll = resolve;
+ });
+
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockReturnValue(startPromise);
+ vi.mocked(deviceFlowClient.pollForToken).mockReturnValue(pollPromise);
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ // Start the flow
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ // Should be starting
+ expect(result.current.status).toBe("starting");
+
+ // Resolve startDeviceFlow
+ await act(async () => {
+ resolveStart!(mockAuthResponse);
+ await Promise.resolve(); // flush microtasks
+ });
+
+ // Now should be awaiting_authorization
+ expect(result.current.status).toBe("awaiting_authorization");
+ expect(result.current.verificationUrl).toBe(
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ );
+ expect(result.current.userCode).toBe("USER-1234");
+
+ // Resolve pollForToken
+ await act(async () => {
+ resolvePoll!(mockTokenResponse);
+ await Promise.resolve(); // flush microtasks
+ });
+
+ // Now should be success
+ expect(result.current.status).toBe("success");
+ expect(result.current.apiKey).toBe("api-key-123");
+ });
+
+ it("handles startDeviceFlow error", async () => {
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockRejectedValue(
+ new deviceFlowClient.DeviceFlowError("Failed to start"),
+ );
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("error");
+ });
+
+ expect(result.current.error).toBe("Failed to start");
+ });
+
+ it("handles pollForToken error", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete:
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockResolvedValue(
+ mockAuthResponse,
+ );
+ vi.mocked(deviceFlowClient.pollForToken).mockRejectedValue(
+ new deviceFlowClient.DeviceFlowError("Access denied", "access_denied"),
+ );
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("error");
+ });
+
+ expect(result.current.error).toBe("Access denied");
+ expect(result.current.errorCode).toBe("access_denied");
+ });
+
+ it("cancels flow and resets to idle", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete:
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ // Make pollForToken hang indefinitely
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockResolvedValue(
+ mockAuthResponse,
+ );
+ vi.mocked(deviceFlowClient.pollForToken).mockImplementation(
+ () => new Promise(() => {}),
+ );
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("awaiting_authorization");
+ });
+
+ act(() => {
+ result.current.cancel();
+ });
+
+ expect(result.current.status).toBe("idle");
+ expect(result.current.verificationUrl).toBeNull();
+ });
+
+ it("resets to idle state", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete:
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ const mockTokenResponse = {
+ access_token: "api-key-123",
+ token_type: "Bearer",
+ };
+
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockResolvedValue(
+ mockAuthResponse,
+ );
+ vi.mocked(deviceFlowClient.pollForToken).mockResolvedValue(
+ mockTokenResponse,
+ );
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("success");
+ });
+
+ act(() => {
+ result.current.reset();
+ });
+
+ expect(result.current.status).toBe("idle");
+ expect(result.current.apiKey).toBeNull();
+ });
+
+ it("cancels previous flow when starting a new one", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete:
+ "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockResolvedValue(
+ mockAuthResponse,
+ );
+ vi.mocked(deviceFlowClient.pollForToken).mockImplementation(
+ () => new Promise(() => {}),
+ );
+
+ const { result } = renderHook(() => useDeviceFlow());
+
+ // Start first flow
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("awaiting_authorization");
+ });
+
+ // Start second flow (should cancel first)
+ act(() => {
+ result.current.start("https://staging.all-hands.dev");
+ });
+
+ // Should be starting again (first flow cancelled)
+ expect(result.current.status).toBe("starting");
+ });
+
+ it("cleans up on unmount without state update warnings", async () => {
+ const mockAuthResponse = {
+ device_code: "device123",
+ user_code: "USER-1234",
+ verification_uri: "https://app.all-hands.dev/device",
+ verification_uri_complete: "https://app.all-hands.dev/device?user_code=USER-1234",
+ expires_in: 600,
+ interval: 5,
+ };
+
+ vi.mocked(deviceFlowClient.startDeviceFlow).mockResolvedValue(
+ mockAuthResponse,
+ );
+ // Make pollForToken hang forever to simulate in-progress flow
+ vi.mocked(deviceFlowClient.pollForToken).mockImplementation(
+ () => new Promise(() => {}),
+ );
+
+ const { result, unmount } = renderHook(() => useDeviceFlow());
+
+ act(() => {
+ result.current.start("https://app.all-hands.dev");
+ });
+
+ await waitFor(() => {
+ expect(result.current.status).toBe("awaiting_authorization");
+ });
+
+ // Unmount should abort without errors or state update warnings
+ unmount();
+
+ // If cleanup didn't work, React would warn about state updates on unmounted component
+ // No assertion needed - the test passes if unmount completes without warnings
+ });
+});
diff --git a/src/api/device-flow-client.ts b/src/api/device-flow-client.ts
new file mode 100644
index 0000000000..7a777ad00e
--- /dev/null
+++ b/src/api/device-flow-client.ts
@@ -0,0 +1,340 @@
+/**
+ * OAuth 2.0 Device Flow client implementation (RFC 8628).
+ *
+ * Used for one-click authentication with cloud backends.
+ * The flow allows users to authenticate in their browser while the
+ * application polls for the resulting API key.
+ *
+ * All device flow requests are proxied through the local agent-server's
+ * cloud-proxy endpoint to avoid CORS issues. Since a local agent-server
+ * is required to use the frontend, the proxy is always available.
+ */
+
+import { getEffectiveLocalBackend } from "./backend-registry/active-store";
+import { buildAuthHeaders } from "./backend-registry/auth";
+
+export class DeviceFlowError extends Error {
+ constructor(
+ message: string,
+ public readonly code?: string,
+ ) {
+ super(message);
+ this.name = "DeviceFlowError";
+ }
+}
+
+export interface DeviceAuthorizationResponse {
+ device_code: string;
+ user_code: string;
+ verification_uri: string;
+ verification_uri_complete: string;
+ expires_in: number;
+ interval: number;
+}
+
+export interface DeviceTokenResponse {
+ access_token: string;
+ token_type: string;
+ expires_in?: number;
+}
+
+interface DeviceTokenErrorResponse {
+ error: string;
+ error_description?: string;
+ interval?: number;
+}
+
+const DEFAULT_TIMEOUT_MS = 600_000; // 10 minutes
+const MAX_INTERVAL_MS = 30_000; // 30 seconds max polling interval
+
+/**
+ * Check if a host is a known OpenHands Cloud domain.
+ * Uses hostname extraction to prevent substring matching attacks.
+ */
+export function isOpenHandsCloudHost(host: string): boolean {
+ try {
+ // Extract hostname from URL or treat as hostname if no protocol
+ const trimmed = host.trim().toLowerCase();
+ const withProtocol = /^https?:\/\//i.test(trimmed)
+ ? trimmed
+ : `https://${trimmed}`;
+ const url = new URL(withProtocol);
+ const hostname = url.hostname;
+
+ // Check if hostname ends with known domains (exact suffix match)
+ return (
+ hostname.endsWith(".all-hands.dev") ||
+ hostname === "all-hands.dev" ||
+ hostname.endsWith(".openhands.dev") ||
+ hostname === "openhands.dev"
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Make a proxied request through the local agent-server's cloud-proxy endpoint.
+ * This avoids CORS issues when calling OpenHands Cloud endpoints.
+ */
+async function makeProxiedRequest(
+ upstreamHost: string,
+ method: "GET" | "POST",
+ path: string,
+ body?: unknown,
+ contentType?: string,
+ signal?: AbortSignal,
+): Promise<Response> {
+ const local = getEffectiveLocalBackend();
+ const proxyUrl = `${local.host.replace(/\/+$/, "")}/api/cloud-proxy`;
+
+ const response = await fetch(proxyUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...buildAuthHeaders(local),
+ },
+ body: JSON.stringify({
+ host: upstreamHost,
+ method,
+ path,
+ headers: contentType ? { "Content-Type": contentType } : {},
+ body: body ?? null,
+ }),
+ signal,
+ });
+
+ return response;
+}
+
+/**
+ * Start the OAuth 2.0 Device Flow by requesting a device code.
+ * All requests are proxied through the local agent-server to avoid CORS issues.
+ *
+ * @param host - The cloud backend host URL (e.g., "https://app.all-hands.dev")
+ * @returns DeviceAuthorizationResponse with device_code, user_code, verification URLs, etc.
+ * @throws DeviceFlowError if the request fails
+ */
+export async function startDeviceFlow(
+ host: string,
+): Promise<DeviceAuthorizationResponse> {
+ const normalizedHost = host.replace(/\/+$/, "");
+
+ try {
+ const response = await makeProxiedRequest(
+ normalizedHost,
+ "POST",
+ "/oauth/device/authorize",
+ {},
+ "application/json",
+ );
+
+ if (!response.ok) {
+ // Avoid exposing sensitive server error details
+ throw new DeviceFlowError(
+ `Failed to start device flow: Server returned ${response.status}`,
+ );
+ }
+
+ const data = await response.json();
+
+ // Validate required fields per RFC 8628 Section 3.2
+ // verification_uri_complete is OPTIONAL per RFC
+ if (!data.device_code || !data.user_code || !data.verification_uri) {
+ throw new DeviceFlowError(
+ "Invalid response from device authorization endpoint: missing required fields",
+ );
+ }
+
+ // Build verification_uri_complete if not provided (optional per RFC)
+ const verificationUriComplete =
+ data.verification_uri_complete ??
+ `${data.verification_uri}?user_code=${encodeURIComponent(data.user_code)}`;
+
+ return {
+ device_code: data.device_code,
+ user_code: data.user_code,
+ verification_uri: data.verification_uri,
+ verification_uri_complete: verificationUriComplete,
+ expires_in: data.expires_in ?? 600,
+ interval: data.interval ?? 5,
+ };
+ } catch (error) {
+ if (error instanceof DeviceFlowError) {
+ throw error;
+ }
+ throw new DeviceFlowError(
+ `Failed to start device flow: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+}
+
+export interface PollOptions {
+ /** Polling interval in seconds (from device authorization response) */
+ interval: number;
+ /** Maximum time to wait for authorization in milliseconds */
+ timeout?: number;
+ /** Abort signal to cancel polling */
+ signal?: AbortSignal;
+}
+
+/**
+ * Poll for the API key after user authorization.
+ * All requests are proxied through the local agent-server to avoid CORS issues.
+ *
+ * @param host - The cloud backend host URL
+ * @param deviceCode - The device code from startDeviceFlow
+ * @param options - Polling options including interval, timeout, and abort signal
+ * @returns DeviceTokenResponse containing the access_token (API key)
+ * @throws DeviceFlowError if polling fails, user denies access, or timeout expires
+ */
+export async function pollForToken(
+ host: string,
+ deviceCode: string,
+ options: PollOptions,
+): Promise<DeviceTokenResponse> {
+ const normalizedHost = host.replace(/\/+$/, "");
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
+ let interval = Math.max(1, options.interval) * 1000; // At least 1 second
+ const startTime = Date.now();
+
+ while (Date.now() - startTime < timeout) {
+ // Check if cancelled
+ if (options.signal?.aborted) {
+ throw new DeviceFlowError("Authorization cancelled", "cancelled");
+ }
+
+ try {
+ // RFC 8628 Section 3.4 requires grant_type parameter
+ const tokenRequestBody = new URLSearchParams({
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: deviceCode,
+ }).toString();
+
+ const response = await makeProxiedRequest(
+ normalizedHost,
+ "POST",
+ "/oauth/device/token",
+ tokenRequestBody,
+ "application/x-www-form-urlencoded",
+ options.signal,
+ );
+
+ if (response.ok) {
+ const data = await response.json();
+ if (!data.access_token) {
+ throw new DeviceFlowError(
+ "Invalid token response: missing access_token",
+ );
+ }
+ return {
+ access_token: data.access_token,
+ token_type: data.token_type ?? "Bearer",
+ expires_in: data.expires_in,
+ };
+ }
+
+ // Handle error responses
+ let errorData: DeviceTokenErrorResponse;
+ try {
+ errorData = await response.json();
+ } catch {
+ throw new DeviceFlowError(
+ `Unexpected response from server: ${response.status}`,
+ );
+ }
+
+ const { error, error_description } = errorData;
+
+ switch (error) {
+ case "authorization_pending":
+ // User hasn't finished yet; continue polling
+ break;
+
+ case "slow_down":
+ // Server asks us to poll less frequently
+ // RFC 8628 Section 3.5: "the client MUST increase its polling interval by 5 seconds"
+ // Validate server-provided interval to prevent DoS (must be number, finite, positive)
+ if (
+ typeof errorData.interval === "number" &&
+ isFinite(errorData.interval) &&
+ errorData.interval > 0
+ ) {
+ interval = Math.max(1, Math.min(errorData.interval, 30)) * 1000;
+ } else {
+ // RFC 8628 mandates incrementing by 5 seconds
+ interval = Math.min(interval + 5000, MAX_INTERVAL_MS);
+ }
+ break;
+
+ case "expired_token":
+ throw new DeviceFlowError(
+ "Device code has expired. Please try again.",
+ "expired_token",
+ );
+
+ case "access_denied":
+ throw new DeviceFlowError(
+ "Authorization request was denied.",
+ "access_denied",
+ );
+
+ default:
+ throw new DeviceFlowError(
+ `Authorization error: ${error}${error_description ? ` - ${error_description}` : ""}`,
+ error,
+ );
+ }
+ } catch (error) {
+ // DeviceFlowError means a definitive error (denied, expired, etc.) - rethrow
+ if (error instanceof DeviceFlowError) {
+ throw error;
+ }
+ // User cancelled - rethrow
+ if (error instanceof DOMException && error.name === "AbortError") {
+ throw new DeviceFlowError("Authorization cancelled", "cancelled");
+ }
+ // Network errors during polling should continue until timeout, not fail immediately
+ // Brief network hiccups shouldn't abort 10-minute flows
+ console.warn("Network error during polling, retrying:", error);
+ }
+
+ // Wait before next poll (wrap in try-catch for consistent abort handling)
+ try {
+ await sleep(interval, options.signal);
+ } catch (error) {
+ if (error instanceof DOMException && error.name === "AbortError") {
+ throw new DeviceFlowError("Authorization cancelled", "cancelled");
+ }
+ throw error;
+ }
+ }
+
+ throw new DeviceFlowError(
+ "Timeout waiting for authorization. Please try again.",
+ "timeout",
+ );
+}
+
+/**
+ * Sleep for a given duration, respecting an optional abort signal.
+ */
+function sleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(new DOMException("Aborted", "AbortError"));
+ return;
+ }
+
+ const timeoutId = setTimeout(resolve, ms);
+
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(timeoutId);
+ reject(new DOMException("Aborted", "AbortError"));
+ },
+ { once: true },
+ );
+ });
+}
diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsx
index 45270f7426..1bc1aa5644 100644
--- a/src/components/features/backends/backend-form-modal.tsx
+++ b/src/components/features/backends/backend-form-modal.tsx
@@ -11,6 +11,7 @@ import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { I18nKey } from "#/i18n/declaration";
import type { Backend, BackendKind } from "#/api/backend-registry/types";
import { BackendStatusDot } from "./backend-status-dot";
+import { DeviceFlowAuth } from "./device-flow-auth";
export type BackendFormMode = "add" | "edit";
@@ -163,6 +164,7 @@ export function BackendForm({
// already chose one, so don't re-infer over their choice.
const [touchedKind, setTouchedKind] = React.useState(mode === "edit");
+ // Auto-infer kind from host when user hasn't explicitly selected a kind via radio
React.useEffect(() => {
if (!touchedKind && host) {
setKind(inferKindFromHost(host));
@@ -231,16 +233,65 @@ export function BackendForm({
className="w-full"
/>
- <SettingsInput
- testId={`${testIdRoot}-api-key`}
- name={`${testIdRoot}-api-key`}
- type="password"
- label={t(I18nKey.BACKEND$KEY_LABEL)}
- value={apiKey}
- onChange={setApiKey}
- placeholder=""
- className="w-full"
- />
+ {/* Device Flow auth for cloud backends in add mode - always visible */}
+ {mode === "add" && kind === "cloud" && (
+ <div className="flex flex-col gap-3">
+ <DeviceFlowAuth
+ host={host}
+ onSuccess={setApiKey}
+ testIdRoot={testIdRoot}
+ isDisabled={host.trim().length === 0}
+ />
+
+ {/* Divider with "or" */}
+ <div className="flex items-center gap-3">
+ <div className="flex-1 border-t border-gray-600" />
+ <span className="text-xs text-gray-500 uppercase">
+ {t(I18nKey.BACKEND$LOGIN_OR)}
+ </span>
+ <div className="flex-1 border-t border-gray-600" />
+ </div>
+
+ {/* Manual API key section */}
+ <div className="flex flex-col gap-2">
+ <SettingsInput
+ testId={`${testIdRoot}-api-key`}
+ name={`${testIdRoot}-api-key`}
+ type="password"
+ label={t(I18nKey.BACKEND$KEY_LABEL)}
+ value={apiKey}
+ onChange={setApiKey}
+ placeholder=""
+ className="w-full"
+ />
+ <p className="text-xs text-gray-400">
+ {t(I18nKey.BACKEND$KEY_DOCS_HINT)}{" "}
+ <a
+ href="https://docs.openhands.dev/openhands/usage/settings/api-keys-settings"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-400 hover:underline"
+ >
+ {t(I18nKey.BACKEND$KEY_DOCS_LINK)}
+ </a>
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Regular API key input for non-cloud or edit mode */}
+ {(mode === "edit" || kind !== "cloud") && (
+ <SettingsInput
+ testId={`${testIdRoot}-api-key`}
+ name={`${testIdRoot}-api-key`}
+ type="password"
+ label={t(I18nKey.BACKEND$KEY_LABEL)}
+ value={apiKey}
+ onChange={setApiKey}
+ placeholder=""
+ className="w-full"
+ />
+ )}
{mode === "edit" && backend ? (
<BackendStatusBadge backend={backend} testIdRoot={testIdRoot} />
diff --git a/src/components/features/backends/device-flow-auth.tsx b/src/components/features/backends/device-flow-auth.tsx
new file mode 100644
index 0000000000..252f2ab740
--- /dev/null
+++ b/src/components/features/backends/device-flow-auth.tsx
@@ -0,0 +1,247 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { useDeviceFlow } from "#/hooks/use-device-flow";
+import { I18nKey } from "#/i18n/declaration";
+
+interface DeviceFlowAuthProps {
+ /** The host URL for the cloud backend */
+ host: string;
+ /** Callback when authentication succeeds with the API key */
+ onSuccess: (apiKey: string) => void;
+ /** Test ID prefix for the component */
+ testIdRoot: string;
+ /** Whether the login button should be disabled (e.g., when no host is entered) */
+ isDisabled?: boolean;
+}
+
+/**
+ * Device Flow authentication UI component.
+ *
+ * Shows a "Login with OpenHands" button that initiates OAuth 2.0 Device Flow
+ * authentication. Displays status during the auth process and auto-opens
+ * the browser for user authorization.
+ */
+/**
+ * Validate that a URL is safe to open in a popup.
+ * Prevents XSS via javascript: URLs or other malicious schemes.
+ */
+function isValidVerificationUrl(url: string): boolean {
+ try {
+ const parsed = new URL(url);
+ return parsed.protocol === "https:";
+ } catch {
+ return false;
+ }
+}
+
+export function DeviceFlowAuth({
+ host,
+ onSuccess,
+ testIdRoot,
+ isDisabled = false,
+}: DeviceFlowAuthProps) {
+ const { t } = useTranslation("openhands");
+ const deviceFlow = useDeviceFlow();
+ const popupRef = React.useRef<Window | null>(null);
+
+ // Close popup on unmount or when auth completes/errors
+ React.useEffect(() => {
+ return () => {
+ popupRef.current?.close();
+ };
+ }, []);
+
+ // Update popup URL when verification URL becomes available
+ React.useEffect(() => {
+ if (
+ deviceFlow.status === "awaiting_authorization" &&
+ deviceFlow.verificationUrl &&
+ popupRef.current &&
+ !popupRef.current.closed
+ ) {
+ // Validate URL before assigning to prevent XSS
+ if (!isValidVerificationUrl(deviceFlow.verificationUrl)) {
+ console.error("Invalid verification URL protocol");
+ return;
+ }
+ try {
+ popupRef.current.location.href = deviceFlow.verificationUrl;
+ } catch {
+ // Cross-origin error - popup was navigated away
+ // Open a new one as fallback
+ popupRef.current = window.open(
+ deviceFlow.verificationUrl,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ }
+ }
+ }, [deviceFlow.status, deviceFlow.verificationUrl]);
+
+ // Call onSuccess when authentication completes
+ React.useEffect(() => {
+ if (deviceFlow.status === "success" && deviceFlow.apiKey) {
+ try {
+ onSuccess(deviceFlow.apiKey);
+ } finally {
+ deviceFlow.reset();
+ popupRef.current?.close();
+ }
+ }
+ }, [deviceFlow.status, deviceFlow.apiKey, deviceFlow.reset, onSuccess]);
+
+ const handleStartAuth = () => {
+ // Normalize and validate the host URL
+ const normalizedHost = host.trim().replace(/\/+$/, "");
+ const fullHost = /^https?:\/\//i.test(normalizedHost)
+ ? normalizedHost
+ : `https://${normalizedHost}`;
+
+ // Validate URL before proceeding
+ try {
+ const url = new URL(fullHost);
+ // Check for URL manipulation attacks
+ if (url.username || url.password) {
+ throw new Error("Invalid URL format");
+ }
+ } catch {
+ return; // Invalid URL, don't proceed
+ }
+
+ // Open popup immediately on user click to avoid popup blocker
+ // Start with about:blank and update URL once we have verification URL
+ // Note: We intentionally don't use "noopener" here because we need to
+ // maintain a reference to update the popup's location when the
+ // verification URL becomes available
+ popupRef.current = window.open("about:blank", "_blank");
+
+ if (!popupRef.current) {
+ // Popup was blocked - flow will still work, user can click manual link
+ console.warn("Popup blocked - user will need to use manual link");
+ }
+
+ deviceFlow.start(fullHost);
+ };
+
+ return (
+ <div
+ data-testid={`${testIdRoot}-device-flow`}
+ className="flex flex-col gap-3"
+ >
+ {deviceFlow.status === "idle" && (
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={handleStartAuth}
+ testId={`${testIdRoot}-login-button`}
+ className="w-full"
+ isDisabled={isDisabled}
+ >
+ 🔑 {t(I18nKey.BACKEND$LOGIN_WITH_OPENHANDS)}
+ </BrandButton>
+ )}
+
+ {deviceFlow.status === "starting" && (
+ <div
+ className="flex items-center gap-2 p-3 bg-base-tertiary rounded-lg"
+ data-testid={`${testIdRoot}-auth-starting`}
+ role="status"
+ aria-live="polite"
+ >
+ <LoadingSpinner />
+ <span className="text-sm text-gray-300">
+ {t(I18nKey.BACKEND$AUTH_STARTING)}
+ </span>
+ </div>
+ )}
+
+ {deviceFlow.status === "awaiting_authorization" && (
+ <div
+ className="flex flex-col gap-3 p-4 bg-base-tertiary rounded-lg"
+ data-testid={`${testIdRoot}-auth-awaiting`}
+ role="status"
+ aria-live="polite"
+ >
+ <div className="flex items-center gap-2">
+ <LoadingSpinner />
+ <span className="text-sm font-medium text-white">
+ {t(I18nKey.BACKEND$AUTH_AWAITING)}
+ </span>
+ </div>
+ <p className="text-sm text-gray-300">
+ {t(I18nKey.BACKEND$AUTH_BROWSER_OPENED)}
+ </p>
+ {deviceFlow.verificationUrl &&
+ isValidVerificationUrl(deviceFlow.verificationUrl) && (
+ <div className="text-xs text-gray-400">
+ <p>{t(I18nKey.BACKEND$AUTH_OPEN_MANUALLY)}</p>
+ <a
+ href={deviceFlow.verificationUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-400 hover:underline break-all"
+ >
+ {deviceFlow.verificationUrl}
+ </a>
+ </div>
+ )}
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={deviceFlow.cancel}
+ testId={`${testIdRoot}-auth-cancel`}
+ className="w-full mt-2"
+ >
+ {t(I18nKey.BACKEND$AUTH_CANCEL)}
+ </BrandButton>
+ </div>
+ )}
+
+ {deviceFlow.status === "error" && (
+ <div
+ className="flex flex-col gap-3 p-4 bg-red-900/20 border border-red-700 rounded-lg"
+ data-testid={`${testIdRoot}-auth-error`}
+ role="alert"
+ >
+ <p className="text-sm text-red-400">{deviceFlow.error}</p>
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={handleStartAuth}
+ testId={`${testIdRoot}-auth-retry`}
+ className="w-full"
+ >
+ {t(I18nKey.BACKEND$AUTH_RETRY)}
+ </BrandButton>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function LoadingSpinner() {
+ return (
+ <svg
+ className="animate-spin h-4 w-4 text-white"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ />
+ </svg>
+ );
+}
diff --git a/src/hooks/use-device-flow.ts b/src/hooks/use-device-flow.ts
new file mode 100644
index 0000000000..255c032eed
--- /dev/null
+++ b/src/hooks/use-device-flow.ts
@@ -0,0 +1,186 @@
+import React from "react";
+import {
+ startDeviceFlow,
+ pollForToken,
+ DeviceFlowError,
+ type DeviceAuthorizationResponse,
+} from "#/api/device-flow-client";
+
+export type DeviceFlowStatus =
+ | "idle"
+ | "starting"
+ | "awaiting_authorization"
+ | "success"
+ | "error";
+
+export interface DeviceFlowState {
+ status: DeviceFlowStatus;
+ /** The verification URL to show/open for the user */
+ verificationUrl: string | null;
+ /** User code to display as fallback */
+ userCode: string | null;
+ /** The resulting API key on success */
+ apiKey: string | null;
+ /** Error message if status is "error" */
+ error: string | null;
+ /** Error code for programmatic handling */
+ errorCode: string | null;
+}
+
+export interface UseDeviceFlowReturn extends DeviceFlowState {
+ /** Start the device flow authentication */
+ start: (host: string) => void;
+ /** Cancel an in-progress flow */
+ cancel: () => void;
+ /** Reset state back to idle */
+ reset: () => void;
+}
+
+const initialState: DeviceFlowState = {
+ status: "idle",
+ verificationUrl: null,
+ userCode: null,
+ apiKey: null,
+ error: null,
+ errorCode: null,
+};
+
+/**
+ * React hook for managing OAuth 2.0 Device Flow authentication.
+ *
+ * Usage:
+ * ```tsx
+ * const { status, verificationUrl, apiKey, error, start, cancel, reset } = useDeviceFlow();
+ *
+ * // Start auth
+ * start("https://app.all-hands.dev");
+ *
+ * // Open browser when awaiting
+ * if (status === "awaiting_authorization" && verificationUrl) {
+ * window.open(verificationUrl, "_blank");
+ * }
+ *
+ * // Use API key on success
+ * if (status === "success" && apiKey) {
+ * setApiKeyField(apiKey);
+ * }
+ * ```
+ */
+export function useDeviceFlow(): UseDeviceFlowReturn {
+ const [state, setState] = React.useState<DeviceFlowState>(initialState);
+ const abortControllerRef = React.useRef<AbortController | null>(null);
+
+ const start = React.useCallback((host: string) => {
+ // Cancel any existing flow
+ abortControllerRef.current?.abort();
+ const abortController = new AbortController();
+ abortControllerRef.current = abortController;
+
+ setState({
+ ...initialState,
+ status: "starting",
+ });
+
+ (async () => {
+ let authResponse: DeviceAuthorizationResponse;
+
+ try {
+ authResponse = await startDeviceFlow(host);
+ } catch (error) {
+ if (abortController.signal.aborted) return;
+
+ const message =
+ error instanceof Error
+ ? error.message
+ : "Failed to start device flow";
+ const code = error instanceof DeviceFlowError ? error.code : undefined;
+
+ setState({
+ ...initialState,
+ status: "error",
+ error: message,
+ errorCode: code ?? null,
+ });
+ return;
+ }
+
+ if (abortController.signal.aborted) return;
+
+ setState({
+ ...initialState,
+ status: "awaiting_authorization",
+ verificationUrl: authResponse.verification_uri_complete,
+ userCode: authResponse.user_code,
+ });
+
+ try {
+ const tokenResponse = await pollForToken(
+ host,
+ authResponse.device_code,
+ {
+ interval: authResponse.interval,
+ signal: abortController.signal,
+ },
+ );
+
+ if (abortController.signal.aborted) return;
+
+ setState({
+ ...initialState,
+ status: "success",
+ apiKey: tokenResponse.access_token,
+ });
+ } catch (error) {
+ // Early return if component unmounted or user cancelled
+ if (abortController.signal.aborted) return;
+
+ // Defensive: handle cancellation errors that may slip through
+ // (currently pollForToken only throws "cancelled" when signal.aborted,
+ // which is caught above, but this guards against future changes)
+ const isCancel =
+ error instanceof DeviceFlowError && error.code === "cancelled";
+ if (isCancel) {
+ setState(initialState);
+ return;
+ }
+
+ const message =
+ error instanceof Error ? error.message : "Authorization failed";
+ const code = error instanceof DeviceFlowError ? error.code : undefined;
+
+ setState({
+ ...initialState,
+ status: "error",
+ error: message,
+ errorCode: code ?? null,
+ });
+ }
+ })();
+ }, []);
+
+ const cancel = React.useCallback(() => {
+ abortControllerRef.current?.abort();
+ abortControllerRef.current = null;
+ setState(initialState);
+ }, []);
+
+ const reset = React.useCallback(() => {
+ abortControllerRef.current?.abort();
+ abortControllerRef.current = null;
+ setState(initialState);
+ }, []);
+
+ // Cleanup on unmount
+ React.useEffect(() => {
+ return () => {
+ abortControllerRef.current?.abort();
+ };
+ }, []);
+
+ return {
+ ...state,
+ start,
+ cancel,
+ reset,
+ };
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 00e74c3cd0..87913d0282 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -23935,6 +23935,210 @@
"uk": "Перемикання на {{environment}}",
"ca": "Canviant a {{environment}}"
},
+ "BACKEND$LOGIN_WITH_OPENHANDS": {
+ "en": "Login with OpenHands",
+ "ja": "OpenHandsでログイン",
+ "zh-CN": "使用 OpenHands 登录",
+ "zh-TW": "使用 OpenHands 登入",
+ "ko-KR": "OpenHands로 로그인",
+ "no": "Logg inn med OpenHands",
+ "it": "Accedi con OpenHands",
+ "pt": "Entrar com OpenHands",
+ "es": "Iniciar sesión con OpenHands",
+ "ar": "تسجيل الدخول باستخدام OpenHands",
+ "fr": "Se connecter avec OpenHands",
+ "tr": "OpenHands ile giriş yap",
+ "de": "Mit OpenHands anmelden",
+ "uk": "Увійти через OpenHands",
+ "ca": "Inicia sessió amb OpenHands"
+ },
+ "BACKEND$LOGIN_OR_MANUAL": {
+ "en": "or enter API key manually",
+ "ja": "または API キーを手動で入力",
+ "zh-CN": "或手动输入 API 密钥",
+ "zh-TW": "或手動輸入 API 金鑰",
+ "ko-KR": "또는 API 키를 직접 입력",
+ "no": "eller skriv inn API-nøkkel manuelt",
+ "it": "oppure inserisci la chiave API manualmente",
+ "pt": "ou insira a chave API manualmente",
+ "es": "o ingresa la clave API manualmente",
+ "ar": "أو أدخل مفتاح API يدويًا",
+ "fr": "ou entrez la clé API manuellement",
+ "tr": "veya API anahtarını manuel girin",
+ "de": "oder API-Schlüssel manuell eingeben",
+ "uk": "або введіть API-ключ вручну",
+ "ca": "o introdueix la clau API manualment"
+ },
+ "BACKEND$AUTH_STARTING": {
+ "en": "Starting authentication...",
+ "ja": "認証を開始しています...",
+ "zh-CN": "正在启动身份验证...",
+ "zh-TW": "正在啟動身份驗證...",
+ "ko-KR": "인증을 시작하는 중...",
+ "no": "Starter autentisering...",
+ "it": "Avvio autenticazione...",
+ "pt": "Iniciando autenticação...",
+ "es": "Iniciando autenticación...",
+ "ar": "جارٍ بدء المصادقة...",
+ "fr": "Démarrage de l'authentification...",
+ "tr": "Kimlik doğrulama başlatılıyor...",
+ "de": "Authentifizierung wird gestartet...",
+ "uk": "Запуск автентифікації...",
+ "ca": "Iniciant autenticació..."
+ },
+ "BACKEND$AUTH_AWAITING": {
+ "en": "Waiting for authorization...",
+ "ja": "承認を待っています...",
+ "zh-CN": "等待授权...",
+ "zh-TW": "等待授權...",
+ "ko-KR": "인증 대기 중...",
+ "no": "Venter på autorisasjon...",
+ "it": "In attesa di autorizzazione...",
+ "pt": "Aguardando autorização...",
+ "es": "Esperando autorización...",
+ "ar": "في انتظار التفويض...",
+ "fr": "En attente d'autorisation...",
+ "tr": "Yetkilendirme bekleniyor...",
+ "de": "Warte auf Autorisierung...",
+ "uk": "Очікування авторизації...",
+ "ca": "Esperant autorització..."
+ },
+ "BACKEND$AUTH_BROWSER_OPENED": {
+ "en": "Browser opened. Complete sign-in to continue.",
+ "ja": "ブラウザが開きました。サインインを完了してください。",
+ "zh-CN": "浏览器已打开。请完成登录以继续。",
+ "zh-TW": "瀏覽器已開啟。請完成登入以繼續。",
+ "ko-KR": "브라우저가 열렸습니다. 로그인을 완료해 주세요.",
+ "no": "Nettleser åpnet. Fullfør pålogging for å fortsette.",
+ "it": "Browser aperto. Completa l'accesso per continuare.",
+ "pt": "Navegador aberto. Complete o login para continuar.",
+ "es": "Navegador abierto. Completa el inicio de sesión para continuar.",
+ "ar": "تم فتح المتصفح. أكمل تسجيل الدخول للمتابعة.",
+ "fr": "Navigateur ouvert. Terminez la connexion pour continuer.",
+ "tr": "Tarayıcı açıldı. Devam etmek için oturum açmayı tamamlayın.",
+ "de": "Browser geöffnet. Melden Sie sich an, um fortzufahren.",
+ "uk": "Браузер відкрито. Завершіть вхід, щоб продовжити.",
+ "ca": "Navegador obert. Completa l'inici de sessió per continuar."
+ },
+ "BACKEND$AUTH_OPEN_MANUALLY": {
+ "en": "If browser didn't open, visit:",
+ "ja": "ブラウザが開かない場合は、以下にアクセスしてください:",
+ "zh-CN": "如果浏览器未打开,请访问:",
+ "zh-TW": "如果瀏覽器未開啟,請訪問:",
+ "ko-KR": "브라우저가 열리지 않으면 다음 주소를 방문하세요:",
+ "no": "Hvis nettleseren ikke åpnet, besøk:",
+ "it": "Se il browser non si è aperto, visita:",
+ "pt": "Se o navegador não abriu, visite:",
+ "es": "Si el navegador no se abrió, visita:",
+ "ar": "إذا لم يفتح المتصفح، قم بزيارة:",
+ "fr": "Si le navigateur ne s'est pas ouvert, visitez :",
+ "tr": "Tarayıcı açılmadıysa şu adresi ziyaret edin:",
+ "de": "Wenn der Browser nicht geöffnet wurde, besuchen Sie:",
+ "uk": "Якщо браузер не відкрився, перейдіть за адресою:",
+ "ca": "Si el navegador no s'ha obert, visita:"
+ },
+ "BACKEND$AUTH_SUCCESS": {
+ "en": "Authentication successful!",
+ "ja": "認証に成功しました!",
+ "zh-CN": "身份验证成功!",
+ "zh-TW": "身份驗證成功!",
+ "ko-KR": "인증 성공!",
+ "no": "Autentisering vellykket!",
+ "it": "Autenticazione riuscita!",
+ "pt": "Autenticação bem-sucedida!",
+ "es": "¡Autenticación exitosa!",
+ "ar": "تمت المصادقة بنجاح!",
+ "fr": "Authentification réussie !",
+ "tr": "Kimlik doğrulama başarılı!",
+ "de": "Authentifizierung erfolgreich!",
+ "uk": "Автентифікація успішна!",
+ "ca": "Autenticació correcta!"
+ },
+ "BACKEND$AUTH_CANCEL": {
+ "en": "Cancel",
+ "ja": "キャンセル",
+ "zh-CN": "取消",
+ "zh-TW": "取消",
+ "ko-KR": "취소",
+ "no": "Avbryt",
+ "it": "Annulla",
+ "pt": "Cancelar",
+ "es": "Cancelar",
+ "ar": "إلغاء",
+ "fr": "Annuler",
+ "tr": "İptal",
+ "de": "Abbrechen",
+ "uk": "Скасувати",
+ "ca": "Cancel·la"
+ },
+ "BACKEND$AUTH_RETRY": {
+ "en": "Try again",
+ "ja": "再試行",
+ "zh-CN": "重试",
+ "zh-TW": "重試",
+ "ko-KR": "다시 시도",
+ "no": "Prøv igjen",
+ "it": "Riprova",
+ "pt": "Tentar novamente",
+ "es": "Intentar de nuevo",
+ "ar": "حاول مرة أخرى",
+ "fr": "Réessayer",
+ "tr": "Tekrar dene",
+ "de": "Erneut versuchen",
+ "uk": "Спробувати ще раз",
+ "ca": "Torna-ho a provar"
+ },
+ "BACKEND$LOGIN_OR": {
+ "en": "or",
+ "ja": "または",
+ "zh-CN": "或",
+ "zh-TW": "或",
+ "ko-KR": "또는",
+ "no": "eller",
+ "it": "oppure",
+ "pt": "ou",
+ "es": "o",
+ "ar": "أو",
+ "fr": "ou",
+ "tr": "veya",
+ "de": "oder",
+ "uk": "або",
+ "ca": "o"
+ },
+ "BACKEND$KEY_DOCS_HINT": {
+ "en": "Need an API key?",
+ "ja": "APIキーが必要ですか?",
+ "zh-CN": "需要 API 密钥?",
+ "zh-TW": "需要 API 金鑰?",
+ "ko-KR": "API 키가 필요하신가요?",
+ "no": "Trenger du en API-nøkkel?",
+ "it": "Hai bisogno di una chiave API?",
+ "pt": "Precisa de uma chave API?",
+ "es": "¿Necesitas una clave API?",
+ "ar": "هل تحتاج إلى مفتاح API؟",
+ "fr": "Besoin d'une clé API ?",
+ "tr": "API anahtarına mı ihtiyacınız var?",
+ "de": "Benötigen Sie einen API-Schlüssel?",
+ "uk": "Потрібен API-ключ?",
+ "ca": "Necessites una clau API?"
+ },
+ "BACKEND$KEY_DOCS_LINK": {
+ "en": "Learn how to get one",
+ "ja": "取得方法を見る",
+ "zh-CN": "了解如何获取",
+ "zh-TW": "了解如何取得",
+ "ko-KR": "발급 방법 알아보기",
+ "no": "Lær hvordan du får en",
+ "it": "Scopri come ottenerne una",
+ "pt": "Saiba como obter uma",
+ "es": "Aprende cómo obtener una",
+ "ar": "تعرف على كيفية الحصول على واحد",
+ "fr": "Découvrez comment en obtenir une",
+ "tr": "Nasıl alacağınızı öğrenin",
+ "de": "Erfahren Sie, wie Sie einen erhalten",
+ "uk": "Дізнайтеся, як отримати",
+ "ca": "Aprèn com obtenir-ne una"
+ },
"TELEMETRY$CONSENT_TITLE": {
"en": "Help improve OpenHands",
"ja": "OpenHandsの改善にご協力ください",