From 2b5e13091649b16c40a53ea6b3ec62faeed51395 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 15 Apr 2026 14:10:19 -0400 Subject: [PATCH] feat: add dynamic OAuth prompt system with conditional fields - Add PromptFieldSchema supporting text and select input types - Support conditional prompt visibility based on previous inputs - Add inputs parameter to OAuth authorize request - Update OAuth dialogs to render dynamic prompts - Add OPENCODE_PUBLIC_URL config for OAuth callback URLs - Remove redundant OAuthMethod enum in favor of backend schema --- backend/src/routes/oauth.ts | 2 +- .../src/services/opencode-single-server.ts | 2 + frontend/src/api/oauth.ts | 23 +-- frontend/src/api/opencode-spec.json | 112 +++++++++- frontend/src/api/opencode-types.ts | 21 ++ .../settings/OAuthAuthorizeDialog.tsx | 192 ++++++++++++++++-- .../settings/OAuthCallbackDialog.tsx | 53 +++-- .../components/settings/ProviderSettings.tsx | 10 +- frontend/src/lib/oauthErrors.ts | 6 - shared/src/config/defaults.ts | 1 + shared/src/config/env.ts | 1 + shared/src/schemas/auth.ts | 26 ++- 12 files changed, 371 insertions(+), 78 deletions(-) diff --git a/backend/src/routes/oauth.ts b/backend/src/routes/oauth.ts index 9dd362d3..5b4d64d4 100644 --- a/backend/src/routes/oauth.ts +++ b/backend/src/routes/oauth.ts @@ -18,7 +18,7 @@ export function createOAuthRoutes() { const body = await c.req.json() const validated = OAuthAuthorizeRequestSchema.parse(body) - // Proxy to OpenCode server + // Proxy to OpenCode server - only method and inputs are supported const response = await proxyRequest( new Request( `${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/authorize`, diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 0aa7a3e9..64daf632 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -23,6 +23,7 @@ import { patchOpenCodeConfig } from './proxy' const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST +const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL const MIN_OPENCODE_VERSION = '1.0.137' const MAX_STDERR_SIZE = 10240 @@ -247,6 +248,7 @@ class OpenCodeServerManager { GIT_SSH_COMMAND: gitSshCommand, XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'), XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'), + ...(OPENCODE_SERVER_PUBLIC_URL ? { OPENCODE_PUBLIC_URL: OPENCODE_SERVER_PUBLIC_URL } : {}), OPENCODE_CONFIG: openCodeConfigPath, } } diff --git a/frontend/src/api/oauth.ts b/frontend/src/api/oauth.ts index 6c389c7d..f0e62249 100644 --- a/frontend/src/api/oauth.ts +++ b/frontend/src/api/oauth.ts @@ -1,21 +1,14 @@ import { API_BASE_URL } from "@/config" +import type { components, operations } from "./opencode-types" import { fetchWrapper, FetchError } from "./fetchWrapper" -export interface OAuthAuthorizeResponse { - url: string - method: "code" - instructions: string -} +type OpenCodeAuthorizeRequest = NonNullable["content"]["application/json"] -export interface OAuthCallbackRequest { - method: number - code?: string -} +export type OAuthAuthorizeResponse = components["schemas"]["ProviderAuthAuthorization"] -export interface ProviderAuthMethod { - type: "oauth" | "api" - label: string -} +export type OAuthCallbackRequest = NonNullable["content"]["application/json"] + +export type ProviderAuthMethod = components["schemas"]["ProviderAuthMethod"] export interface ProviderAuthMethods { [providerId: string]: ProviderAuthMethod[] @@ -29,12 +22,12 @@ function handleApiError(error: unknown, context: string): never { } export const oauthApi = { - authorize: async (providerId: string, method: number): Promise => { + authorize: async (providerId: string, method: number, inputs?: OpenCodeAuthorizeRequest["inputs"]): Promise => { try { return await fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ method }), + body: JSON.stringify({ method, inputs }), }) } catch (error) { handleApiError(error, "OAuth authorization failed") diff --git a/frontend/src/api/opencode-spec.json b/frontend/src/api/opencode-spec.json index e6c39b59..c378eeb3 100644 --- a/frontend/src/api/opencode-spec.json +++ b/frontend/src/api/opencode-spec.json @@ -3552,16 +3552,22 @@ "requestBody": { "content": { "application/json": { - "schema": { - "type": "object", - "properties": { - "method": { - "description": "Auth method index", - "type": "number" - } - }, - "required": [ - "method" + "schema": { + "type": "object", + "properties": { + "method": { + "description": "Auth method index", + "type": "number" + }, + "inputs": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "method" ] } } @@ -10399,6 +10405,90 @@ }, "label": { "type": "string" + }, + "prompts": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "text" + }, + "key": { + "type": "string" + }, + "message": { + "type": "string" + }, + "placeholder": { + "type": "string" + } + }, + "required": [ + "type", + "key", + "message" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "select" + }, + "key": { + "type": "string" + }, + "message": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "label", + "value" + ] + } + }, + "when": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "key", + "value" + ] + } + }, + "required": [ + "type", + "key", + "message", + "options" + ] + } + ] + } } }, "required": [ @@ -10932,4 +11022,4 @@ } } } -} \ No newline at end of file +} diff --git a/frontend/src/api/opencode-types.ts b/frontend/src/api/opencode-types.ts index 40884796..ff9bcca1 100644 --- a/frontend/src/api/opencode-types.ts +++ b/frontend/src/api/opencode-types.ts @@ -3379,6 +3379,24 @@ export interface components { ProviderAuthMethod: { type: "oauth" | "api"; label: string; + prompts?: ({ + type: "text"; + key: string; + message: string; + placeholder?: string; + } | { + type: "select"; + key: string; + message: string; + options: { + label: string; + value: string; + }[]; + when?: { + key: string; + value: string; + }; + })[]; }; ProviderAuthAuthorization: { url: string; @@ -5698,6 +5716,9 @@ export interface operations { "application/json": { /** @description Auth method index */ method: number; + inputs?: { + [key: string]: string; + }; }; }; }; diff --git a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx index 882871a2..4decf2b2 100644 --- a/frontend/src/components/settings/OAuthAuthorizeDialog.tsx +++ b/frontend/src/components/settings/OAuthAuthorizeDialog.tsx @@ -1,55 +1,135 @@ import { useState } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { Copy } from 'lucide-react' -import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth' -import { mapOAuthError, OAuthMethod } from '@/lib/oauthErrors' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Badge } from '@/components/ui/badge' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { ExternalLink } from 'lucide-react' +import { oauthApi, type OAuthAuthorizeResponse, type ProviderAuthMethod } from '@/api/oauth' +import { mapOAuthError } from '@/lib/oauthErrors' interface OAuthAuthorizeDialogProps { providerId: string providerName: string + methods: ProviderAuthMethod[] open: boolean onOpenChange: (open: boolean) => void - onSuccess: (response: OAuthAuthorizeResponse) => void + onSuccess: (response: OAuthAuthorizeResponse, methodIndex: number) => void +} + +type OAuthPrompt = NonNullable[number] + +function isBrowserLocalMethod(method: ProviderAuthMethod): boolean { + return method.label.toLowerCase().includes('browser') +} + +function getVisiblePrompts(method: ProviderAuthMethod, inputs: Record): OAuthPrompt[] { + const visiblePrompts: OAuthPrompt[] = [] + const activeInputs: Record = {} + + for (const prompt of method.prompts ?? []) { + const isVisible = !('when' in prompt) || !prompt.when || activeInputs[prompt.when.key] === prompt.when.value + + if (!isVisible) { + continue + } + + visiblePrompts.push(prompt) + + if (inputs[prompt.key]) { + activeInputs[prompt.key] = inputs[prompt.key] + } + } + + return visiblePrompts +} + +function hasPrompts(method: ProviderAuthMethod): boolean { + return (method.prompts?.length ?? 0) > 0 } export function OAuthAuthorizeDialog({ providerId, - providerName, + providerName, + methods, open, onOpenChange, onSuccess }: OAuthAuthorizeDialogProps) { const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) + const [selectedMethodIndex, setSelectedMethodIndex] = useState(null) + const [promptInputs, setPromptInputs] = useState>>({}) + + const getMethodInputs = (methodIndex: number) => promptInputs[methodIndex] || {} const handleAuthorize = async (methodIndex: number) => { + const method = methods[methodIndex] + const methodInputs = getMethodInputs(methodIndex) + const visiblePrompts = getVisiblePrompts(method, methodInputs) + const missingPrompt = visiblePrompts.some((prompt) => !methodInputs[prompt.key]?.trim()) + + if (missingPrompt) { + setError('Please complete all authentication fields') + setSelectedMethodIndex(methodIndex) + return + } + setIsLoading(true) setError(null) + setSelectedMethodIndex(methodIndex) try { - const response = await oauthApi.authorize(providerId, methodIndex) - onSuccess(response) + const inputs = visiblePrompts.length > 0 + ? Object.fromEntries( + visiblePrompts.map((prompt) => [prompt.key, methodInputs[prompt.key].trim()]) + ) + : undefined + const response = await oauthApi.authorize(providerId, methodIndex, inputs) + onSuccess(response, methodIndex) } catch (err) { setError(mapOAuthError(err, 'authorize')) - console.error('OAuth authorize error:', err) } finally { setIsLoading(false) } } + const handleMethodSelection = (methodIndex: number) => { + setError(null) + setSelectedMethodIndex(methodIndex) + + if (!hasPrompts(methods[methodIndex])) { + void handleAuthorize(methodIndex) + } + } + + const handlePromptChange = (methodIndex: number, key: string, value: string) => { + setPromptInputs((prev) => ({ + ...prev, + [methodIndex]: { + ...prev[methodIndex], + [key]: value, + }, + })) + } + const handleClose = () => { setError(null) + setPromptInputs({}) + setSelectedMethodIndex(null) onOpenChange(false) } + const oauthMethods = methods.flatMap((method, index) => method.type === 'oauth' ? [{ method, index }] : []) + return ( Connect to {providerName} - Connect your {providerName} account using authorization code. + Select an authentication method to connect your {providerName} account. @@ -59,20 +139,92 @@ export function OAuthAuthorizeDialog({ )} -
- +
+ {oauthMethods.map(({ method, index }) => { + const isBrowserLocal = isBrowserLocalMethod(method) + const methodInputs = getMethodInputs(index) + const visiblePrompts = getVisiblePrompts(method, methodInputs) + const canSubmitPrompts = visiblePrompts.every((prompt) => methodInputs[prompt.key]?.trim()) + + return ( +
+
+ + {isBrowserLocal && ( + + Localhost only + + )} +
+ + {selectedMethodIndex === index && hasPrompts(method) && ( +
+ {visiblePrompts.map((prompt) => ( + prompt.type === 'text' ? ( +
+ + handlePromptChange(index, prompt.key, e.target.value)} + placeholder={prompt.placeholder} + className="bg-background border-border" + disabled={isLoading} + /> +
+ ) : ( +
+ + +
+ ) + ))} + + +
+ )} + + {isBrowserLocal && ( +

+ This method relies on a callback server started by OpenCode and may not work when OCM is remote. +

+ )} +
+ ) + })}
-

