mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +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
@@ -15,9 +15,7 @@ import {
|
||||
formatModelName,
|
||||
formatProviderName,
|
||||
} from "@/api/providers";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useOpenCodeClient } from "@/hooks/useOpenCode";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useModelSelection } from "@/hooks/useModelSelection";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { Model, ProviderWithModels } from "@/api/providers";
|
||||
|
||||
@@ -25,7 +23,7 @@ interface ModelSelectDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
opcodeUrl?: string | null;
|
||||
currentSessionModel?: string | null;
|
||||
directory?: string;
|
||||
}
|
||||
|
||||
interface FlatModel {
|
||||
@@ -181,13 +179,17 @@ interface ModelGridProps {
|
||||
currentModel: string;
|
||||
onSelect: (providerId: string, modelId: string) => void;
|
||||
loading: boolean;
|
||||
recentModels?: FlatModel[];
|
||||
showRecent?: boolean;
|
||||
}
|
||||
|
||||
const ModelGrid = memo(function ModelGrid({
|
||||
models,
|
||||
currentModel,
|
||||
onSelect,
|
||||
loading
|
||||
loading,
|
||||
recentModels = [],
|
||||
showRecent = false,
|
||||
}: ModelGridProps) {
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -197,7 +199,7 @@ const ModelGrid = memo(function ModelGrid({
|
||||
);
|
||||
}
|
||||
|
||||
if (models.length === 0) {
|
||||
if (models.length === 0 && recentModels.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-12 text-zinc-500">
|
||||
No models found
|
||||
@@ -206,17 +208,49 @@ const ModelGrid = memo(function ModelGrid({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
|
||||
{models.map(({ model, provider, modelKey }) => (
|
||||
<ModelCard
|
||||
key={modelKey}
|
||||
model={model}
|
||||
provider={provider}
|
||||
modelKey={modelKey}
|
||||
isSelected={currentModel === modelKey}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
<div className="space-y-6">
|
||||
{showRecent && recentModels.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-muted-foreground mb-3 flex items-center gap-1.5">
|
||||
<Star className="h-3.5 w-3.5" />
|
||||
Recent Models
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
|
||||
{recentModels.map(({ model, provider, modelKey }) => (
|
||||
<ModelCard
|
||||
key={`recent-${modelKey}`}
|
||||
model={model}
|
||||
provider={provider}
|
||||
modelKey={modelKey}
|
||||
isSelected={currentModel === modelKey}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{models.length > 0 && (
|
||||
<div>
|
||||
{showRecent && recentModels.length > 0 && (
|
||||
<h3 className="text-sm font-semibold text-muted-foreground mb-3">
|
||||
All Models
|
||||
</h3>
|
||||
)}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
|
||||
{models.map(({ model, provider, modelKey }) => (
|
||||
<ModelCard
|
||||
key={modelKey}
|
||||
model={model}
|
||||
provider={provider}
|
||||
modelKey={modelKey}
|
||||
isSelected={currentModel === modelKey}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -322,15 +356,13 @@ export function ModelSelectDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
opcodeUrl,
|
||||
currentSessionModel,
|
||||
directory,
|
||||
}: ModelSelectDialogProps) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedProvider, setSelectedProvider] = useState<string>("");
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
const client = useOpenCodeClient(opcodeUrl);
|
||||
const { sessionID } = useParams<{ sessionID: string }>();
|
||||
|
||||
const currentModel = currentSessionModel || preferences?.defaultModel || "";
|
||||
const { modelString, setModel, recentModels } = useModelSelection(opcodeUrl, directory);
|
||||
const currentModel = modelString || "";
|
||||
|
||||
const { data: providers = [], isLoading: loading } = useQuery({
|
||||
queryKey: ["providers-with-models"],
|
||||
@@ -341,22 +373,35 @@ export function ModelSelectDialog({
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (currentModel && providers.length > 0) {
|
||||
const [providerId] = currentModel.split("/");
|
||||
setSelectedProvider(providerId);
|
||||
if (open) {
|
||||
setSelectedProvider("");
|
||||
}
|
||||
}, [currentModel, providers]);
|
||||
}, [open]);
|
||||
|
||||
const flatModels = useMemo((): FlatModel[] => {
|
||||
return providers.flatMap((provider) =>
|
||||
provider.models.map((model) => ({
|
||||
model,
|
||||
provider,
|
||||
modelKey: `${provider.id}/${model.id}`,
|
||||
}))
|
||||
);
|
||||
const sourceOrder = { configured: 0, local: 1, builtin: 2 };
|
||||
return providers
|
||||
.slice()
|
||||
.sort((a, b) => (sourceOrder[a.source] ?? 2) - (sourceOrder[b.source] ?? 2))
|
||||
.flatMap((provider) =>
|
||||
provider.models.map((model) => ({
|
||||
model,
|
||||
provider,
|
||||
modelKey: `${provider.id}/${model.id}`,
|
||||
}))
|
||||
);
|
||||
}, [providers]);
|
||||
|
||||
const recentFlatModels = useMemo((): FlatModel[] => {
|
||||
return recentModels
|
||||
.map((recent) => {
|
||||
const modelKey = `${recent.providerID}/${recent.modelID}`;
|
||||
return flatModels.find((fm) => fm.modelKey === modelKey);
|
||||
})
|
||||
.filter((fm): fm is FlatModel => fm !== undefined)
|
||||
.slice(0, 6);
|
||||
}, [recentModels, flatModels]);
|
||||
|
||||
const filteredModels = useMemo(() => {
|
||||
const search = searchQuery.toLowerCase();
|
||||
return flatModels.filter((item) => {
|
||||
@@ -393,24 +438,10 @@ export function ModelSelectDialog({
|
||||
setSearchQuery(query);
|
||||
}, []);
|
||||
|
||||
const handleModelSelect = useCallback(async (providerId: string, modelId: string) => {
|
||||
const newModel = `${providerId}/${modelId}`;
|
||||
updateSettings({ defaultModel: newModel });
|
||||
|
||||
if (sessionID && client) {
|
||||
try {
|
||||
await client.sendCommand(sessionID, {
|
||||
command: "model",
|
||||
arguments: newModel,
|
||||
model: newModel,
|
||||
});
|
||||
} catch {
|
||||
// Ignore errors
|
||||
}
|
||||
}
|
||||
|
||||
const handleModelSelect = useCallback((providerId: string, modelId: string) => {
|
||||
setModel({ providerID: providerId, modelID: modelId });
|
||||
onOpenChange(false);
|
||||
}, [sessionID, client, updateSettings, onOpenChange]);
|
||||
}, [setModel, onOpenChange]);
|
||||
|
||||
const searchResetKey = selectedProvider;
|
||||
|
||||
@@ -491,6 +522,8 @@ export function ModelSelectDialog({
|
||||
currentModel={currentModel}
|
||||
onSelect={handleModelSelect}
|
||||
loading={loading}
|
||||
recentModels={recentFlatModels}
|
||||
showRecent={!selectedProvider && !searchQuery}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in new issue
Block a user