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:
Chris Scott authored and GitHub committed 2025-12-07 23:01:05 -05:00
1 parent 680fed3313
commit bc99c96021
20 files changed
+848 -423

No files matched your search

@@ -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>
)
}