• "Use Authorization Code" will give you a code to manually enter

+

• Some methods may require completing authorization in your browser

diff --git a/frontend/src/components/settings/OAuthCallbackDialog.tsx b/frontend/src/components/settings/OAuthCallbackDialog.tsx index 46b17595..d6ea704e 100644 --- a/frontend/src/components/settings/OAuthCallbackDialog.tsx +++ b/frontend/src/components/settings/OAuthCallbackDialog.tsx @@ -5,12 +5,13 @@ import { Label } from '@/components/ui/label' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Loader2, ExternalLink, CheckCircle } from 'lucide-react' import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth' -import { mapOAuthError, OAuthMethod } from '@/lib/oauthErrors' +import { mapOAuthError } from '@/lib/oauthErrors' interface OAuthCallbackDialogProps { providerId: string providerName: string authResponse: OAuthAuthorizeResponse + methodIndex: number open: boolean onOpenChange: (open: boolean) => void onSuccess: () => void @@ -20,6 +21,7 @@ export function OAuthCallbackDialog({ providerId, providerName, authResponse, + methodIndex, open, onOpenChange, onSuccess @@ -29,19 +31,19 @@ export function OAuthCallbackDialog({ const [authCode, setAuthCode] = useState('') const [error, setError] = useState(null) - const handleCodeCallback = async () => { - if (!authCode.trim()) { - setError('Please enter the authorization code') - return - } - + const handleCallback = async () => { setIsLoading(true) setLoadingMessage('Completing authentication...') setError(null) try { setLoadingMessage('Restarting server with new credentials...') - await oauthApi.callback(providerId, { method: OAuthMethod.CODE, code: authCode.trim() }) + await oauthApi.callback( + providerId, + authResponse.method === 'code' + ? { method: methodIndex, code: authCode.trim() } + : { method: methodIndex } + ) onSuccess() } catch (err) { setError(mapOAuthError(err, 'callback')) @@ -62,13 +64,18 @@ export function OAuthCallbackDialog({ onOpenChange(false) } + const isAutoMethod = authResponse.method === 'auto' + return ( Complete {providerName} Authentication - Enter the authorization code from the provider. + {isAutoMethod + ? 'Follow the instructions below to complete authentication.' + : 'Enter the authorization code from the provider.' + } @@ -93,22 +100,24 @@ export function OAuthCallbackDialog({ -
- - setAuthCode(e.target.value)} - placeholder="Enter the authorization code..." - className="bg-background border-border" - disabled={isLoading} - /> -
+ {!isAutoMethod && ( +
+ + setAuthCode(e.target.value)} + placeholder="Enter the authorization code..." + className="bg-background border-border" + disabled={isLoading} + /> +
+ )}