mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add OAuth provider authentication support (#14)
* feat: Implement OAuth support for provider authentication - Add OAuth routes and API endpoints for authorize/callback flows - Create OAuthAuthorizeDialog and OAuthCallbackDialog components - Extend ProviderSettings to support both OAuth and API key auth - Add OAuth credential support to auth service - Update shared schemas with OAuth request/response types - Support both 'auto' and 'code' OAuth flows - Maintain backward compatibility with existing API key authentication Backend: - backend/src/routes/oauth.ts (new) - backend/src/services/auth.ts (extended) - backend/src/index.ts (route registration) Frontend: - frontend/src/api/oauth.ts (new) - frontend/src/components/settings/OAuthAuthorizeDialog.tsx (new) - frontend/src/components/settings/OAuthCallbackDialog.tsx (new) - frontend/src/components/settings/ProviderSettings.tsx (enhanced) Shared: - shared/src/schemas/auth.ts (OAuth schemas) * feat: Complete OAuth implementation with comprehensive features - Add comprehensive error handling for OAuth failures with specific error messages - Implement OAuth token status checking and expiration monitoring - Add token refresh preparation with 5-minute expiration buffer - Enhance OAuth API client with detailed error reporting - Update OAuth routes to include database parameter and token status endpoint - Add complete OAuth documentation to README with setup guide - Improve user experience with clear error messages and troubleshooting steps - Support both auto and code OAuth flows for different providers - Maintain backward compatibility with existing API key authentication Error Handling: - Specific error messages for invalid codes, expiration, access denied - Graceful fallback for server errors and network issues - User-friendly error display in OAuth dialogs Token Management: - Token status endpoint for checking credential validity - Expiration monitoring with automatic refresh preparation - Secure storage of OAuth credentials alongside API keys Documentation: - Complete OAuth setup guide in README - Comparison table for OAuth vs API keys - Troubleshooting section for common OAuth issues * fix: Resolve OAuth button opening API key dialog instead - Add isOAuthMode state to track authentication mode - Update API key dialog to only open when not in OAuth mode - Modify OAuth and API key button handlers to set proper mode - Add proper cleanup handlers to reset OAuth mode on close - Ensure dialog state management prevents conflicting dialogs This fixes the issue where clicking 'Add OAuth' would incorrectly open the API key dialog instead of the OAuth authorization dialog. * refactor: Address audit findings for OAuth implementation Critical fixes: - Remove unused db parameter from createOAuthRoutes() - Add query invalidation in handleOAuthSuccess to update UI after OAuth - Remove unused setOAuth and getOAuthWithRefreshCheck methods - Fix file permission in delete method (add mode: 0o600) DRY improvements: - Extract duplicated error handling to shared oauthErrors.ts utility - Add OAuthMethod constants to replace magic numbers 0/1 - Use centralized OPENCODE_SERVER_URL constant via ENV config - Remove unused ProviderAuthMethodsResponseSchema import Code quality: - Add documentation comment noting types should match shared schemas - Consolidate error mapping logic into single mapOAuthError function - Improve code maintainability and reduce duplication Files changed: - backend/src/routes/oauth.ts - backend/src/services/auth.ts - backend/src/index.ts - frontend/src/lib/oauthErrors.ts (new) - frontend/src/api/oauth.ts - frontend/src/components/settings/OAuthAuthorizeDialog.tsx - frontend/src/components/settings/OAuthCallbackDialog.tsx - frontend/src/components/settings/ProviderSettings.tsx * Store model selection client-side with recent models display * Limit provider settings to OAuth-capable providers only * Remove unused code and consolidate model initialization into useModelSelection hook
This commit is contained in:
1 parent
680fed3313
commit
bc99c96021
20 files changed
+848
-423
No files matched your search
@@ -1,222 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Loader2, ExternalLink } from 'lucide-react'
|
||||
import { PROVIDER_TEMPLATES, type ProviderTemplate } from '@/lib/providerTemplates'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange }: AddProviderDialogProps) {
|
||||
const [step, setStep] = useState<'select' | 'customize'>('select')
|
||||
const [selectedTemplate, setSelectedTemplate] = useState<ProviderTemplate | null>(null)
|
||||
const [providerId, setProviderId] = useState('')
|
||||
const [providerName, setProviderName] = useState('')
|
||||
const [baseURL, setBaseURL] = useState('')
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const addProviderMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const config = await settingsApi.getDefaultOpenCodeConfig()
|
||||
const currentProvider = config?.content?.provider || {}
|
||||
|
||||
const newProvider = {
|
||||
npm: selectedTemplate?.npm || '@ai-sdk/openai-compatible',
|
||||
name: providerName || selectedTemplate?.name,
|
||||
...(baseURL && {
|
||||
options: {
|
||||
baseURL,
|
||||
},
|
||||
}),
|
||||
...(selectedTemplate?.models && {
|
||||
models: selectedTemplate.models,
|
||||
}),
|
||||
}
|
||||
|
||||
const updatedConfig = {
|
||||
...config?.content,
|
||||
provider: {
|
||||
...currentProvider,
|
||||
[providerId]: newProvider,
|
||||
},
|
||||
}
|
||||
|
||||
await settingsApi.updateOpenCodeConfig(
|
||||
config?.name || 'default',
|
||||
{ content: updatedConfig }
|
||||
)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers'] })
|
||||
handleClose()
|
||||
},
|
||||
})
|
||||
|
||||
const handleSelectTemplate = (template: ProviderTemplate) => {
|
||||
setSelectedTemplate(template)
|
||||
setProviderId(template.id)
|
||||
setProviderName(template.name)
|
||||
setBaseURL(template.options?.baseURL || '')
|
||||
setStep('customize')
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
if (providerId && selectedTemplate) {
|
||||
addProviderMutation.mutate()
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setStep('select')
|
||||
setSelectedTemplate(null)
|
||||
setProviderId('')
|
||||
setProviderName('')
|
||||
setBaseURL('')
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="max-w-3xl max-h-[80vh] bg-card border-border overflow-y-auto">
|
||||
{step === 'select' && (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Provider</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose a provider template to get started quickly
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 py-4">
|
||||
{PROVIDER_TEMPLATES.map((template) => (
|
||||
<Card
|
||||
key={template.id}
|
||||
className="cursor-pointer hover:border-blue-500 transition-colors bg-background border-border"
|
||||
onClick={() => handleSelectTemplate(template)}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
{template.name}
|
||||
{!template.requiresApiKey && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Local
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-sm mt-1">
|
||||
{template.description}
|
||||
</CardDescription>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
{template.npm}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 'customize' && selectedTemplate && (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Configure {selectedTemplate.name}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Customize the provider settings before adding
|
||||
{selectedTemplate.docsUrl && (
|
||||
<a
|
||||
href={selectedTemplate.docsUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-blue-500 hover:underline ml-2"
|
||||
>
|
||||
View docs <ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="providerId">Provider ID</Label>
|
||||
<Input
|
||||
id="providerId"
|
||||
value={providerId}
|
||||
onChange={(e) => setProviderId(e.target.value)}
|
||||
placeholder="e.g., anthropic, openai, my-provider"
|
||||
className="bg-background border-border"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Unique identifier for this provider (lowercase, no spaces)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="providerName">Display Name</Label>
|
||||
<Input
|
||||
id="providerName"
|
||||
value={providerName}
|
||||
onChange={(e) => setProviderName(e.target.value)}
|
||||
placeholder={selectedTemplate.name}
|
||||
className="bg-background border-border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{selectedTemplate.options?.baseURL && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="baseURL">Base URL</Label>
|
||||
<Input
|
||||
id="baseURL"
|
||||
value={baseURL}
|
||||
onChange={(e) => setBaseURL(e.target.value)}
|
||||
placeholder={selectedTemplate.options.baseURL}
|
||||
className="bg-background border-border"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
API endpoint for this provider
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>NPM Package:</strong> {selectedTemplate.npm}
|
||||
</p>
|
||||
{selectedTemplate.models && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
<strong>Models:</strong> {Object.keys(selectedTemplate.models).length} pre-configured
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setStep('select')}>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={!providerId || addProviderMutation.isPending}
|
||||
>
|
||||
{addProviderMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Add Provider
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { ExternalLink, Copy } from 'lucide-react'
|
||||
import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth'
|
||||
import { mapOAuthError, OAuthMethod } from '@/lib/oauthErrors'
|
||||
|
||||
interface OAuthAuthorizeDialogProps {
|
||||
providerId: string
|
||||
providerName: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: (response: OAuthAuthorizeResponse) => void
|
||||
}
|
||||
|
||||
export function OAuthAuthorizeDialog({
|
||||
providerId,
|
||||
providerName,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess
|
||||
}: OAuthAuthorizeDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleAuthorize = async (methodIndex: number) => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await oauthApi.authorize(providerId, methodIndex)
|
||||
onSuccess(response)
|
||||
} catch (err) {
|
||||
setError(mapOAuthError(err, 'authorize'))
|
||||
console.error('OAuth authorize error:', err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setError(null)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="bg-card border-border max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Connect to {providerName}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose an authentication method to connect your {providerName} account.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{error && (
|
||||
<div className="bg-destructive/10 border border-destructive/20 rounded-md p-3">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={() => handleAuthorize(OAuthMethod.AUTO)}
|
||||
disabled={isLoading}
|
||||
className="w-full justify-start"
|
||||
variant="outline"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
{isLoading ? 'Authorizing...' : 'Open Authorization Page'}
|
||||
</Button>
|
||||
|
||||
<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>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p>• "Open Authorization Page" will open a browser window for you to sign in</p>
|
||||
<p>• "Use Authorization Code" will give you a code to manually enter</p>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
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'
|
||||
|
||||
interface OAuthCallbackDialogProps {
|
||||
providerId: string
|
||||
providerName: string
|
||||
authResponse: OAuthAuthorizeResponse
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function OAuthCallbackDialog({
|
||||
providerId,
|
||||
providerName,
|
||||
authResponse,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess
|
||||
}: OAuthCallbackDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [authCode, setAuthCode] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleAutoCallback = async () => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
await oauthApi.callback(providerId, { method: OAuthMethod.AUTO })
|
||||
onSuccess()
|
||||
} catch (err) {
|
||||
setError(mapOAuthError(err, 'callback'))
|
||||
console.error('OAuth callback error:', err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCodeCallback = async () => {
|
||||
if (!authCode.trim()) {
|
||||
setError('Please enter the authorization code')
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
await oauthApi.callback(providerId, { method: OAuthMethod.CODE, code: authCode.trim() })
|
||||
onSuccess()
|
||||
} catch (err) {
|
||||
setError(mapOAuthError(err, 'callback'))
|
||||
console.error('OAuth callback error:', err)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenAuthUrl = () => {
|
||||
window.open(authResponse.url, '_blank')
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setError(null)
|
||||
setAuthCode('')
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="bg-card border-border max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Complete {providerName} Authentication</DialogTitle>
|
||||
<DialogDescription>
|
||||
{authResponse.method === 'auto'
|
||||
? 'Follow the instructions to complete authentication.'
|
||||
: 'Enter the authorization code from the provider.'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{error && (
|
||||
<div className="bg-destructive/10 border border-destructive/20 rounded-md p-3">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{authResponse.method === 'auto' ? (
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm">{authResponse.instructions}</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open Authorization Page
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handleAutoCallback}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
{isLoading ? 'Completing...' : 'I Completed Authorization'}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="bg-muted p-3 rounded-md">
|
||||
<p className="text-sm mb-2">{authResponse.instructions}</p>
|
||||
<Button
|
||||
onClick={handleOpenAuthUrl}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open Authorization Page
|
||||
</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>
|
||||
|
||||
<Button
|
||||
onClick={handleCodeCallback}
|
||||
className="w-full"
|
||||
disabled={isLoading || !authCode.trim()}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Completing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
Complete Authentication
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +1,19 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useMemo, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Loader2, Key, Check, X, Plus } from 'lucide-react'
|
||||
import { Loader2, Check, X, Shield } from 'lucide-react'
|
||||
import { providerCredentialsApi, getProviders, type Provider } from '@/api/providers'
|
||||
import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { AddProviderDialog } from './AddProviderDialog'
|
||||
import { OAuthAuthorizeDialog } from './OAuthAuthorizeDialog'
|
||||
import { OAuthCallbackDialog } from './OAuthCallbackDialog'
|
||||
|
||||
export function ProviderSettings() {
|
||||
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
|
||||
const [apiKey, setApiKey] = useState('')
|
||||
const [showApiKey, setShowApiKey] = useState(false)
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false)
|
||||
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
|
||||
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
|
||||
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: providers, isLoading: providersLoading } = useQuery<Provider[]>({
|
||||
@@ -28,14 +27,9 @@ export function ProviderSettings() {
|
||||
queryFn: () => providerCredentialsApi.list(),
|
||||
})
|
||||
|
||||
const setCredentialMutation = useMutation({
|
||||
mutationFn: ({ providerId, apiKey }: { providerId: string; apiKey: string }) =>
|
||||
providerCredentialsApi.set(providerId, apiKey),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
|
||||
setSelectedProvider(null)
|
||||
setApiKey('')
|
||||
},
|
||||
const { data: authMethods } = useQuery({
|
||||
queryKey: ['provider-auth-methods'],
|
||||
queryFn: () => oauthApi.getAuthMethods(),
|
||||
})
|
||||
|
||||
const deleteCredentialMutation = useMutation({
|
||||
@@ -45,22 +39,49 @@ export function ProviderSettings() {
|
||||
},
|
||||
})
|
||||
|
||||
const handleSetCredential = () => {
|
||||
if (selectedProvider && apiKey) {
|
||||
setCredentialMutation.mutate({ providerId: selectedProvider, apiKey })
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteCredential = (providerId: string) => {
|
||||
if (confirm(`Remove credentials for ${providerId}?`)) {
|
||||
deleteCredentialMutation.mutate(providerId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOAuthAuthorize = (response: OAuthAuthorizeResponse) => {
|
||||
setOauthResponse(response)
|
||||
setOauthDialogOpen(false)
|
||||
setOauthCallbackDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleOAuthDialogClose = () => {
|
||||
setOauthDialogOpen(false)
|
||||
setSelectedProvider(null)
|
||||
}
|
||||
|
||||
const handleOAuthSuccess = () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
|
||||
setOauthCallbackDialogOpen(false)
|
||||
setOauthResponse(null)
|
||||
setSelectedProvider(null)
|
||||
}
|
||||
|
||||
const supportsOAuth = useCallback((providerId: string) => {
|
||||
const methods = authMethods?.[providerId] || []
|
||||
return methods.some(method => method.type === 'oauth')
|
||||
}, [authMethods])
|
||||
|
||||
const hasCredentials = (providerId: string) => {
|
||||
return credentialsList?.includes(providerId) || false
|
||||
}
|
||||
|
||||
const oauthProviders = useMemo(() => {
|
||||
if (!providers || !authMethods) return []
|
||||
return providers.filter(provider => supportsOAuth(provider.id))
|
||||
}, [providers, authMethods, supportsOAuth])
|
||||
|
||||
const selectedProviderName = useMemo(() => {
|
||||
if (!selectedProvider) return ''
|
||||
return providers?.find(p => p.id === selectedProvider)?.name || selectedProvider
|
||||
}, [selectedProvider, providers])
|
||||
|
||||
if (providersLoading || credentialsLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
@@ -71,30 +92,24 @@ export function ProviderSettings() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">Provider Credentials</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manage API keys for AI providers. Keys are stored securely in your workspace.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Provider
|
||||
</Button>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">OAuth Providers</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connect to AI providers using OAuth. For API keys, configure them in your OpenCode config file.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!providers || providers.length === 0 ? (
|
||||
{oauthProviders.length === 0 ? (
|
||||
<Card className="bg-card border-border">
|
||||
<CardContent className="pt-6">
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
No providers configured. Add providers in your OpenCode config.
|
||||
No OAuth-capable providers available.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{providers.map((provider) => {
|
||||
{oauthProviders.map((provider) => {
|
||||
const hasKey = hasCredentials(provider.id)
|
||||
const modelCount = Object.keys(provider.models || {}).length
|
||||
|
||||
@@ -108,12 +123,12 @@ export function ProviderSettings() {
|
||||
{hasKey ? (
|
||||
<Badge variant="default" className="bg-green-600 hover:bg-green-700">
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Configured
|
||||
Connected
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">
|
||||
<X className="h-3 w-3 mr-1" />
|
||||
No Key
|
||||
Not Connected
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
@@ -131,10 +146,13 @@ export function ProviderSettings() {
|
||||
<Button
|
||||
size="sm"
|
||||
variant={hasKey ? 'outline' : 'default'}
|
||||
onClick={() => setSelectedProvider(provider.id)}
|
||||
onClick={() => {
|
||||
setSelectedProvider(provider.id)
|
||||
setOauthDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Key className="h-4 w-4 mr-1" />
|
||||
{hasKey ? 'Update' : 'Add'} Key
|
||||
<Shield className="h-4 w-4 mr-1" />
|
||||
{hasKey ? 'Reconnect' : 'Connect'}
|
||||
</Button>
|
||||
{hasKey && (
|
||||
<Button
|
||||
@@ -143,7 +161,7 @@ export function ProviderSettings() {
|
||||
onClick={() => handleDeleteCredential(provider.id)}
|
||||
disabled={deleteCredentialMutation.isPending}
|
||||
>
|
||||
Remove
|
||||
Disconnect
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -155,56 +173,26 @@ export function ProviderSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={!!selectedProvider} onOpenChange={(open) => !open && setSelectedProvider(null)}>
|
||||
<DialogContent className="bg-card border-border">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Set API Key for {selectedProvider}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter your API key. It will be stored securely in your workspace.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{selectedProvider && (
|
||||
<OAuthAuthorizeDialog
|
||||
providerId={selectedProvider}
|
||||
providerName={selectedProviderName}
|
||||
open={oauthDialogOpen}
|
||||
onOpenChange={handleOAuthDialogClose}
|
||||
onSuccess={handleOAuthAuthorize}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="apiKey"
|
||||
type={showApiKey ? 'text' : 'password'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
className="bg-background border-border pr-20"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 h-7"
|
||||
onClick={() => setShowApiKey(!showApiKey)}
|
||||
>
|
||||
{showApiKey ? 'Hide' : 'Show'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setSelectedProvider(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSetCredential}
|
||||
disabled={!apiKey || setCredentialMutation.isPending}
|
||||
>
|
||||
{setCredentialMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AddProviderDialog open={addDialogOpen} onOpenChange={setAddDialogOpen} />
|
||||
{selectedProvider && oauthResponse && (
|
||||
<OAuthCallbackDialog
|
||||
providerId={selectedProvider}
|
||||
providerName={selectedProviderName}
|
||||
authResponse={oauthResponse}
|
||||
open={oauthCallbackDialogOpen}
|
||||
onOpenChange={setOauthCallbackDialogOpen}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user