diff --git a/eslint.config.js b/eslint.config.js index a91a13c6..1e1fc7fd 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -27,6 +27,7 @@ export default tseslint.config( }, rules: { ...reactHooks.configs.recommended.rules, + "react-hooks/exhaustive-deps": "error", "react-refresh/only-export-components": [ "warn", { allowConstantExport: true }, diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index 5a17280c..f30b2c96 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -8,12 +8,12 @@ "theme_color": "#000000", "icons": [ { - "src": "/icon-192.png", + "src": "/favicon.png", "sizes": "192x192", "type": "image/png" }, { - "src": "/icon-512.png", + "src": "/favicon.png", "sizes": "512x512", "type": "image/png" } diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 256f788d..a328926f 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -8,6 +8,7 @@ import Settings from "./pages/Settings"; import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; import DataSettings from "./pages/DataSettings"; +import GitHubOAuth from "./pages/GitHubOAuth"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; import { ProjectView } from "./pages/ProjectView"; @@ -21,6 +22,7 @@ export function AppRouter() { } /> } /> + } /> }> } /> } /> diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx index 223b777c..afc4b3ee 100644 --- a/src/components/AppLayout.tsx +++ b/src/components/AppLayout.tsx @@ -4,7 +4,7 @@ import { type Project } from '@/lib/ProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { Button } from '@/components/ui/button'; -import { Menu, Columns2 } from 'lucide-react'; +import { Menu } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface AppLayoutProps { @@ -129,6 +129,7 @@ export function AppLayout({ selectedProject={selectedProject} onSelectProject={handleProjectSelect} className="h-screen sticky top-0" + onToggleSidebar={() => setIsSidebarVisible(false)} /> )} @@ -136,16 +137,16 @@ export function AppLayout({ {/* Main Content Area */}
- {/* Toggle Button - positioned absolutely in top-left corner */} - {showSidebar && ( + {/* Show open button when sidebar is collapsed */} + {showSidebar && !isSidebarVisible && ( )} diff --git a/src/components/ProjectSidebar.test.tsx b/src/components/ProjectSidebar.test.tsx new file mode 100644 index 00000000..be2ff20f --- /dev/null +++ b/src/components/ProjectSidebar.test.tsx @@ -0,0 +1,105 @@ +import { render, screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { ProjectSidebar } from './ProjectSidebar'; +import { useProjects } from '@/hooks/useProjects'; +import { useLocalStorage } from '@/hooks/useLocalStorage'; + +// Mock the hooks +vi.mock('@/hooks/useProjects'); +vi.mock('@/hooks/useLocalStorage'); +vi.mock('@/hooks/useProjectSessionStatus', () => ({ + useProjectSessionStatus: () => ({ hasRunningSessions: false }) +})); +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); +vi.mock('@tanstack/react-query', () => ({ + useQueryClient: () => ({ + invalidateQueries: vi.fn() + }) +})); + +// Mock the LoginArea component +vi.mock('@/components/auth/LoginArea', () => ({ + LoginArea: ({ className }: { className?: string }) => ( +
Login Area
+ ) +})); + +const mockUseProjects = vi.mocked(useProjects); +const mockUseLocalStorage = vi.mocked(useLocalStorage); + +describe('ProjectSidebar', () => { + beforeEach(() => { + mockUseProjects.mockReturnValue({ + data: [], + isLoading: false, + error: null + } as unknown as ReturnType); + + mockUseLocalStorage.mockReturnValue([[], vi.fn()]); + }); + + it('renders sidebar header with logo', () => { + render( + + ); + + expect(screen.getByText('🎭')).toBeInTheDocument(); + expect(screen.getByText('Shakespeare')).toBeInTheDocument(); + }); + + it('shows collapse button when onToggleSidebar is provided', () => { + const mockToggle = vi.fn(); + + render( + + ); + + const collapseButton = screen.getByLabelText('Collapse sidebar'); + expect(collapseButton).toBeInTheDocument(); + + fireEvent.click(collapseButton); + expect(mockToggle).toHaveBeenCalledTimes(1); + }); + + it('does not show collapse button when onToggleSidebar is not provided', () => { + render( + + ); + + expect(screen.queryByLabelText('Collapse sidebar')).not.toBeInTheDocument(); + }); + + it('renders login area at the bottom', () => { + render( + + ); + + expect(screen.getByTestId('login-area')).toBeInTheDocument(); + }); + + it('shows new project button', () => { + render( + + ); + + expect(screen.getByText('New Project')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 3c4c3dd1..0b8b62c6 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,6 +1,6 @@ import React, { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -76,12 +76,14 @@ interface ProjectSidebarProps { selectedProject: Project | null; onSelectProject: (project: Project | null) => void; className?: string; + onToggleSidebar?: () => void; } export function ProjectSidebar({ selectedProject, onSelectProject, - className + className, + onToggleSidebar }: ProjectSidebarProps) { const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); @@ -116,16 +118,19 @@ export function ProjectSidebar({ Shakespeare -
- -
+ {onToggleSidebar && ( +
+ +
+ )}
diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index fae67aac..2321e773 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'; import { useNavigate, useLocation, Outlet } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -61,7 +61,7 @@ export function SettingsLayout() { // Set initial sidebar state based on projects and device type if (!hasSetInitialState && !isMobile) { // On desktop, show sidebar if there are projects - setIsSidebarVisible(projectList.length > 0); + setIsSidebarVisible(true); setHasSetInitialState(true); } else if (!hasSetInitialState && isMobile) { // On mobile, always start hidden @@ -145,6 +145,7 @@ export function SettingsLayout() { selectedProject={null} onSelectProject={handleProjectSelect} className="h-full" + onToggleSidebar={() => setIsSidebarVisible(false)} /> )} @@ -154,15 +155,17 @@ export function SettingsLayout() { {/* Header with toggle button */}
- + {!isSidebarVisible && ( + + )}

Settings

diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index f6bbcbae..342a8cb8 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -298,18 +298,6 @@ export const ChatPane = forwardRef(({ } }, [projectId, scrolledProjects]); - // Also scroll on initial mount if we have a projectId - useEffect(() => { - if (projectId && !scrolledProjects.has(projectId)) { - const timer = setTimeout(() => { - scrollToBottom(); - scrolledProjects.add(projectId); - }, 100); - - return () => clearTimeout(timer); - } - }, []); // Empty dependency array = runs on mount - const handleFileSelect = (file: File) => { setAttachedFiles(prev => [...prev, file]); }; diff --git a/src/components/Shakespeare/FileTree.tsx b/src/components/Shakespeare/FileTree.tsx index 0cb506ee..c88c949f 100644 --- a/src/components/Shakespeare/FileTree.tsx +++ b/src/components/Shakespeare/FileTree.tsx @@ -2,9 +2,10 @@ import { useState, useEffect, useCallback } from 'react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; import { useGitStatus } from '@/hooks/useGitStatus'; -import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react'; +import { ChevronRight, ChevronDown, File, Folder, Search } from 'lucide-react'; import { cn } from '@/lib/utils'; import { createGitignoreFilter, normalizePathForGitignore } from '@/lib/gitignore'; +import { Input } from '@/components/ui/input'; interface FileTreeProps { projectId: string; @@ -22,11 +23,14 @@ interface FileNode { export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) { const [tree, setTree] = useState([]); + const [filteredTree, setFilteredTree] = useState([]); const [isLoading, setIsLoading] = useState(true); const [gitignoreFilter, setGitignoreFilter] = useState<{ isIgnored: (path: string) => boolean; shouldShow: (path: string) => boolean; } | null>(null); + const [searchTerm, setSearchTerm] = useState(''); + const [isSearching, setIsSearching] = useState(false); const { fs } = useFS(); const projectsManager = useProjectsManager(); const { data: gitStatus } = useGitStatus(projectId); @@ -127,6 +131,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp const structure = await buildFileTree(projectId, ''); setTree(structure); + setFilteredTree(structure); } catch (_error) { console.error('Failed to load file tree:', _error); } finally { @@ -151,7 +156,9 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp }); }; + // Update both the original tree and filtered tree setTree(prev => toggleNode(prev)); + setFilteredTree(prev => toggleNode(prev)); }; const handleFileClick = (filePath: string, type: 'file' | 'directory') => { @@ -162,6 +169,58 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp } }; + // Search functions + const searchInFiles = useCallback(async (nodes: FileNode[], term: string): Promise => { + if (!term.trim()) return nodes; + + const results: FileNode[] = []; + const searchTermLower = term.toLowerCase(); + + for (const node of nodes) { + if (node.type === 'file') { + const fileNameMatch = node.name.toLowerCase().includes(searchTermLower); + + if (fileNameMatch) { + results.push(node); + } + } else if (node.type === 'directory' && node.children) { + const childResults = await searchInFiles(node.children, term); + if (childResults.length > 0) { + // Create a filtered directory node with matching children + results.push({ + ...node, + children: childResults, + isOpen: true, // Auto-expand directories with matches + }); + } + } + } + + return results }, []); + + // Perform search when search term changes + useEffect(() => { + const performSearch = async () => { + if (!searchTerm.trim()) { + setFilteredTree(tree); + return; + } + + setIsSearching(true); + try { + const results = await searchInFiles(tree, searchTerm); + setFilteredTree(results); + } catch (error) { + console.error('Search failed:', error); + setFilteredTree([]); + } finally { + setIsSearching(false); + } + }; + + performSearch(); + }, [searchTerm, tree, searchInFiles]); + const renderNode = (node: FileNode, depth: number = 0) => { const isSelected = selectedFile === node.path; @@ -232,12 +291,32 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp return (
- {tree.length === 0 ? ( -
- No files found + {/* Search Section */} +
+
+ + setSearchTerm(e.target.value)} + className="pl-8" + /> +
+
+ + {/* File Tree */} + {isSearching ? ( +
+ {[...Array(3)].map((_, i) => ( +
+ ))} +
+ ) : filteredTree.length === 0 ? ( +
+ {searchTerm ? 'No files found matching your search' : 'No files found'}
) : ( - tree.map(node => renderNode(node)) + filteredTree.map(node => renderNode(node)) )}
); diff --git a/src/components/auth/AccountSwitcher.test.tsx b/src/components/auth/AccountSwitcher.test.tsx new file mode 100644 index 00000000..e503b526 --- /dev/null +++ b/src/components/auth/AccountSwitcher.test.tsx @@ -0,0 +1,63 @@ +import { render, screen } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { AccountSwitcher } from './AccountSwitcher'; +import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; + +// Mock the hooks +vi.mock('@/hooks/useLoggedInAccounts'); +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); + +// Mock the RelaySelector component +vi.mock('@/components/RelaySelector', () => ({ + RelaySelector: ({ className }: { className?: string }) => ( +
Relay Selector
+ ) +})); + +const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts); + +describe('AccountSwitcher', () => { + it('renders account switcher with dropdown trigger', () => { + mockUseLoggedInAccounts.mockReturnValue({ + authors: [{ + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }], + currentUser: { + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + render(); + + // Should show the user's name + expect(screen.getByText('Test User')).toBeInTheDocument(); + + // Should show dropdown trigger button + expect(screen.getByRole('button')).toBeInTheDocument(); + }); + + + + it('returns null when no current user', () => { + mockUseLoggedInAccounts.mockReturnValue({ + authors: [], + currentUser: undefined, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + const { container } = render(); + + expect(container.firstChild).toBeNull(); + }); +}); \ No newline at end of file diff --git a/src/components/auth/AccountSwitcher.tsx b/src/components/auth/AccountSwitcher.tsx index cc22c368..3a5b9901 100644 --- a/src/components/auth/AccountSwitcher.tsx +++ b/src/components/auth/AccountSwitcher.tsx @@ -1,7 +1,7 @@ // NOTE: This file is stable and usually should not be modified. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. -import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react'; +import { ChevronDown, LogOut, UserIcon, UserPlus, Settings, HelpCircle } from 'lucide-react'; import { DropdownMenu, DropdownMenuContent, @@ -13,6 +13,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx' import { RelaySelector } from '@/components/RelaySelector'; import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; import { genUserName } from '@/lib/genUserName'; +import { useNavigate } from 'react-router-dom'; interface AccountSwitcherProps { onAddAccountClick: () => void; @@ -20,6 +21,7 @@ interface AccountSwitcherProps { export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) { const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts(); + const navigate = useNavigate(); if (!currentUser) return null; @@ -63,6 +65,20 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) { ))} + navigate('/settings')} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Settings + + window.open('https://soapbox.pub/shakespeare-resources/', '_blank')} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Help + ({ + useAppContext: () => ({ + config: { relayUrl: 'wss://relay.damus.io' }, + updateConfig: vi.fn(), + presetRelays: [ + { name: 'Damus', url: 'wss://relay.damus.io' } + ] + }) +})); + +// Mock the components +vi.mock('./AccountSwitcher', () => ({ + AccountSwitcher: ({ onAddAccountClick }: { onAddAccountClick: () => void }) => ( +
+ +
+ ) +})); + +// Mock react-router-dom +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); + +vi.mock('@/components/RelaySelector', () => ({ + RelaySelector: ({ className }: { className?: string }) => ( +
Relay Selector
+ ) +})); + +vi.mock('./LoginDialog', () => ({ + default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) => + isOpen ?
Login Dialog
: null +})); + +vi.mock('./SignupDialog', () => ({ + default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) => + isOpen ?
Signup Dialog
: null +})); + +const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts); + +describe('LoginArea', () => { + it('shows AccountSwitcher when user is logged in', () => { + mockUseLoggedInAccounts.mockReturnValue({ + authors: [{ + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }], + currentUser: { + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + render(); + + expect(screen.getByTestId('account-switcher')).toBeInTheDocument(); + }); + + it('shows anonymous user menu when user is not logged in', () => { + mockUseLoggedInAccounts.mockReturnValue({ + authors: [], + currentUser: undefined, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + render(); + + // Should show anonymous user display + expect(screen.getByText('Anonymous')).toBeInTheDocument(); + + // Should show the dropdown trigger button + expect(screen.getByRole('button')).toBeInTheDocument(); + }); + + + + it('maintains consistent layout structure whether logged in or not', () => { + // Test logged out state + mockUseLoggedInAccounts.mockReturnValue({ + authors: [], + currentUser: undefined, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + const { rerender } = render(); + + const loggedOutContainer = screen.getByRole('button'); + expect(loggedOutContainer).toHaveClass('flex', 'items-center', 'gap-3', 'p-3', 'rounded-full'); + + // Test logged in state + mockUseLoggedInAccounts.mockReturnValue({ + authors: [{ + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }], + currentUser: { + id: 'user1', + pubkey: 'pubkey1', + metadata: { name: 'Test User' } + }, + otherUsers: [], + setLogin: vi.fn(), + removeLogin: vi.fn() + }); + + rerender(); + + // Both states should maintain similar structure + expect(screen.getByTestId('account-switcher')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index f84414a4..e13d2d45 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -2,13 +2,22 @@ // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. import { useState } from 'react'; -import { User, UserPlus } from 'lucide-react'; -import { Button } from '@/components/ui/button.tsx'; +import { User, UserPlus, ChevronDown, Settings, HelpCircle } from 'lucide-react'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu.tsx'; +import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx'; +import { RelaySelector } from '@/components/RelaySelector'; import LoginDialog from './LoginDialog'; import SignupDialog from './SignupDialog'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { AccountSwitcher } from './AccountSwitcher'; import { cn } from '@/lib/utils'; +import { useNavigate } from 'react-router-dom'; export interface LoginAreaProps { className?: string; @@ -16,6 +25,7 @@ export interface LoginAreaProps { export function LoginArea({ className }: LoginAreaProps) { const { currentUser } = useLoggedInAccounts(); + const navigate = useNavigate(); const [loginDialogOpen, setLoginDialogOpen] = useState(false); const [signupDialogOpen, setSignupDialogOpen] = useState(false); @@ -29,22 +39,55 @@ export function LoginArea({ className }: LoginAreaProps) { {currentUser ? ( setLoginDialogOpen(true)} /> ) : ( -
- -
+ + + + + +
Switch Relay
+ + + navigate('/settings')} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Settings + + window.open('https://soapbox.pub/shakespeare-resources/', '_blank')} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Help + + + setLoginDialogOpen(true)} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Log in + + setSignupDialogOpen(true)} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + Sign up + +
+
)} 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: TestApp, + }); + + // Mock fetch for token exchange and user info + 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: TestApp, + }); + + 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: TestApp, + }); + + 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: TestApp, + }); + + 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( + expect.stringContaining('github.com/login/oauth/access_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 4fae32b1..0b64aa80 100644 --- a/src/hooks/useGitHubOAuth.ts +++ b/src/hooks/useGitHubOAuth.ts @@ -25,7 +25,28 @@ export function useGitHubOAuth() { import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET ); - const initiateOAuth = useCallback(() => { + // 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 => { + 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) { @@ -33,19 +54,36 @@ export function useGitHubOAuth() { return; } - // Generate a random state parameter for security - const state = crypto.randomUUID(); - localStorage.setItem('github_oauth_state', state); + try { + // Generate PKCE parameters + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); - // Redirect to GitHub OAuth - const params = new URLSearchParams({ - client_id: clientId, - redirect_uri: window.location.origin + '/', - scope: 'repo', - state: state, - }); + // Generate a random state parameter for security + const state = crypto.randomUUID(); - window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`; + // 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', + 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) => { @@ -58,8 +96,15 @@ export function useGitHubOAuth() { throw new Error('Invalid OAuth state parameter'); } - // Clean up stored state + // 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; @@ -68,18 +113,22 @@ export function useGitHubOAuth() { throw new Error('GitHub OAuth credentials not configured'); } - // Exchange code for access token + // 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 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, - }), + body: JSON.stringify(tokenRequestBody), }); if (!tokenResponse.ok) { @@ -116,6 +165,11 @@ export function useGitHubOAuth() { return true; } catch (error) { console.error('GitHub OAuth error:', error); + + // Clean up any remaining OAuth data on error + localStorage.removeItem('github_oauth_state'); + localStorage.removeItem('github_oauth_code_verifier'); + setState(prev => ({ ...prev, isLoading: false, diff --git a/src/pages/GitHubOAuth.tsx b/src/pages/GitHubOAuth.tsx new file mode 100644 index 00000000..1082d935 --- /dev/null +++ b/src/pages/GitHubOAuth.tsx @@ -0,0 +1,90 @@ +import { useEffect } from 'react'; +import { useSearchParams, useNavigate } from 'react-router-dom'; +import { useGitHubOAuth } from '@/hooks/useGitHubOAuth'; +import { useToast } from '@/hooks/useToast'; +import { Card, CardContent } from '@/components/ui/card'; +import { Github } from 'lucide-react'; + +export default function GitHubOAuth() { + const [searchParams] = useSearchParams(); + const navigate = useNavigate(); + const { handleCallback } = useGitHubOAuth(); + 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('github_oauth_state'); + const storedCodeVerifier = localStorage.getItem('github_oauth_code_verifier'); + + // Handle OAuth errors + if (error) { + toast({ + title: "GitHub OAuth Error", + description: errorDescription || error, + variant: "destructive", + }); + navigate('/settings/git'); + return; + } + + // Handle successful OAuth callback + if (code && state && storedState && storedCodeVerifier) { + handleCallback(code, state).then((success) => { + if (success) { + toast({ + title: "GitHub Connected", + description: "Successfully connected to GitHub. You can now push and pull from GitHub repositories.", + }); + } else { + toast({ + title: "Connection Failed", + description: "Failed to connect to GitHub. Please try again.", + variant: "destructive", + }); + } + // Always redirect to Git settings after handling the callback + navigate('/settings/git'); + }); + } else if (code && state && storedState && !storedCodeVerifier) { + // Missing code verifier - likely an incomplete PKCE flow + toast({ + title: "Authentication Error", + description: "OAuth flow is incomplete. Please try connecting to GitHub again.", + variant: "destructive", + }); + // Clean up any remaining OAuth data + localStorage.removeItem('github_oauth_state'); + localStorage.removeItem('github_oauth_code_verifier'); + navigate('/settings/git'); + } else { + // No code or state parameters - redirect to Git settings + navigate('/settings/git'); + } + }, [searchParams, handleCallback, toast, navigate]); + + return ( +
+ + +
+
+ +
+
+

Connecting to GitHub

+

+ Processing your GitHub authentication... +

+
+
+
+
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/pages/GitSettings.tsx b/src/pages/GitSettings.tsx index 9c009aa9..a306ce50 100644 --- a/src/pages/GitSettings.tsx +++ b/src/pages/GitSettings.tsx @@ -236,7 +236,7 @@ export function GitSettings() { diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index fd84394f..0d248d97 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -1,13 +1,11 @@ import { useState, useEffect } from 'react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; +import { useNavigate } 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'; @@ -24,14 +22,11 @@ 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] || ''; @@ -51,27 +46,6 @@ 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/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 54b59ad9..6a1db21f 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -9,7 +9,7 @@ import { ProjectInfoDialog } from '@/components/ProjectInfoDialog'; import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; -import { ArrowLeft, MessageSquare, Eye, Code, Menu, Columns2 } from 'lucide-react'; +import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; import { ActionsMenu } from '@/components/ActionsMenu'; @@ -371,6 +371,7 @@ export function ProjectView() { navigate('/'); } }} + onToggleSidebar={() => setIsSidebarVisible(!isSidebarVisible)} className="h-full" />
@@ -385,32 +386,34 @@ export function ProjectView() { {/* Chat Header */}
- {/* Left side - Sidebar toggle */} -
- -
- - {/* Center - Project title */} -
- {project ? ( + {/* Left side - Sidebar toggle (when collapsed) */} +
+ {!isSidebarVisible && ( - ) : ( - )} + + {/* Project title */} +
+ {project ? ( + + ) : ( + + )} +
{/* Right side - Star and Actions Menu */}