20 KiB
Unified OAuth System
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
Architecture
The OAuth system consists of three main components:
- Generic OAuth Hook (
useOAuth) - Core OAuth logic that works with any provider - Provider-Specific Hooks - Thin wrappers that configure the generic hook for specific providers
- OAuth Callback Pages - React components that handle the OAuth redirect flow
Current Supported Providers
- GitHub - Git repository hosting (with PKCE support)
- Netlify - Static site deployment
- Vercel - Static site deployment
- OpenRouter - AI model routing (with PKCE support)
File Structure
src/
├── hooks/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-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
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
Environment Variables
OAuth credentials are stored in environment variables and loaded from process.env:
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
Security Note
Client secrets are stored in environment variables and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
- Shakespeare is a client-side application with no backend
- The OAuth tokens are scoped to specific permissions
- Users can revoke tokens at any time from the provider's settings
- The redirect URIs are validated by the OAuth provider
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
How It Works
1. Generic OAuth Hook (useOAuth)
The useOAuth hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
Configuration Interface:
interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
clientId: string; // OAuth client ID
clientSecret: string; // OAuth client secret
authorizeUrl: string; // Provider's authorization endpoint
tokenUrl: string; // Provider's token exchange endpoint
scope?: string; // Requested OAuth scopes (optional)
redirectUri: string; // Callback URL after authorization
usePKCE?: boolean; // Enable PKCE (default: false)
getUserInfo?: ( // Optional function to fetch user info
accessToken: string,
corsProxy: string
) => Promise<{
username: string;
[key: string]: unknown;
}>;
}
Returned API:
{
isLoading: boolean; // True during token exchange
error: string | null; // Error message if OAuth fails
isOAuthConfigured: boolean; // True if client ID and secret are set
initiateOAuth: () => void; // Start the OAuth flow
handleCallback: ( // Handle the OAuth callback
code: string,
state: string
) => Promise<OAuthResult | null>;
}
2. OAuth Flow Steps
Step 1: Initiate OAuth
When the user clicks "Connect to [Provider]", the initiateOAuth() function:
- Generates a random
stateparameter for CSRF protection - Optionally generates PKCE parameters (code verifier and challenge)
- Stores the state and code verifier in localStorage
- Redirects to the provider's authorization page
const { initiateOAuth } = useGitHubOAuth();
// User clicks button
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
Step 2: User Authorizes
The user is redirected to the provider's authorization page where they:
- Log in to their account (if not already logged in)
- Review the requested permissions
- Approve or deny the authorization request
Step 3: OAuth Callback
After authorization, the provider redirects back to the callback URL with:
code- Authorization codestate- The state parameter we senterror(optional) - Error code if authorization failederror_description(optional) - Human-readable error description
The callback page (e.g., GitHubOAuth.tsx) extracts these parameters and calls handleCallback().
Step 4: Token Exchange
The handleCallback() function:
- Verifies the
stateparameter matches what we stored - Retrieves the PKCE code verifier (if PKCE is enabled)
- Exchanges the authorization code for an access token
- Optionally fetches user information using the access token
- Returns an
OAuthResultobject with the token and user data
interface OAuthResult {
accessToken: string; // OAuth access token
username?: string; // User's username/email
scopes?: string[]; // Granted OAuth scopes
userData?: Record<string, unknown>; // Additional user data
}
Step 5: Store Credentials
Provider-specific hooks override handleCallback to store the credentials appropriately:
- GitHub: Stores in Git settings (for push/pull operations)
- Netlify/Vercel: Stores in Deploy settings (for deployment operations)
3. PKCE Support
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
How PKCE works:
- Generate a random
code_verifier(cryptographically random string) - Create a
code_challengeby hashing the verifier with SHA-256 - Send the
code_challengeduring authorization - Send the
code_verifierduring token exchange - The server verifies that the verifier matches the challenge
Enabling PKCE:
const config: OAuthConfig = {
// ... other config
usePKCE: true, // Enable PKCE
};
Provider Support:
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
- ✅ OpenRouter - Requires PKCE (enabled)
Scope Parameter
The scope parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
Provider Scope Usage:
- ✅ 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:
- No Client Credentials: OpenRouter doesn't require client ID or client secret - it uses PKCE only
- Authorization URL: Uses
callback_urlparameter instead ofredirect_uri - Token Exchange: Posts to
/api/v1/auth/keyswith a simplified request body - Response Format: Returns
{ key }instead of standard{ access_token } - PKCE Required: Must use PKCE with S256 code challenge method
- No User Info: Doesn't provide a user info endpoint after authentication
- 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:
{
"code": "<CODE_FROM_QUERY_PARAM>",
"code_verifier": "<CODE_VERIFIER>",
"code_challenge_method": "S256"
}
Token Exchange Response:
{
"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
To add a new OAuth provider, follow these steps:
1. Add Environment Variables
Add the client ID and secret to .env.example:
# NewProvider OAuth Configuration
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
2. Create Provider-Specific Hook
Create a new file src/hooks/useNewProviderOAuth.ts:
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { proxyUrl } from '@/lib/proxyUrl';
interface NewProviderUserInfo {
id: string;
email: string;
// ... other user fields
}
export function useNewProviderOAuth() {
// Get the context where you want to store credentials
// e.g., useDeploySettings() or useGitSettings()
const { setProviders, settings } = useDeploySettings();
const config: OAuthConfig = {
provider: 'newprovider',
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://provider.com/oauth/authorize',
tokenUrl: 'https://provider.com/oauth/token',
scope: 'read write', // Optional - omit if provider doesn't use scopes
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
}
const userData: NewProviderUserInfo = await userResponse.json();
return {
username: userData.email,
...userData,
};
},
};
const oauth = useOAuth(config);
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Store the credentials in the appropriate context
// This will vary based on what the provider is used for
const newProvider = {
id: crypto.randomUUID(),
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
type: 'newprovider',
apiKey: result.accessToken,
proxy: true,
};
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
3. Create OAuth Callback Page
Create a new file src/pages/NewProviderOAuth.tsx:
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function NewProviderOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useNewProviderOAuth();
const { toast } = useToast();
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('newprovider_oauth_state');
if (error) {
toast({
title: "NewProvider OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy'); // or appropriate settings page
return;
}
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "NewProvider Connected",
description: "Successfully connected to NewProvider.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to NewProvider. Please try again.",
variant: "destructive",
});
}
navigate('/settings/deploy'); // or appropriate settings page
});
} else {
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate]);
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">
{/* Provider logo/icon */}
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
{/* Provider icon SVG */}
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
<p className="text-muted-foreground">
Processing your NewProvider 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>
);
}
4. Add Route
Add the OAuth callback route to src/AppRouter.tsx:
import NewProviderOAuth from "./pages/NewProviderOAuth";
// ...
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
5. Add to UI
Add the provider to the appropriate settings page (e.g., DeploySettings.tsx):
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
// In component:
const newProviderOAuth = useNewProviderOAuth();
// In PRESET_PROVIDERS array:
{
id: 'newprovider',
type: 'newprovider',
name: 'NewProvider',
description: 'Deploy to NewProvider',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://provider.com/settings/tokens',
proxy: true,
}
// In the render logic, add the OAuth hook to the switch:
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
preset.type === 'vercel' ? vercelOAuth :
preset.type === 'newprovider' ? newProviderOAuth : null;
6. Register OAuth Application
Register your OAuth application with the provider:
- Go to the provider's developer settings
- Create a new OAuth application
- Set the redirect URI to:
https://yourdomain.com/oauth/newprovider - Note the client ID and client secret
- Add them to your
.envfile
Testing OAuth Flow
To test the OAuth flow locally:
-
Set up a tunnel (e.g., ngrok, cloudflared) to expose localhost:
npx cloudflared tunnel --url http://localhost:5173 -
Register OAuth app with the tunnel URL as the redirect URI:
https://your-tunnel-url.trycloudflare.com/oauth/provider -
Add credentials to
.env:VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id" VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret" -
Start the dev server:
npm run dev -
Test the flow by clicking the "Connect to Provider" button
Error Handling
The OAuth system handles several types of errors:
User Denies Authorization
If the user denies authorization, the provider redirects with an error parameter:
/oauth/provider?error=access_denied&error_description=User+denied+access
The callback page displays an error toast and redirects to settings.
Invalid State Parameter
If the state parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
Token Exchange Failure
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
Missing PKCE Verifier
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
Security Considerations
- State Parameter: Always used for CSRF protection
- PKCE: Used when supported by the provider for additional security
- HTTPS Only: OAuth should only be used over HTTPS in production
- Token Storage: Tokens are stored in browser storage (localStorage/IndexedDB)
- Token Revocation: Users can revoke tokens from the provider's settings
- Scope Limitation: Request only the minimum required scopes
Troubleshooting
"OAuth client ID not configured"
The environment variables are not set. Check your .env file and ensure the variables are prefixed with VITE_.
"Invalid OAuth state parameter"
The state parameter doesn't match. This could be caused by:
- Multiple OAuth flows running simultaneously
- Browser localStorage being cleared mid-flow
- CSRF attack attempt
"Failed to verify token"
The provider's API rejected the access token. This could be caused by:
- Incorrect API endpoint URL
- Token doesn't have required scopes
- Provider API is down
Redirect URI Mismatch
The redirect URI in your OAuth app registration must exactly match the URI in your code:
redirectUri: window.location.origin + '/oauth/provider'
For local development with a tunnel, this would be:
https://your-tunnel-url.trycloudflare.com/oauth/provider
Best Practices
- Always use PKCE when the provider supports it
- Request minimal scopes - only what you need
- Handle errors gracefully - show user-friendly error messages
- Clear localStorage on errors to prevent stuck states
- Validate tokens by fetching user info after exchange
- Store tokens securely - use appropriate browser storage APIs
- Provide token revocation - link to provider's token management page
- Test error cases - user denial, network failures, etc.
Future Improvements
Potential enhancements to the OAuth system:
- Token Refresh: Implement refresh token flow for long-lived sessions
- Token Expiry: Track token expiration and prompt for re-authentication
- Multiple Accounts: Support multiple accounts per provider
- Backend Proxy: Optional backend service for secure token exchange
- Device Flow: Support OAuth device flow for CLI tools
- Biometric Auth: Integrate with WebAuthn for passwordless OAuth