mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Netlify/Vercel OAuth
This commit is contained in:
9 files changed
+697
-175
No files matched your search
@@ -16,6 +16,8 @@ import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -31,6 +33,8 @@ export function AppRouter() {
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
|
||||
+60
-173
@@ -1,157 +1,40 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import type { GitHostToken } from '@/contexts/GitSettingsContext';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface GitHubTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
interface GitHubUserInfo {
|
||||
login: string;
|
||||
id: number;
|
||||
avatar_url?: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for GitHub OAuth authentication.
|
||||
* Uses the generic useOAuth hook with GitHub-specific configuration.
|
||||
*/
|
||||
export function useGitHubOAuth() {
|
||||
const [state, setState] = useState<GitHubOAuthState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential, addHostToken } = useGitSettings();
|
||||
const { config } = useAppContext();
|
||||
const { corsProxy } = config;
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID &&
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
|
||||
);
|
||||
|
||||
// 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, '');
|
||||
};
|
||||
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
|
||||
if (!clientId) {
|
||||
setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' }));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate PKCE parameters
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
|
||||
// Store both state and code verifier for later use
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
localStorage.setItem('github_oauth_code_verifier', codeVerifier);
|
||||
|
||||
// Redirect to GitHub OAuth with PKCE parameters
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/oauth/github',
|
||||
scope: 'repo workflow',
|
||||
state: state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate OAuth with PKCE:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
error: 'Failed to generate PKCE parameters. Please try again.'
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleCallback = useCallback(async (code: string, state: string) => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
// Verify state parameter
|
||||
const storedState = localStorage.getItem('github_oauth_state');
|
||||
if (!storedState || storedState !== state) {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Get the stored code verifier for PKCE
|
||||
const codeVerifier = localStorage.getItem('github_oauth_code_verifier');
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
localStorage.removeItem('github_oauth_code_verifier');
|
||||
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error('GitHub OAuth credentials not configured');
|
||||
}
|
||||
|
||||
// Exchange code for access token with PKCE code verifier
|
||||
const tokenRequestBody = {
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
redirect_uri: window.location.origin + '/oauth/github',
|
||||
code_verifier: codeVerifier,
|
||||
};
|
||||
|
||||
const tokenUrl = proxyUrl(corsProxy, 'https://github.com/login/oauth/access_token');
|
||||
const tokenResponse = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(tokenRequestBody),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error(`GitHub OAuth token exchange failed: ${tokenResponse.statusText}`);
|
||||
}
|
||||
|
||||
const tokenData: GitHubTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.access_token) {
|
||||
throw new Error('No access token received from GitHub');
|
||||
}
|
||||
|
||||
// Get user info to verify the token works
|
||||
// GitHub OAuth configuration
|
||||
const config: OAuthConfig = {
|
||||
provider: 'github',
|
||||
clientId: import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID || '',
|
||||
clientSecret: import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET || '',
|
||||
authorizeUrl: 'https://github.com/login/oauth/authorize',
|
||||
tokenUrl: 'https://github.com/login/oauth/access_token',
|
||||
scope: 'repo workflow',
|
||||
redirectUri: window.location.origin + '/oauth/github',
|
||||
usePKCE: true, // GitHub supports PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokenData.access_token}`,
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
@@ -160,45 +43,49 @@ export function useGitHubOAuth() {
|
||||
throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
// Store the credentials (legacy format for existing push/pull operations)
|
||||
addCredential('https://github.com', {
|
||||
username: userData.login || 'git',
|
||||
password: tokenData.access_token,
|
||||
});
|
||||
|
||||
// Also store as host token for PR/contribution operations
|
||||
const hostToken: GitHostToken = {
|
||||
token: tokenData.access_token,
|
||||
const userData: GitHubUserInfo = await userResponse.json();
|
||||
return {
|
||||
username: userData.login,
|
||||
scopes: tokenData.scope ? tokenData.scope.split(',').map(s => s.trim()) : [],
|
||||
createdAt: Date.now(),
|
||||
...userData,
|
||||
};
|
||||
addHostToken('github.com', hostToken);
|
||||
},
|
||||
};
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('GitHub OAuth error:', error);
|
||||
const oauth = useOAuth(config);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
localStorage.removeItem('github_oauth_code_verifier');
|
||||
/**
|
||||
* Handles the OAuth callback and stores the credentials in git settings.
|
||||
*/
|
||||
const handleCallbackAndStore = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<boolean> => {
|
||||
const result: OAuthResult | null = await oauth.handleCallback(code, state);
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'OAuth authentication failed'
|
||||
}));
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
}, [addCredential, addHostToken, corsProxy]);
|
||||
|
||||
// Store the credentials (legacy format for existing push/pull operations)
|
||||
addCredential('https://github.com', {
|
||||
username: result.username || 'git',
|
||||
password: result.accessToken,
|
||||
});
|
||||
|
||||
// Also store as host token for PR/contribution operations
|
||||
const hostToken: GitHostToken = {
|
||||
token: result.accessToken,
|
||||
username: result.username || 'git',
|
||||
scopes: result.scopes || [],
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
addHostToken('github.com', hostToken);
|
||||
|
||||
return true;
|
||||
}, [oauth, addCredential, addHostToken]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
...oauth,
|
||||
handleCallback: handleCallbackAndStore,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
|
||||
import { useDeploySettings } from './useDeploySettings';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import type { NetlifyProvider } from '@/contexts/DeploySettingsContext';
|
||||
|
||||
interface NetlifyUserInfo {
|
||||
id: string;
|
||||
email: string;
|
||||
full_name?: string;
|
||||
avatar_url?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for Netlify OAuth authentication.
|
||||
* Uses the generic useOAuth hook with Netlify-specific configuration.
|
||||
*/
|
||||
export function useNetlifyOAuth() {
|
||||
const { setProviders, settings } = useDeploySettings();
|
||||
|
||||
// Netlify OAuth configuration
|
||||
const config: OAuthConfig = {
|
||||
provider: 'netlify',
|
||||
clientId: import.meta.env.VITE_NETLIFY_OAUTH_CLIENT_ID || '',
|
||||
clientSecret: import.meta.env.VITE_NETLIFY_OAUTH_CLIENT_SECRET || '',
|
||||
authorizeUrl: 'https://app.netlify.com/authorize',
|
||||
tokenUrl: 'https://api.netlify.com/oauth/token',
|
||||
scope: 'deploy',
|
||||
redirectUri: window.location.origin + '/oauth/netlify',
|
||||
usePKCE: false, // Netlify doesn't require PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify Netlify token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData: NetlifyUserInfo = await userResponse.json();
|
||||
return {
|
||||
username: userData.email || userData.full_name || 'Netlify User',
|
||||
...userData,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const oauth = useOAuth(config);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback and stores the credentials in deploy settings.
|
||||
*/
|
||||
const handleCallbackAndStore = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<boolean> => {
|
||||
const result: OAuthResult | null = await oauth.handleCallback(code, state);
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a new Netlify provider with the OAuth token
|
||||
const newProvider: NetlifyProvider = {
|
||||
id: crypto.randomUUID(),
|
||||
name: result.username ? `Netlify (${result.username})` : 'Netlify',
|
||||
type: 'netlify',
|
||||
apiKey: result.accessToken,
|
||||
proxy: true, // Netlify typically requires CORS proxy
|
||||
};
|
||||
|
||||
// Add the new provider to settings
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
|
||||
return true;
|
||||
}, [oauth, setProviders, settings.providers]);
|
||||
|
||||
return {
|
||||
...oauth,
|
||||
handleCallback: handleCallbackAndStore,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel';
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
authorizeUrl: string;
|
||||
tokenUrl: string;
|
||||
scope: string;
|
||||
redirectUri: string;
|
||||
usePKCE?: boolean;
|
||||
getUserInfo?: (accessToken: string, corsProxy: string) => Promise<{
|
||||
username: string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface OAuthState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface OAuthTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface OAuthResult {
|
||||
accessToken: string;
|
||||
username?: string;
|
||||
scopes?: string[];
|
||||
userData?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic OAuth hook that handles the OAuth 2.0 flow with optional PKCE support.
|
||||
* This hook can be used for any OAuth provider by passing the appropriate configuration.
|
||||
*/
|
||||
export function useOAuth(config: OAuthConfig) {
|
||||
const [state, setState] = useState<OAuthState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { config: appConfig } = useAppContext();
|
||||
const { corsProxy } = appConfig;
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(config.clientId && config.clientSecret);
|
||||
|
||||
// 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 the provider's authorization page.
|
||||
*/
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
if (!config.clientId) {
|
||||
setState(prev => ({ ...prev, error: `${config.provider} OAuth client ID not configured` }));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
const storagePrefix = `${config.provider}_oauth`;
|
||||
|
||||
// Store state for later verification
|
||||
localStorage.setItem(`${storagePrefix}_state`, state);
|
||||
|
||||
// Build authorization URL params
|
||||
const params = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
scope: config.scope,
|
||||
state: state,
|
||||
response_type: 'code',
|
||||
});
|
||||
|
||||
// Add PKCE parameters if enabled
|
||||
if (config.usePKCE) {
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
|
||||
params.append('code_challenge', codeChallenge);
|
||||
params.append('code_challenge_method', 'S256');
|
||||
}
|
||||
|
||||
// Redirect to provider's authorization page
|
||||
window.location.href = `${config.authorizeUrl}?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error(`Failed to initiate ${config.provider} OAuth:`, error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
error: config.usePKCE
|
||||
? 'Failed to generate PKCE parameters. Please try again.'
|
||||
: 'Failed to initiate OAuth. Please try again.'
|
||||
}));
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback after the user authorizes the application.
|
||||
* Exchanges the authorization code for an access token.
|
||||
*/
|
||||
const handleCallback = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<OAuthResult | null> => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
const storagePrefix = `${config.provider}_oauth`;
|
||||
|
||||
try {
|
||||
// Verify state parameter
|
||||
const storedState = localStorage.getItem(`${storagePrefix}_state`);
|
||||
if (!storedState || storedState !== state) {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Build token request body
|
||||
const tokenRequestBody: Record<string, string> = {
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
code: code,
|
||||
redirect_uri: config.redirectUri,
|
||||
grant_type: 'authorization_code',
|
||||
};
|
||||
|
||||
// Add PKCE code verifier if enabled
|
||||
if (config.usePKCE) {
|
||||
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
tokenRequestBody.code_verifier = codeVerifier;
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
if (config.usePKCE) {
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
|
||||
const tokenResponse = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(tokenRequestBody),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
const errorText = await tokenResponse.text();
|
||||
throw new Error(`OAuth token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const tokenData: OAuthTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.access_token) {
|
||||
throw new Error('No access token received');
|
||||
}
|
||||
|
||||
// Build result object
|
||||
const result: OAuthResult = {
|
||||
accessToken: tokenData.access_token,
|
||||
scopes: tokenData.scope ? tokenData.scope.split(/[\s,]+/).map(s => s.trim()).filter(Boolean) : [],
|
||||
};
|
||||
|
||||
// Get user info if getUserInfo function is provided
|
||||
if (config.getUserInfo) {
|
||||
try {
|
||||
const userData = await config.getUserInfo(tokenData.access_token, corsProxy);
|
||||
result.username = userData.username;
|
||||
result.userData = userData;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to fetch user info for ${config.provider}:`, error);
|
||||
// Continue without user info - it's optional
|
||||
}
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(`${config.provider} OAuth error:`, error);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
if (config.usePKCE) {
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
}
|
||||
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'OAuth authentication failed'
|
||||
}));
|
||||
return null;
|
||||
}
|
||||
}, [config, corsProxy]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
|
||||
import { useDeploySettings } from './useDeploySettings';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import type { VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
|
||||
interface VercelUserInfo {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
username?: string;
|
||||
avatar?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for Vercel OAuth authentication.
|
||||
* Uses the generic useOAuth hook with Vercel-specific configuration.
|
||||
*/
|
||||
export function useVercelOAuth() {
|
||||
const { setProviders, settings } = useDeploySettings();
|
||||
|
||||
// Vercel OAuth configuration
|
||||
const config: OAuthConfig = {
|
||||
provider: 'vercel',
|
||||
clientId: import.meta.env.VITE_VERCEL_OAUTH_CLIENT_ID || '',
|
||||
clientSecret: import.meta.env.VITE_VERCEL_OAUTH_CLIENT_SECRET || '',
|
||||
authorizeUrl: 'https://vercel.com/oauth/authorize',
|
||||
tokenUrl: 'https://api.vercel.com/v2/oauth/access_token',
|
||||
scope: 'deployments:write deployments:read projects:read projects:write',
|
||||
redirectUri: window.location.origin + '/oauth/vercel',
|
||||
usePKCE: false, // Vercel doesn't require PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify Vercel token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData: VercelUserInfo = await userResponse.json();
|
||||
return {
|
||||
username: userData.user.username || userData.user.email || userData.user.name || 'Vercel User',
|
||||
...userData.user,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const oauth = useOAuth(config);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback and stores the credentials in deploy settings.
|
||||
*/
|
||||
const handleCallbackAndStore = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<boolean> => {
|
||||
const result: OAuthResult | null = await oauth.handleCallback(code, state);
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a new Vercel provider with the OAuth token
|
||||
const newProvider: VercelProvider = {
|
||||
id: crypto.randomUUID(),
|
||||
name: result.username ? `Vercel (${result.username})` : 'Vercel',
|
||||
type: 'vercel',
|
||||
apiKey: result.accessToken,
|
||||
proxy: true, // Vercel typically requires CORS proxy
|
||||
};
|
||||
|
||||
// Add the new provider to settings
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
|
||||
return true;
|
||||
}, [oauth, setProviders, settings.providers]);
|
||||
|
||||
return {
|
||||
...oauth,
|
||||
handleCallback: handleCallbackAndStore,
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import { Label } from '@/components/ui/label';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { useDeploySettings } from '@/hooks/useDeploySettings';
|
||||
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
|
||||
import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
@@ -42,6 +44,7 @@ interface PresetProvider {
|
||||
apiKeyLabel?: string;
|
||||
apiKeyURL?: string;
|
||||
proxy?: boolean;
|
||||
supportsOAuth?: boolean;
|
||||
}
|
||||
|
||||
interface SortableProviderItemProps {
|
||||
@@ -200,6 +203,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
apiKeyLabel: 'Personal Access Token',
|
||||
apiKeyURL: 'https://app.netlify.com/user/applications#personal-access-tokens',
|
||||
proxy: true,
|
||||
supportsOAuth: true,
|
||||
},
|
||||
{
|
||||
id: 'vercel',
|
||||
@@ -209,6 +213,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
apiKeyLabel: 'Access Token',
|
||||
apiKeyURL: 'https://vercel.com/account/tokens',
|
||||
proxy: true,
|
||||
supportsOAuth: true,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -219,6 +224,10 @@ export function DeploySettings() {
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// OAuth hooks
|
||||
const netlifyOAuth = useNetlifyOAuth();
|
||||
const vercelOAuth = useVercelOAuth();
|
||||
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
|
||||
// Custom provider form state
|
||||
@@ -436,11 +445,18 @@ export function DeploySettings() {
|
||||
const isLoggedIntoNostr = !!user;
|
||||
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
|
||||
|
||||
// Get OAuth hook for this preset
|
||||
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
|
||||
preset.type === 'vercel' ? vercelOAuth : null;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
return (
|
||||
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h5 className="font-medium">{preset.name}</h5>
|
||||
{preset.apiKeyURL && (
|
||||
{preset.apiKeyURL && !isOAuthConfigured && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground"
|
||||
@@ -462,7 +478,46 @@ export function DeploySettings() {
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : preset.supportsOAuth && isOAuthConfigured ? (
|
||||
// Show OAuth button if OAuth is configured
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="w-full max-w-full gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{preset.type === 'netlify' && (
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M16.934 8.519a1.044 1.044 0 0 1 .303.23l2.349 2.348a1 1 0 0 1 0 1.414l-2.348 2.349a1.044 1.044 0 0 1-.231.303 1.042 1.042 0 0 1-1.473-1.473l.527-.527H11a1 1 0 1 1 0-2h5.061l-.527-.527a1.042 1.042 0 0 1 1.4-1.517zM7.066 15.481a1.044 1.044 0 0 1-.303-.23l-2.349-2.348a1 1 0 0 1 0-1.414l2.348-2.349a1.044 1.044 0 0 1 .231-.303 1.042 1.042 0 0 1 1.473 1.473l-.527.527H13a1 1 0 0 1 0 2H7.939l.527.527a1.042 1.042 0 0 1-1.4 1.517z" />
|
||||
</svg>
|
||||
)}
|
||||
{preset.type === 'vercel' && (
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 1.5L24 22.5H0L12 1.5z" />
|
||||
</svg>
|
||||
)}
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Show manual token input
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.requiresNostr && (
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
export default function NetlifyOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useNetlifyOAuth();
|
||||
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('netlify_oauth_state');
|
||||
|
||||
// Handle OAuth errors
|
||||
if (error) {
|
||||
toast({
|
||||
title: "Netlify OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/deploy');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle successful OAuth callback
|
||||
if (code && state && storedState) {
|
||||
handleCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "Netlify Connected",
|
||||
description: "Successfully connected to Netlify. You can now deploy your projects.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to Netlify. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
// Always redirect to Deploy settings after handling the callback
|
||||
navigate('/settings/deploy');
|
||||
});
|
||||
} else {
|
||||
// No code or state parameters - redirect to Deploy settings
|
||||
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">
|
||||
<div className="flex justify-center">
|
||||
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M16.934 8.519a1.044 1.044 0 0 1 .303.23l2.349 2.348a1 1 0 0 1 0 1.414l-2.348 2.349a1.044 1.044 0 0 1-.231.303 1.042 1.042 0 0 1-1.473-1.473l.527-.527H11a1 1 0 1 1 0-2h5.061l-.527-.527a1.042 1.042 0 0 1 1.4-1.517zM7.066 15.481a1.044 1.044 0 0 1-.303-.23l-2.349-2.348a1 1 0 0 1 0-1.414l2.348-2.349a1.044 1.044 0 0 1 .231-.303 1.042 1.042 0 0 1 1.473 1.473l-.527.527H13a1 1 0 0 1 0 2H7.939l.527.527a1.042 1.042 0 0 1-1.4 1.517z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to Netlify</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your Netlify 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
export default function VercelOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useVercelOAuth();
|
||||
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('vercel_oauth_state');
|
||||
|
||||
// Handle OAuth errors
|
||||
if (error) {
|
||||
toast({
|
||||
title: "Vercel OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/deploy');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle successful OAuth callback
|
||||
if (code && state && storedState) {
|
||||
handleCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "Vercel Connected",
|
||||
description: "Successfully connected to Vercel. You can now deploy your projects.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to Vercel. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
// Always redirect to Deploy settings after handling the callback
|
||||
navigate('/settings/deploy');
|
||||
});
|
||||
} else {
|
||||
// No code or state parameters - redirect to Deploy settings
|
||||
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">
|
||||
<div className="flex justify-center">
|
||||
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 1.5L24 22.5H0L12 1.5z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to Vercel</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your Vercel 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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user