diff --git a/src/components/DeploySettingsProvider.tsx b/src/components/DeploySettingsProvider.tsx index 5e74b5a2..c5f67a01 100644 --- a/src/components/DeploySettingsProvider.tsx +++ b/src/components/DeploySettingsProvider.tsx @@ -69,6 +69,7 @@ export function DeploySettingsProvider({ children }: { children: ReactNode }) { removeProvider, setProviders, isConfigured, + isInitialized, }; return ( diff --git a/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index f6cdaa5b..227e1d8d 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -131,6 +131,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { removeHostToken, updateHostToken, isConfigured, + isInitialized, }; return ( diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 0a4be210..1125a3d0 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -36,6 +36,7 @@ export interface DeploySettingsContextType { removeProvider: (index: number) => void; setProviders: (providers: DeployProvider[]) => void; isConfigured: boolean; + isInitialized: boolean; } export const DeploySettingsContext = createContext(undefined); diff --git a/src/contexts/GitSettingsContext.ts b/src/contexts/GitSettingsContext.ts index cfd0c367..4f36747f 100644 --- a/src/contexts/GitSettingsContext.ts +++ b/src/contexts/GitSettingsContext.ts @@ -30,6 +30,7 @@ export interface GitSettingsContextType { removeHostToken: (host: string) => void; updateHostToken: (host: string, token: Partial) => void; isConfigured: boolean; + isInitialized: boolean; } export const GitSettingsContext = createContext(undefined); \ No newline at end of file diff --git a/src/hooks/useGitHubOAuth.test.ts b/src/hooks/useGitHubOAuth.test.ts deleted file mode 100644 index 596e686f..00000000 --- a/src/hooks/useGitHubOAuth.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { renderHook, act } from '@testing-library/react'; -import { createElement } from 'react'; -import { useGitHubOAuth } from './useGitHubOAuth'; -import { TestApp } from '@/test/TestApp'; -import { AppProvider } from '@/components/AppProvider'; -import type { AppConfig } from '@/contexts/AppContext'; - -// Mock environment variables for testing -vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_ID', '********************'); -vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_SECRET', '****************************************'); - -// Wrapper component to provide AppContext -function Wrapper({ children }: { children: React.ReactNode }) { - const defaultConfig: AppConfig = { - theme: 'light', - relayUrl: 'wss://relay.test', - projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git', - deployServer: 'test.com', - esmUrl: 'https://esm.test', - corsProxy: 'https://proxy.shakespeare.diy/?url={href}', - previewDomain: 'local-test.dev', - showcaseEnabled: true, - showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', - ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], - }; - - return createElement( - TestApp, - null, - createElement( - AppProvider, - { storageKey: 'test-app-config', defaultConfig, children } - ) - ); -} - -// Mock crypto.subtle for PKCE testing -const mockCryptoSubtle = { - digest: vi.fn(), -}; - -const mockCrypto = { - getRandomValues: vi.fn(), - randomUUID: vi.fn(), - subtle: mockCryptoSubtle, -}; - -Object.defineProperty(global, 'crypto', { - value: mockCrypto, - writable: true, -}); - -// Mock btoa for base64 encoding -global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64')); - -describe('useGitHubOAuth PKCE', () => { - beforeEach(() => { - vi.clearAllMocks(); - localStorage.clear(); - - // Setup crypto mocks - mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => { - // Fill with predictable values for testing - for (let i = 0; i < array.length; i++) { - array[i] = i % 256; - } - return array; - }); - - mockCrypto.randomUUID.mockReturnValue('test-state-uuid'); - - // Mock SHA-256 digest to return predictable hash - mockCryptoSubtle.digest.mockResolvedValue( - new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]) - ); - }); - - afterEach(() => { - localStorage.clear(); - }); - - it('should validate state parameter in callback', async () => { - // Setup stored state - localStorage.setItem('github_oauth_state', 'correct-state'); - localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); - - const { result } = renderHook(() => useGitHubOAuth(), { - wrapper: Wrapper, - }); - - // Mock fetch for token exchange and user info (using proxy URLs) - const mockFetch = vi.fn() - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ access_token: 'test-token' }), - }) - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ login: 'testuser' }), - }); - - global.fetch = mockFetch; - - let success: boolean | undefined; - await act(async () => { - success = await result.current.handleCallback('test-code', 'correct-state'); - }); - - expect(success).toBe(true); - expect(localStorage.getItem('github_oauth_state')).toBeNull(); - expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull(); - }); - - it('should reject invalid state parameter', async () => { - localStorage.setItem('github_oauth_state', 'correct-state'); - localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); - - const { result } = renderHook(() => useGitHubOAuth(), { - wrapper: Wrapper, - }); - - let success: boolean | undefined; - await act(async () => { - success = await result.current.handleCallback('test-code', 'wrong-state'); - }); - - expect(success).toBe(false); - expect(result.current.error).toBe('Invalid OAuth state parameter'); - // Should clean up on error - expect(localStorage.getItem('github_oauth_state')).toBeNull(); - expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull(); - }); - - it('should reject missing code verifier', async () => { - localStorage.setItem('github_oauth_state', 'correct-state'); - // Don't set code verifier - - const { result } = renderHook(() => useGitHubOAuth(), { - wrapper: Wrapper, - }); - - let success: boolean | undefined; - await act(async () => { - success = await result.current.handleCallback('test-code', 'correct-state'); - }); - - expect(success).toBe(false); - expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.'); - }); - - it('should include code_verifier in token request', async () => { - localStorage.setItem('github_oauth_state', 'correct-state'); - localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); - - const { result } = renderHook(() => useGitHubOAuth(), { - wrapper: Wrapper, - }); - - const mockFetch = vi.fn() - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ access_token: 'test-token' }), - }) - .mockResolvedValueOnce({ - ok: true, - json: () => Promise.resolve({ login: 'testuser' }), - }); - - global.fetch = mockFetch; - - await act(async () => { - await result.current.handleCallback('test-code', 'correct-state'); - }); - - // Check that the token request includes the code verifier - expect(mockFetch).toHaveBeenCalledWith( - 'https://proxy.shakespeare.diy/?url=https%3A%2F%2Fgithub.com%2Flogin%2Foauth%2Faccess_token', - expect.objectContaining({ - method: 'POST', - body: expect.stringContaining('"code_verifier":"test-verifier"'), - }) - ); - }); -}); \ No newline at end of file diff --git a/src/hooks/useGitHubOAuth.ts b/src/hooks/useGitHubOAuth.ts index 49a4009b..59287f9e 100644 --- a/src/hooks/useGitHubOAuth.ts +++ b/src/hooks/useGitHubOAuth.ts @@ -18,7 +18,7 @@ interface GitHubUserInfo { * Uses the generic useOAuth hook with GitHub-specific configuration. */ export function useGitHubOAuth() { - const { addCredential, addHostToken } = useGitSettings(); + const { addCredential, addHostToken, isInitialized } = useGitSettings(); // GitHub OAuth configuration const config: OAuthConfig = { @@ -60,6 +60,11 @@ export function useGitHubOAuth() { code: string, state: string ): Promise => { + // Wait for settings to be initialized before processing + if (!isInitialized) { + return false; + } + const result: OAuthResult | null = await oauth.handleCallback(code, state); if (!result) { @@ -82,7 +87,7 @@ export function useGitHubOAuth() { addHostToken('github.com', hostToken); return true; - }, [oauth, addCredential, addHostToken]); + }, [oauth, addCredential, addHostToken, isInitialized]); return { ...oauth, diff --git a/src/hooks/useNetlifyOAuth.ts b/src/hooks/useNetlifyOAuth.ts index 3b548ef8..44719e0b 100644 --- a/src/hooks/useNetlifyOAuth.ts +++ b/src/hooks/useNetlifyOAuth.ts @@ -17,7 +17,7 @@ interface NetlifyUserInfo { * Uses the generic useOAuth hook with Netlify-specific configuration. */ export function useNetlifyOAuth() { - const { setProviders, settings } = useDeploySettings(); + const { setProviders, settings, isInitialized } = useDeploySettings(); // Netlify OAuth configuration const config: OAuthConfig = { @@ -58,6 +58,11 @@ export function useNetlifyOAuth() { code: string, state: string ): Promise => { + // Wait for settings to be initialized before processing + if (!isInitialized) { + return false; + } + const result: OAuthResult | null = await oauth.handleCallback(code, state); if (!result) { @@ -78,7 +83,7 @@ export function useNetlifyOAuth() { setProviders([...settings.providers, newProvider]); return true; - }, [oauth, setProviders, settings.providers]); + }, [oauth, setProviders, settings.providers, isInitialized]); return { ...oauth, diff --git a/src/hooks/useVercelOAuth.ts b/src/hooks/useVercelOAuth.ts index 059f1e60..b16f15ee 100644 --- a/src/hooks/useVercelOAuth.ts +++ b/src/hooks/useVercelOAuth.ts @@ -21,7 +21,7 @@ interface VercelUserInfo { * Uses the generic useOAuth hook with Vercel-specific configuration. */ export function useVercelOAuth() { - const { setProviders, settings } = useDeploySettings(); + const { setProviders, settings, isInitialized } = useDeploySettings(); // Vercel OAuth configuration const config: OAuthConfig = { @@ -62,6 +62,11 @@ export function useVercelOAuth() { code: string, state: string ): Promise => { + // Wait for settings to be initialized before processing + if (!isInitialized) { + return false; + } + const result: OAuthResult | null = await oauth.handleCallback(code, state); if (!result) { @@ -82,7 +87,7 @@ export function useVercelOAuth() { setProviders([...settings.providers, newProvider]); return true; - }, [oauth, setProviders, settings.providers]); + }, [oauth, setProviders, settings.providers, isInitialized]); return { ...oauth, diff --git a/src/pages/GitHubOAuth.tsx b/src/pages/GitHubOAuth.tsx index 1082d935..d9ddddf3 100644 --- a/src/pages/GitHubOAuth.tsx +++ b/src/pages/GitHubOAuth.tsx @@ -1,6 +1,7 @@ import { useEffect } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; +import { useGitSettings } from '@/hooks/useGitSettings'; import { useToast } from '@/hooks/useToast'; import { Card, CardContent } from '@/components/ui/card'; import { Github } from 'lucide-react'; @@ -9,9 +10,15 @@ export default function GitHubOAuth() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const { handleCallback } = useGitHubOAuth(); + const { isInitialized } = useGitSettings(); const { toast } = useToast(); useEffect(() => { + // Wait for git settings to be initialized + if (!isInitialized) { + return; + } + const code = searchParams.get('code'); const state = searchParams.get('state'); const error = searchParams.get('error'); @@ -63,7 +70,7 @@ export default function GitHubOAuth() { // No code or state parameters - redirect to Git settings navigate('/settings/git'); } - }, [searchParams, handleCallback, toast, navigate]); + }, [searchParams, handleCallback, toast, navigate, isInitialized]); return (
diff --git a/src/pages/NetlifyOAuth.tsx b/src/pages/NetlifyOAuth.tsx index b114a0ab..d4f5d6ed 100644 --- a/src/pages/NetlifyOAuth.tsx +++ b/src/pages/NetlifyOAuth.tsx @@ -1,6 +1,7 @@ import { useEffect } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth'; +import { useDeploySettings } from '@/hooks/useDeploySettings'; import { useToast } from '@/hooks/useToast'; import { Card, CardContent } from '@/components/ui/card'; @@ -8,9 +9,15 @@ export default function NetlifyOAuth() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const { handleCallback } = useNetlifyOAuth(); + const { isInitialized } = useDeploySettings(); const { toast } = useToast(); useEffect(() => { + // Wait for deploy settings to be initialized + if (!isInitialized) { + return; + } + const code = searchParams.get('code'); const state = searchParams.get('state'); const error = searchParams.get('error'); @@ -50,7 +57,7 @@ export default function NetlifyOAuth() { // No code or state parameters - redirect to Deploy settings navigate('/settings/deploy'); } - }, [searchParams, handleCallback, toast, navigate]); + }, [searchParams, handleCallback, toast, navigate, isInitialized]); return (
diff --git a/src/pages/VercelOAuth.tsx b/src/pages/VercelOAuth.tsx index bfd1a437..3a3cb2c5 100644 --- a/src/pages/VercelOAuth.tsx +++ b/src/pages/VercelOAuth.tsx @@ -1,6 +1,7 @@ import { useEffect } from 'react'; import { useSearchParams, useNavigate } from 'react-router-dom'; import { useVercelOAuth } from '@/hooks/useVercelOAuth'; +import { useDeploySettings } from '@/hooks/useDeploySettings'; import { useToast } from '@/hooks/useToast'; import { Card, CardContent } from '@/components/ui/card'; @@ -8,9 +9,15 @@ export default function VercelOAuth() { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const { handleCallback } = useVercelOAuth(); + const { isInitialized } = useDeploySettings(); const { toast } = useToast(); useEffect(() => { + // Wait for deploy settings to be initialized + if (!isInitialized) { + return; + } + const code = searchParams.get('code'); const state = searchParams.get('state'); const error = searchParams.get('error'); @@ -50,7 +57,7 @@ export default function VercelOAuth() { // No code or state parameters - redirect to Deploy settings navigate('/settings/deploy'); } - }, [searchParams, handleCallback, toast, navigate]); + }, [searchParams, handleCallback, toast, navigate, isInitialized]); return (