From a8a7e3ace99916ebc226f88995f051c29a3b7970 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 17 Sep 2025 19:44:31 -0500 Subject: [PATCH 1/2] Add one-click GitHub connect --- .env.example | 2 + src/hooks/useGitHubOAuth.ts | 134 ++++++++++++++++++++++++++++++++++++ src/pages/GitSettings.tsx | 112 +++++++++++++++++++++++------- src/pages/Index.tsx | 28 +++++++- src/vite-env.d.ts | 9 +++ 5 files changed, 258 insertions(+), 27 deletions(-) create mode 100644 .env.example create mode 100644 src/hooks/useGitHubOAuth.ts diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..47b88f58 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +VITE_GITHUB_OAUTH_CLIENT_ID="********************" +VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************" \ No newline at end of file diff --git a/src/hooks/useGitHubOAuth.ts b/src/hooks/useGitHubOAuth.ts new file mode 100644 index 00000000..4fae32b1 --- /dev/null +++ b/src/hooks/useGitHubOAuth.ts @@ -0,0 +1,134 @@ +import { useState, useCallback } from 'react'; +import { useGitSettings } from './useGitSettings'; + +interface GitHubOAuthState { + isLoading: boolean; + error: string | null; +} + +interface GitHubTokenResponse { + access_token: string; + token_type: string; + scope: string; +} + +export function useGitHubOAuth() { + const [state, setState] = useState({ + isLoading: false, + error: null, + }); + const { addCredential } = useGitSettings(); + + // Check if OAuth is configured + const isOAuthConfigured = !!( + import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID && + import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET + ); + + const initiateOAuth = useCallback(() => { + const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID; + + if (!clientId) { + setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' })); + return; + } + + // Generate a random state parameter for security + const state = crypto.randomUUID(); + localStorage.setItem('github_oauth_state', state); + + // Redirect to GitHub OAuth + const params = new URLSearchParams({ + client_id: clientId, + redirect_uri: window.location.origin + '/', + scope: 'repo', + state: state, + }); + + window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`; + }, []); + + 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'); + } + + // Clean up stored state + localStorage.removeItem('github_oauth_state'); + + 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 + const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + client_id: clientId, + client_secret: clientSecret, + code: code, + }), + }); + + 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 + const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', { + headers: { + 'Authorization': `Bearer ${tokenData.access_token}`, + 'Accept': 'application/vnd.github.v3+json', + }, + }); + + if (!userResponse.ok) { + throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`); + } + + const userData = await userResponse.json(); + + // Store the credentials + addCredential('https://github.com', { + username: userData.login || 'git', + password: tokenData.access_token, + }); + + setState(prev => ({ ...prev, isLoading: false })); + return true; + } catch (error) { + console.error('GitHub OAuth error:', error); + setState(prev => ({ + ...prev, + isLoading: false, + error: error instanceof Error ? error.message : 'OAuth authentication failed' + })); + return false; + } + }, [addCredential]); + + return { + ...state, + isOAuthConfigured, + initiateOAuth, + handleCallback, + }; +} \ No newline at end of file diff --git a/src/pages/GitSettings.tsx b/src/pages/GitSettings.tsx index f894a20a..49607a2a 100644 --- a/src/pages/GitSettings.tsx +++ b/src/pages/GitSettings.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { Check, GitBranch, ArrowLeft } from 'lucide-react'; +import { Check, GitBranch, ArrowLeft, Github } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -7,6 +7,7 @@ import { Separator } from '@/components/ui/separator'; import { Badge } from '@/components/ui/badge'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { useGitSettings } from '@/hooks/useGitSettings'; +import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useNavigate } from 'react-router-dom'; import type { GitCredential } from '@/contexts/GitSettingsContext'; @@ -38,6 +39,7 @@ const PRESET_PROVIDERS: PresetProvider[] = [ export function GitSettings() { const { settings, addCredential, removeCredential, updateCredential } = useGitSettings(); + const { initiateOAuth, isLoading: isOAuthLoading, error: oauthError, isOAuthConfigured } = useGitHubOAuth(); const isMobile = useIsMobile(); const navigate = useNavigate(); const [customOrigin, setCustomOrigin] = useState(''); @@ -217,7 +219,7 @@ export function GitSettings() {
{preset.name}
- {preset.tokenURL && ( + {preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
-
- setPresetTokens(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} - /> - -
+ + {preset.id === 'github' ? ( + // Special rendering for GitHub - OAuth button if configured, otherwise token input + isOAuthConfigured ? ( +
+ + {oauthError && ( +

+ {oauthError} +

+ )} +
+ ) : ( +
+ setPresetTokens(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + +
+ ) + ) : ( + // Standard rendering for other providers +
+ setPresetTokens(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + +
+ )}
))} diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 986e1a46..548e67c7 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -1,11 +1,13 @@ import { useState, useEffect } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate, useSearchParams } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useAIProjectId } from '@/hooks/useAIProjectId'; import { useFS } from '@/hooks/useFS'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useAISettings } from '@/hooks/useAISettings'; +import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; +import { useToast } from '@/hooks/useToast'; import { AppLayout } from '@/components/AppLayout'; import { DotAI } from '@/lib/DotAI'; import type { AIMessage } from '@/lib/SessionManager'; @@ -20,11 +22,14 @@ export default function Index() { const [prompt, setPrompt] = useState(''); const [isCreating, setIsCreating] = useState(false); const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); + const [searchParams, setSearchParams] = useSearchParams(); const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { fs } = useFS(); const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); const { settings, addRecentlyUsedModel } = useAISettings(); + const { handleCallback: handleGitHubCallback } = useGitHubOAuth(); + const { toast } = useToast(); const [providerModel, setProviderModel] = useState(() => { // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; @@ -36,6 +41,27 @@ export default function Index() { description: 'Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment.', }); + // Handle GitHub OAuth callback + useEffect(() => { + const code = searchParams.get('code'); + const state = searchParams.get('state'); + + if (code && state) { + // Handle GitHub OAuth callback + handleGitHubCallback(code, state).then((success) => { + if (success) { + // Clean up URL parameters + setSearchParams({}); + // Show success toast + toast({ + title: "GitHub Connected", + description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.", + }); + } + }); + } + }, [searchParams, setSearchParams, handleGitHubCallback, toast]); + // Restore prompt from local storage on mount useEffect(() => { if (storedPrompt) { diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe2..bc8afa61 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,10 @@ /// + +interface ImportMetaEnv { + readonly VITE_GITHUB_OAUTH_CLIENT_ID?: string; + readonly VITE_GITHUB_OAUTH_CLIENT_SECRET?: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} From 68edc0b6dcab86347bdaee11b90e8674c26375b2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 17 Sep 2025 20:04:18 -0500 Subject: [PATCH 2/2] Fix trash icon --- src/pages/AISettings.tsx | 8 +++----- src/pages/GitSettings.tsx | 15 +++++++-------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index d582d7d9..945aeddc 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { Check, Bot, ArrowLeft } from 'lucide-react'; +import { Check, Bot, ArrowLeft, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -201,11 +201,9 @@ export function AISettings() { e.stopPropagation(); handleRemoveProvider(providerId); }} - className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive" + className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent" > - - - + diff --git a/src/pages/GitSettings.tsx b/src/pages/GitSettings.tsx index 49607a2a..6b9a411c 100644 --- a/src/pages/GitSettings.tsx +++ b/src/pages/GitSettings.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { Check, GitBranch, ArrowLeft, Github } from 'lucide-react'; +import { Check, GitBranch, ArrowLeft, Github, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -154,18 +154,17 @@ export function GitSettings() { {isCustom && Custom} - + +