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

+2
View File
@@ -9,6 +9,7 @@ import { createHealthRoutes } from './routes/health'
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'
import { createFileRoutes } from './routes/files'
import { createProvidersRoutes } from './routes/providers'
import { createOAuthRoutes } from './routes/oauth'
import { ensureDirectoryExists, writeFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
import { opencodeServerManager } from './services/opencode-single-server'
@@ -147,6 +148,7 @@ app.route('/api/settings', createSettingsRoutes(db))
app.route('/api/health', createHealthRoutes(db))
app.route('/api/files', createFileRoutes(db))
app.route('/api/providers', createProvidersRoutes())
app.route('/api/oauth', createOAuthRoutes())
app.route('/api/tts', createTTSRoutes(db))
app.all('/api/opencode/*', async (c) => {
+120
View File
@@ -0,0 +1,120 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { proxyRequest } from '../services/proxy'
import { logger } from '../utils/logger'
import { ENV } from '@opencode-webui/shared'
import {
OAuthAuthorizeRequestSchema,
OAuthAuthorizeResponseSchema,
OAuthCallbackRequestSchema
} from '../../../shared/src/schemas/auth'
const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
export function createOAuthRoutes() {
const app = new Hono()
app.post('/:id/oauth/authorize', async (c) => {
try {
const providerId = c.req.param('id')
const body = await c.req.json()
const validated = OAuthAuthorizeRequestSchema.parse(body)
// Proxy to OpenCode server
const response = await proxyRequest(
new Request(
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/authorize`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validated)
}
)
)
if (!response.ok) {
const error = await response.text()
logger.error(`OAuth authorize failed for ${providerId}:`, error)
return c.json({ error: 'OAuth authorization failed' }, 500)
}
const data = await response.json()
const validatedResponse = OAuthAuthorizeResponseSchema.parse(data)
return c.json(validatedResponse)
} catch (error) {
logger.error('OAuth authorize error:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({ error: 'OAuth authorization failed' }, 500)
}
})
app.post('/:id/oauth/callback', async (c) => {
try {
const providerId = c.req.param('id')
const body = await c.req.json()
const validated = OAuthCallbackRequestSchema.parse(body)
// Proxy to OpenCode server
const response = await proxyRequest(
new Request(
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/callback`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validated)
}
)
)
if (!response.ok) {
const error = await response.text()
logger.error(`OAuth callback failed for ${providerId}:`, error)
return c.json({ error: 'OAuth callback failed' }, 500)
}
const data = await response.json()
return c.json(data)
} catch (error) {
logger.error('OAuth callback error:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({ error: 'OAuth callback failed' }, 500)
}
})
app.get('/auth-methods', async (c) => {
try {
// Proxy to OpenCode server
const response = await proxyRequest(
new Request(`${OPENCODE_SERVER_URL}/provider/auth`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
)
if (!response.ok) {
const error = await response.text()
logger.error('Failed to get provider auth methods:', error)
return c.json({ error: 'Failed to get provider auth methods' }, 500)
}
const data = await response.json()
// The OpenCode server returns the format we need directly
return c.json({ providers: data })
} catch (error) {
logger.error('Provider auth methods error:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid response data', details: error.issues }, 500)
}
return c.json({ error: 'Failed to get provider auth methods' }, 500)
}
})
return app
}
+1 -6
View File
@@ -6,7 +6,6 @@ import { AuthCredentialsSchema } from '../../../shared/src/schemas/auth'
import type { z } from 'zod'
type AuthCredentials = z.infer<typeof AuthCredentialsSchema>
type AuthEntry = AuthCredentials[string]
export class AuthService {
private authPath = getAuthPath()
@@ -42,7 +41,7 @@ export class AuthService {
const auth = await this.getAll()
delete auth[providerId]
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2))
await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2), { mode: 0o600 })
logger.info(`Deleted credentials for provider: ${providerId}`)
}
@@ -56,8 +55,4 @@ export class AuthService {
return !!auth[providerId]
}
async get(providerId: string): Promise<AuthEntry | null> {
const auth = await this.getAll()
return auth[providerId] || null
}
}