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
This commit is contained in:
Chris Scott committed 2026-04-15 14:10:19 -04:00
1 parent 9d94c333b4
commit 2b5e130916
12 files changed
+371 -78

No files matched your search

+1 -1
View File
@@ -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`,
@@ -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,
}
}
+8 -15
View File
@@ -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<operations["provider.oauth.authorize"]["requestBody"]>["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<operations["provider.oauth.callback"]["requestBody"]>["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<OAuthAuthorizeResponse> => {
authorize: async (providerId: string, method: number, inputs?: OpenCodeAuthorizeRequest["inputs"]): Promise<OAuthAuthorizeResponse> => {
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")
+101 -11
View File
@@ -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 @@
}
}
}
}
}
+21
View File
@@ -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;
};
};
};
};
@@ -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<ProviderAuthMethod['prompts']>[number]
function isBrowserLocalMethod(method: ProviderAuthMethod): boolean {
return method.label.toLowerCase().includes('browser')
}
function getVisiblePrompts(method: ProviderAuthMethod, inputs: Record<string, string>): OAuthPrompt[] {
const visiblePrompts: OAuthPrompt[] = []
const activeInputs: Record<string, string> = {}
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<string | null>(null)
const [selectedMethodIndex, setSelectedMethodIndex] = useState<number | null>(null)
const [promptInputs, setPromptInputs] = useState<Record<number, Record<string, string>>>({})
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 (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="bg-card border-border max-w-lg">
<DialogHeader>
<DialogTitle>Connect to {providerName}</DialogTitle>
<DialogDescription>
Connect your {providerName} account using authorization code.
Select an authentication method to connect your {providerName} account.
</DialogDescription>
</DialogHeader>
@@ -59,20 +139,92 @@ export function OAuthAuthorizeDialog({
</div>
)}
<div className="space-y-3">
<Button
onClick={() => handleAuthorize(OAuthMethod.CODE)}
disabled={isLoading}
className="w-full justify-start"
variant="outline"
>
<Copy className="h-4 w-4 mr-2" />
{isLoading ? 'Authorizing...' : 'Use Authorization Code'}
</Button>
<div className="space-y-4">
{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 (
<div key={index} className="space-y-3">
<div className="flex items-center gap-2">
<Button
onClick={() => handleMethodSelection(index)}
disabled={isLoading}
className="flex-1 justify-start"
variant={selectedMethodIndex === index ? 'default' : 'outline'}
>
<ExternalLink className="h-4 w-4 mr-2" />
{isLoading && selectedMethodIndex === index ? 'Authorizing...' : method.label}
</Button>
{isBrowserLocal && (
<Badge variant="secondary" className="text-xs">
Localhost only
</Badge>
)}
</div>
{selectedMethodIndex === index && hasPrompts(method) && (
<div className="space-y-3 pl-10 pr-1 py-2">
{visiblePrompts.map((prompt) => (
prompt.type === 'text' ? (
<div key={prompt.key} className="space-y-2">
<Label htmlFor={prompt.key}>{prompt.message}</Label>
<Input
id={prompt.key}
value={methodInputs[prompt.key] || ''}
onChange={(e) => handlePromptChange(index, prompt.key, e.target.value)}
placeholder={prompt.placeholder}
className="bg-background border-border"
disabled={isLoading}
/>
</div>
) : (
<div key={prompt.key} className="space-y-2">
<Label>{prompt.message}</Label>
<Select
value={methodInputs[prompt.key] || ''}
onValueChange={(value) => handlePromptChange(index, prompt.key, value)}
disabled={isLoading}
>
<SelectTrigger className="bg-background border-border">
<SelectValue placeholder="Select an option" />
</SelectTrigger>
<SelectContent>
{prompt.options.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)
))}
<Button
onClick={() => void handleAuthorize(index)}
disabled={isLoading || !canSubmitPrompts}
className="w-full"
>
{isLoading && selectedMethodIndex === index ? 'Authorizing...' : 'Continue'}
</Button>
</div>
)}
{isBrowserLocal && (
<p className="text-xs text-muted-foreground pl-1">
This method relies on a callback server started by OpenCode and may not work when OCM is remote.
</p>
)}
</div>
)
})}
</div>
<div className="text-xs text-muted-foreground">
<p>• "Use Authorization Code" will give you a code to manually enter</p>
<p>• Some methods may require completing authorization in your browser</p>
</div>
</DialogContent>
</Dialog>
@@ -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<string | null>(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 (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="bg-card border-border max-w-lg">
<DialogHeader>
<DialogTitle>Complete {providerName} Authentication</DialogTitle>
<DialogDescription>
Enter the authorization code from the provider.
{isAutoMethod
? 'Follow the instructions below to complete authentication.'
: 'Enter the authorization code from the provider.'
}
</DialogDescription>
</DialogHeader>
@@ -93,22 +100,24 @@ export function OAuthCallbackDialog({
</Button>
</div>
<div className="space-y-2">
<Label htmlFor="authCode">Authorization Code</Label>
<Input
id="authCode"
value={authCode}
onChange={(e) => setAuthCode(e.target.value)}
placeholder="Enter the authorization code..."
className="bg-background border-border"
disabled={isLoading}
/>
</div>
{!isAutoMethod && (
<div className="space-y-2">
<Label htmlFor="authCode">Authorization Code</Label>
<Input
id="authCode"
value={authCode}
onChange={(e) => setAuthCode(e.target.value)}
placeholder="Enter the authorization code..."
className="bg-background border-border"
disabled={isLoading}
/>
</div>
)}
<Button
onClick={handleCodeCallback}
onClick={handleCallback}
className="w-full"
disabled={isLoading || !authCode.trim()}
disabled={isLoading || (!isAutoMethod && !authCode.trim())}
>
{isLoading ? (
<>
@@ -19,6 +19,7 @@ export function ProviderSettings() {
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
const [oauthMethodIndex, setOauthMethodIndex] = useState<number | null>(null)
const [connectedExpanded, setConnectedExpanded] = useState(false)
const [availableExpanded, setAvailableExpanded] = useState(false)
const [availableSearch, setAvailableSearch] = useState('')
@@ -68,14 +69,16 @@ export function ProviderSettings() {
setDeleteTarget(null)
}
const handleOAuthAuthorize = (response: OAuthAuthorizeResponse) => {
const handleOAuthAuthorize = (response: OAuthAuthorizeResponse, methodIndex: number) => {
setOauthResponse(response)
setOauthMethodIndex(methodIndex)
setOauthDialogOpen(false)
setOauthCallbackDialogOpen(true)
}
const handleOAuthDialogClose = () => {
setOauthDialogOpen(false)
setOauthMethodIndex(null)
setSelectedProvider(null)
}
@@ -83,6 +86,7 @@ export function ProviderSettings() {
invalidateProviderCaches(queryClient)
setOauthCallbackDialogOpen(false)
setOauthResponse(null)
setOauthMethodIndex(null)
setSelectedProvider(null)
}
@@ -239,17 +243,19 @@ export function ProviderSettings() {
<OAuthAuthorizeDialog
providerId={selectedProvider}
providerName={selectedProviderName}
methods={authMethods?.[selectedProvider] || []}
open={oauthDialogOpen}
onOpenChange={handleOAuthDialogClose}
onSuccess={handleOAuthAuthorize}
/>
)}
{selectedProvider && oauthResponse && (
{selectedProvider && oauthResponse && oauthMethodIndex !== null && (
<OAuthCallbackDialog
providerId={selectedProvider}
providerName={selectedProviderName}
authResponse={oauthResponse}
methodIndex={oauthMethodIndex}
open={oauthCallbackDialogOpen}
onOpenChange={setOauthCallbackDialogOpen}
onSuccess={handleOAuthSuccess}
-6
View File
@@ -1,9 +1,3 @@
export const OAuthMethod = {
CODE: 0,
} as const
export type OAuthMethodType = (typeof OAuthMethod)[keyof typeof OAuthMethod]
const ERROR_MAPPINGS: Record<string, string> = {
'invalid code': 'Invalid authorization code. Please try the OAuth flow again.',
'expired': 'Authorization code has expired. Please try the OAuth flow again.',
+1
View File
@@ -13,6 +13,7 @@ export const DEFAULTS = {
OPENCODE: {
PORT: 5551,
HOST: '127.0.0.1',
PUBLIC_URL: '', // Optional: public URL for OAuth callbacks (e.g., https://mydomain.com)
},
DATABASE: {
+1
View File
@@ -53,6 +53,7 @@ export const ENV = {
OPENCODE: {
PORT: getEnvNumber('OPENCODE_SERVER_PORT', DEFAULTS.OPENCODE.PORT),
HOST: getEnvString('OPENCODE_HOST', DEFAULTS.OPENCODE.HOST),
PUBLIC_URL: getEnvString('OPENCODE_PUBLIC_URL', ''), // Public URL for OAuth callbacks
},
DATABASE: {
+25 -1
View File
@@ -22,15 +22,39 @@ export const CredentialListResponseSchema = z.object({
providers: z.array(z.string()),
});
export const PromptFieldSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
key: z.string(),
message: z.string(),
placeholder: z.string().optional(),
}),
z.object({
type: z.literal("select"),
key: z.string(),
message: z.string(),
options: z.array(z.object({
label: z.string(),
value: z.string(),
})),
when: z.object({
key: z.string(),
value: z.string(),
}).optional(),
}),
]);
export const ProviderAuthMethodSchema = z.object({
type: z.enum(["oauth", "api"]),
label: z.string(),
prompts: z.array(PromptFieldSchema).optional(),
});
export const ProviderAuthMethodsSchema = z.record(z.string(), z.array(ProviderAuthMethodSchema));
export const OAuthAuthorizeRequestSchema = z.object({
method: z.number(),
inputs: z.record(z.string(), z.string()).optional(),
});
export const OAuthAuthorizeResponseSchema = z.object({
@@ -46,4 +70,4 @@ export const OAuthCallbackRequestSchema = z.object({
export const ProviderAuthMethodsResponseSchema = z.object({
providers: z.record(z.string(), z.array(ProviderAuthMethodSchema)),
});
}).or(ProviderAuthMethodsSchema);