Add OpenRouter OAuth

This commit is contained in:
Alex Gleason committed 2026-01-04 12:36:15 -06:00
1 parent ddc23e3800
commit 104a08c75a
7 files changed
+403 -8

No files matched your search

+42 -2
View File
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
- **OpenRouter** - AI model routing (with PKCE support)
## File Structure
@@ -24,11 +25,13 @@ src/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
│ ├── useVercelOAuth.ts # Vercel-specific configuration
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
- ✅ OpenRouter - Requires PKCE (enabled)
### Scope Parameter
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
### OpenRouter Custom OAuth Implementation
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
5. **PKCE Required**: Must use PKCE with S256 code challenge method
6. **No User Info**: Doesn't provide a user info endpoint after authentication
7. **No Environment Variables**: No configuration needed - works out of the box
**Authorization URL Format:**
```
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
```
**Token Exchange Request:**
```json
{
"code": "<CODE_FROM_QUERY_PARAM>",
"code_verifier": "<CODE_VERIFIER>",
"code_challenge_method": "S256"
}
```
**Token Exchange Response:**
```json
{
"key": "sk-or-v1-..."
}
```
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
## Adding a New OAuth Provider
+2
View File
@@ -18,6 +18,7 @@ import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -39,6 +40,7 @@ export function AppRouter() {
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
+85 -4
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot } from 'lucide-react';
import { Bot, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { ExternalInput } from '@/components/ui/external-input';
@@ -12,15 +12,31 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import type { PresetProvider } from '@/lib/aiProviderPresets';
interface OAuthHook {
isOAuthConfigured: boolean;
isLoading: boolean;
error: string | null;
initiateOAuth: () => void;
}
interface AddAIProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetProvider;
isLoggedIntoNostr: boolean;
oauthHook?: OAuthHook | null;
forceManualEntry?: boolean;
onSetForceManualEntry?: (force: boolean) => void;
onAdd: (apiKey: string) => void;
}
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
onOpenChange,
preset,
isLoggedIntoNostr,
oauthHook,
forceManualEntry = false,
onSetForceManualEntry,
onAdd,
}: AddAIProviderDialogProps) {
const { t } = useTranslation();
@@ -36,16 +55,27 @@ export function AddAIProviderDialog({
const [termsAgreed, setTermsAgreed] = useState(false);
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey);
setApiKey('');
setTermsAgreed(false);
onOpenChange(false);
};
// Reset state when dialog closes
const handleOpenChange = (open: boolean) => {
if (!open) {
setApiKey('');
setTermsAgreed(false);
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
@@ -73,6 +103,57 @@ export function AddAIProviderDialog({
</Link>
</Button>
</div>
) : isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
<div className="space-y-3">
{!preset.nostr && preset.apiKeysURL && (
@@ -123,7 +204,7 @@ export function AddAIProviderDialog({
)}
</div>
{!showNostrLoginRequired && (
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
+1 -1
View File
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel';
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
clientId: string;
clientSecret: string;
authorizeUrl: string;
+164
View File
@@ -0,0 +1,164 @@
import { useState, useCallback } from 'react';
import { useAISettings } from './useAISettings';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface OpenRouterTokenResponse {
key: string;
}
/**
* Hook for OpenRouter OAuth authentication with PKCE.
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
* It uses PKCE without requiring client credentials.
*/
export function useOpenRouterOAuth() {
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// OpenRouter doesn't require client credentials - it uses PKCE only
const isOAuthConfigured = true;
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
/**
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
*/
const initiateOAuth = useCallback(async () => {
try {
// Generate a random state parameter for security
const state = crypto.randomUUID();
const storagePrefix = 'openrouter_oauth';
// Store state for later verification
localStorage.setItem(`${storagePrefix}_state`, state);
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
// Build authorization URL
const redirectUri = window.location.origin + '/oauth/openrouter';
const params = new URLSearchParams({
callback_url: redirectUri,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
// Redirect to OpenRouter's authorization page
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
} catch (error) {
console.error('Failed to initiate OpenRouter OAuth:', error);
setError('Failed to generate PKCE parameters. Please try again.');
}
}, []);
/**
* Handles the OAuth callback after the user authorizes the application.
* Exchanges the authorization code for an API key.
*/
const handleCallback = useCallback(async (
code: string,
_state: string
): Promise<boolean> => {
setIsLoading(true);
setError(null);
const storagePrefix = 'openrouter_oauth';
try {
// Get PKCE code verifier
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
// Clean up stored values
localStorage.removeItem(`${storagePrefix}_state`);
localStorage.removeItem(`${storagePrefix}_code_verifier`);
// Exchange code for API key using OpenRouter's custom endpoint
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: code,
code_verifier: codeVerifier,
code_challenge_method: 'S256',
}),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
}
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
if (!tokenData.key) {
throw new Error('No API key received from OpenRouter');
}
// Wait for settings to be initialized before storing
if (isSettingsLoading) {
throw new Error('Settings not initialized. Please try again.');
}
// Create a new OpenRouter provider with the OAuth token
const newProvider: AIProvider = {
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: tokenData.key,
};
// Add or update the OpenRouter provider in settings
setProvider(newProvider);
setIsLoading(false);
return true;
} catch (error) {
console.error('OpenRouter OAuth error:', error);
// Clean up any remaining OAuth data on error
localStorage.removeItem(`${storagePrefix}_state`);
localStorage.removeItem(`${storagePrefix}_code_verifier`);
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
setIsLoading(false);
return false;
}
}, [setProvider, isSettingsLoading]);
return {
isLoading,
error,
isOAuthConfigured,
initiateOAuth,
handleCallback,
};
}
+13 -1
View File
@@ -16,6 +16,7 @@ import { CreditsBadge } from '@/components/CreditsBadge';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
@@ -45,6 +46,7 @@ export function AISettings() {
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
const { user } = useCurrentUser();
const { config, defaultConfig, updateConfig } = useAppContext();
const openRouterOAuth = useOpenRouterOAuth();
const [showAdvanced, setShowAdvanced] = useState(false);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
@@ -54,6 +56,7 @@ export function AISettings() {
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
const [forceManualEntry, setForceManualEntry] = useState(false);
// Drag and drop sensors
const sensors = useSensors(
@@ -256,9 +259,18 @@ export function AISettings() {
{selectedPreset && (
<AddAIProviderDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onOpenChange={(open) => {
setAddDialogOpen(open);
if (!open) {
// Reset force manual entry when dialog closes
setForceManualEntry(false);
}
}}
preset={selectedPreset}
isLoggedIntoNostr={!!user}
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
forceManualEntry={forceManualEntry}
onSetForceManualEntry={setForceManualEntry}
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
/>
)}
+96
View File
@@ -0,0 +1,96 @@
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
import { Bot } from 'lucide-react';
export default function OpenRouterOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useOpenRouterOAuth();
const { isLoading: isSettingsLoading } = useAISettings();
const { toast } = useToast();
useEffect(() => {
// Wait for AI settings to be initialized
if (isSettingsLoading) {
return;
}
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedCodeVerifier = localStorage.getItem('openrouter_oauth_code_verifier');
// Handle OAuth errors
if (error) {
toast({
title: "OpenRouter OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/ai');
return;
}
// Handle successful OAuth callback
if (code && storedCodeVerifier) {
handleCallback(code, state || '').then((success) => {
if (success) {
toast({
title: "OpenRouter Connected",
description: "Successfully connected to OpenRouter. You can now use OpenRouter models.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to OpenRouter. Please try again.",
variant: "destructive",
});
}
// Always redirect to AI settings after handling the callback
navigate('/settings/ai');
});
} else if (code && !storedCodeVerifier) {
// Missing code verifier - likely an incomplete PKCE flow
toast({
title: "Authentication Error",
description: "OAuth flow is incomplete. Please try connecting to OpenRouter again.",
variant: "destructive",
});
// Clean up any remaining OAuth data
localStorage.removeItem('openrouter_oauth_state');
localStorage.removeItem('openrouter_oauth_code_verifier');
navigate('/settings/ai');
} else {
// No code parameter - redirect to AI settings
navigate('/settings/ai');
}
}, [searchParams, handleCallback, toast, navigate, isSettingsLoading]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
<div className="flex justify-center">
<Bot className="h-12 w-12 text-primary" />
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to OpenRouter</h1>
<p className="text-muted-foreground">
Processing your OpenRouter authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}