diff --git a/AGENTS.md b/AGENTS.md index 6d787bd4..d4cf2f37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,6 +168,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog) - `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection) - `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane) + - `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options + - `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files - Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration @@ -182,7 +184,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `useSessionManager`: Access session management for AI chat sessions - `useGitStatus`: Real-time Git repository status monitoring - `useProjects`: Project management and CRUD operations - - `useProjectsManager`: Advanced project operations (creation, cloning, building) + - `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import) - `useTheme`: Theme management - `useToast`: Toast notifications - `useLocalStorage`: Persistent local storage diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index a99d2c7d..3d6782a0 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ -import React, { useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } 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'; @@ -9,6 +9,9 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { ZipImportDialog } from '@/components/ZipImportDialog'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useToast } from '@/hooks/useToast'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; @@ -92,6 +95,9 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); + const projectsManager = useProjectsManager(); + const { toast } = useToast(); + const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -117,6 +123,25 @@ export function ProjectSidebar({ } }; + const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { + try { + // Import project from zip file + const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); + + // Show success toast + toast({ + title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", + description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, + }); + + // Navigate to the imported project + navigate(`/project/${project.id}`); + } catch (error) { + console.error('Failed to import project:', error); + throw error; // Re-throw to let the dialog handle the error display + } + }; + useEffect(() => { queryClient.invalidateQueries({ queryKey: ['projects'] }); }, [favorites, queryClient]); @@ -186,6 +211,13 @@ export function ProjectSidebar({ {t('importRepository')} + setIsZipDialogOpen(true)} + className="flex items-center gap-2 w-full" + > + + Import ZIP File + @@ -248,6 +280,13 @@ export function ProjectSidebar({ + + {/* ZIP Import Dialog */} + ); } \ No newline at end of file diff --git a/src/components/ZipImportDialog.test.tsx b/src/components/ZipImportDialog.test.tsx new file mode 100644 index 00000000..19ecadbe --- /dev/null +++ b/src/components/ZipImportDialog.test.tsx @@ -0,0 +1,203 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ZipImportDialog } from './ZipImportDialog'; +import { TestApp } from '@/test/TestApp'; + +// Mock the useProjects hook +const mockProjects = [ + { id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() } +]; + +vi.mock('@/hooks/useProjects', () => ({ + useProjects: () => ({ + data: mockProjects, + isLoading: false, + error: null + }) +})); + +describe('ZipImportDialog', () => { + const mockOnImport = vi.fn(); + const defaultProps = { + onImport: mockOnImport, + disabled: false + }; + + beforeEach(() => { + mockOnImport.mockClear(); + vi.clearAllMocks(); + }); + + it('renders dialog trigger button', () => { + render( + + + + ); + + expect(screen.getByText('Import ZIP')).toBeInTheDocument(); + }); + + it('opens dialog when trigger is clicked', async () => { + render( + + + + ); + + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + await waitFor(() => { + expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument(); + }); + }); + + it('processes file selection without displaying project ID', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file + const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + await waitFor(() => { + // Verify that the file name is displayed (from the file selection area) + expect(screen.getByText('my-project.zip')).toBeInTheDocument(); + // Verify that Project ID label is not displayed + expect(screen.queryByText('Project ID')).not.toBeInTheDocument(); + }); + }); + + it('shows overwrite warning when project ID already exists', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file that will generate an existing project ID + const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + await waitFor(() => { + expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument(); + expect(screen.getByText('Overwrite Project')).toBeInTheDocument(); + }); + }); + + it('calls onImport with correct parameters when import button is clicked', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file + const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + // Wait for file to be processed + await waitFor(() => { + expect(screen.getByText('new-project.zip')).toBeInTheDocument(); + }); + + // Click import button + const importButton = screen.getByText('Import Project'); + fireEvent.click(importButton); + + await waitFor(() => { + expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project"); + }); + }); + + it('shows overwrite confirmation dialog when overwrite button is clicked', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file that will generate an existing project ID + const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + // Wait for overwrite button to appear + await waitFor(() => { + expect(screen.getByText('Overwrite Project')).toBeInTheDocument(); + }); + + // Click overwrite button + const overwriteButton = screen.getByText('Overwrite Project'); + fireEvent.click(overwriteButton); + + // Check for overwrite confirmation dialog + await waitFor(() => { + expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument(); + // Use a more flexible matcher for the text that might be split across elements + const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent'); + if (dialogContent) { + expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists'); + } + }, { timeout: 2000 }); + }); + + it('does not show project ID input field (simplified interface)', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Check that there's no input field for project ID + expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument(); + expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/ZipImportDialog.tsx b/src/components/ZipImportDialog.tsx new file mode 100644 index 00000000..6cfe40f2 --- /dev/null +++ b/src/components/ZipImportDialog.tsx @@ -0,0 +1,397 @@ +import React, { useState, useRef, useCallback, useEffect } from 'react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Progress } from '@/components/ui/progress'; +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; +import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react'; +import { useProjects } from '@/hooks/useProjects'; +import { cn } from '@/lib/utils'; + +interface ZipImportDialogProps { + onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise; + disabled?: boolean; + className?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) { + // Use controlled state if props are provided, otherwise use internal state + const [internalIsOpen, setInternalIsOpen] = useState(false); + const isOpen = open !== undefined ? open : internalIsOpen; + const setIsOpen = onOpenChange || setInternalIsOpen; + const [selectedFile, setSelectedFile] = useState(null); + const [generatedId, setGeneratedId] = useState(''); + const [isImporting, setIsImporting] = useState(false); + const [importProgress, setImportProgress] = useState(0); + const [error, setError] = useState(null); + const [isDragOver, setIsDragOver] = useState(false); + const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null); + const [showOverwriteDialog, setShowOverwriteDialog] = useState(false); + const fileInputRef = useRef(null); + const { data: projects = [] } = useProjects(); + + const handleFileSelect = (file: File) => { + // Only accept zip files + if (!file.name.toLowerCase().endsWith('.zip')) { + setError('Please select a ZIP file'); + return; + } + + setSelectedFile(file); + setError(null); + + // Auto-generate ID from file name + const baseName = file.name.replace(/\.zip$/i, ''); + const id = baseName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + setGeneratedId(id); + }; + + // Check for existing project when generated ID changes + useEffect(() => { + if (generatedId && projects.length > 0) { + const existing = projects.find(project => project.id === generatedId); + setExistingProject(existing || null); + } else { + setExistingProject(null); + } + }, [generatedId, projects]); + + // Drag and drop handlers + const handleDragOver = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(true); + }, []); + + const handleDragLeave = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + }, []); + + const handleDrop = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleDragOverDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(true); + }, []); + + const handleDragLeaveDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + }, []); + + const handleDropDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleClickUpload = () => { + fileInputRef.current?.click(); + }; + + const handleFileRemove = () => { + setSelectedFile(null); + setGeneratedId(''); + setError(null); + }; + + const handleImport = async (overwrite = false) => { + if (!selectedFile) return; + + setIsImporting(true); + setImportProgress(0); + setError(null); + + try { + // Simulate progress for better UX + const progressInterval = setInterval(() => { + setImportProgress(prev => Math.min(prev + 10, 90)); + }, 200); + + await onImport(selectedFile, overwrite, generatedId); + + clearInterval(progressInterval); + setImportProgress(100); + + // Close dialog after a short delay + setTimeout(() => { + setIsOpen(false); + setSelectedFile(null); + setGeneratedId(''); + setImportProgress(0); + setExistingProject(null); + }, 1000); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to import project'); + setImportProgress(0); + } finally { + setIsImporting(false); + } + }; + + const handleImportWithOverwriteCheck = async () => { + if (!selectedFile || !generatedId) return; + + // Check if project with this ID already exists + try { + // This would ideally be passed as a prop or through context + // For now, we'll assume the parent will handle the check and pass existing project info + if (existingProject) { + setShowOverwriteDialog(true); + } else { + await handleImport(false); + } + } catch (error) { + console.error('Error checking existing project:', error); + await handleImport(false); + } + }; + + const confirmOverwrite = async () => { + setShowOverwriteDialog(false); + await handleImport(true); + }; + + const handleClose = () => { + if (!isImporting) { + setIsOpen(false); + setSelectedFile(null); + setGeneratedId(''); + setError(null); + setImportProgress(0); + } + }; + + // Only render DialogTrigger if this component is being used in uncontrolled mode + // (no open/onOpenChange props provided) + const isControlled = open !== undefined && onOpenChange !== undefined; + + return ( + <> + + {!isControlled && ( + + + + )} + + + + + + Import Project from ZIP + + + Upload a ZIP file containing your project source code to import it into Shakespeare. + + + +
+ {!isImporting && ( + <> + {/* Drag and Drop Area */} +
+ { + const files = e.target.files; + if (files && files.length > 0) { + handleFileSelect(files[0]); + } + }} + accept=".zip" + className="hidden" + disabled={isImporting} + /> + +
+
+ {selectedFile ? ( + + ) : ( + + )} +
+ +
+ {selectedFile ? ( +
+

+ {selectedFile.name} +

+

+ {(selectedFile.size / 1024 / 1024).toFixed(2)} MB +

+ +
+ ) : ( +
+

+ Drop your ZIP file here or click to browse +

+

+ Supports ZIP files up to 50MB +

+
+ )} +
+
+
+ + {/* Error Display */} + {error && ( +
+ + {error} +
+ )} + + {/* Overwrite Warning */} + {existingProject && ( +
+ + A project with this ID already exists. You can choose to overwrite it. +
+ )} + + {/* Import Button */} +
+ + +
+ + )} + + {/* Import Progress */} + {isImporting && ( +
+
+
+ Importing project... +
+ +

+ Extracting files and setting up project... +

+
+ )} + + {/* Success State */} + {!isImporting && importProgress === 100 && ( +
+ + + + Project imported successfully! +
+ )} +
+
+
+ + {/* Overwrite Confirmation Dialog */} + + + + + + Overwrite Existing Project + + +

+ A project with the ID "{generatedId}" already exists. + Overwriting it will: +

+
    +
  • Delete all existing files in the project
  • +
  • Replace them with files from the ZIP archive
  • +
  • Preserve Git history if it exists
  • +
  • Keep AI chat history and session data
  • +
+

+ This action cannot be undone. Are you sure you want to continue? +

+
+
+ + Cancel + + Yes, Overwrite Project + + +
+
+ + ); +} \ No newline at end of file diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 4d401518..f823c200 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -14,6 +14,27 @@ const createMockNostr = (): NPool => ({ close: vi.fn(), }) as unknown as NPool; +// Mock JSZip +vi.mock('jszip', () => ({ + default: class MockJSZip { + files: Record Uint8Array }> = {}; + + static async loadAsync(buffer: ArrayBuffer) { + const instance = new MockJSZip(); + // Add a mock file entry + instance.files['package.json'] = { + dir: false, + async: () => new Uint8Array(buffer) + }; + return instance; + } + + async file(name: string) { + return this.files[name]; + } + } +})); + // Mock filesystem for testing class MockFS implements JSRuntimeFS { private files: Map = new Map(); @@ -269,6 +290,156 @@ describe('ProjectsManager', () => { }); }); + describe('importProjectFromZip', () => { + it('should preserve original project name when overwriting', async () => { + await projectsManager.init(); + + // Create an existing project with a specific name + await fs.mkdir('/projects/my-project'); + await fs.mkdir('/projects/my-project/.git'); + await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}'); + + // Mock the git methods to simulate existing project + const mockGit = { + init: vi.fn(), + clone: vi.fn(), + add: vi.fn(), + commit: vi.fn(), + getConfig: vi.fn(), + getAllFiles: vi.fn().mockResolvedValue(['package.json']), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Create a mock ZIP file with different name + const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' }); + + // Mock arrayBuffer method + Object.defineProperty(zipFile, 'arrayBuffer', { + value: () => Promise.resolve(new TextEncoder().encode('test content').buffer), + writable: false + }); + + // Import with overwrite + const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true); + + // Should preserve original project name + expect(project.name).toBe('my-project'); + expect(project.id).toBe('my-project'); + }); + + it('should use new project name when not overwriting', async () => { + await projectsManager.init(); + + // Mock the git methods + const mockGit = { + init: vi.fn(), + clone: vi.fn(), + add: vi.fn(), + commit: vi.fn(), + getConfig: vi.fn(), + getAllFiles: vi.fn().mockResolvedValue(['package.json']), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Create a mock ZIP file + const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' }); + + // Mock arrayBuffer method + Object.defineProperty(zipFile, 'arrayBuffer', { + value: () => Promise.resolve(new TextEncoder().encode('test content').buffer), + writable: false + }); + + // Import without overwrite + const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); + + // Should use formatted name from ID + expect(project.name).toBe('new-project'); + expect(project.id).toBe('new-project'); + }); + + it('should prevent zip slip attacks during import', async () => { + await projectsManager.init(); + + // Mock the git methods + const mockGit = { + init: vi.fn(), + clone: vi.fn(), + add: vi.fn(), + commit: vi.fn(), + getConfig: vi.fn(), + getAllFiles: vi.fn().mockResolvedValue([]), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Create a mock ZIP file that would try to escape the project directory + const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' }); + + // Mock JSZip to simulate a malicious ZIP with path traversal + const JSZip = await import('jszip'); + + const mockLoadAsync = vi.fn().mockResolvedValue({ + files: { + '../../../etc/passwd': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])) + }, + '../../outside.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])) + }, + 'safe-file.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])) + } + } + }); + + vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync); + + // Mock arrayBuffer method + Object.defineProperty(zipFile, 'arrayBuffer', { + value: () => Promise.resolve(new ArrayBuffer(0)), + writable: false + }); + + // Spy on console.warn to check for security warnings + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + try { + // Import the malicious ZIP + const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); + + // Should have completed successfully (safe files extracted) + expect(project).toBeDefined(); + + // Should have logged a security warning about skipped files + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'), + ['../../../etc/passwd', '../../outside.txt'] + ); + + // Verify that only safe files would be written (check writeFile calls) + const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || []; + const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) => + call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt') + ); + expect(maliciousPaths).toHaveLength(0); + + } finally { + // Restore mocks + consoleSpy.mockRestore(); + vi.restoreAllMocks(); + } + }); + }); + describe('renameProject', () => { it('should rename a project directory', async () => { await projectsManager.init(); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index c02b558e..c35f0318 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -1,5 +1,6 @@ import { Buffer } from 'buffer'; -import type { Git } from '@/lib/git'; +import JSZip from 'jszip'; +import { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; import { ensurePersistentStorage } from '@/lib/persistentStorage'; @@ -104,6 +105,192 @@ export class ProjectsManager { return project; } + async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { + // Generate a project ID based on the zip file name or use custom ID + const baseName = zipFile.name.replace(/\.zip$/i, ''); + const generatedId = baseName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + + // Determine the project ID to use + let id: string; + if (customId) { + // Use the provided custom ID (for overwrite scenarios) + id = customId; + } else { + // If no custom ID, generate a unique ID (for new projects) + id = await this.generateUniqueProjectId(generatedId); + } + + const projectPath = `${this.dir}/${id}`; + const projectExists = await this.projectExists(id); + + // Check if project with this ID already exists when not overwriting + if (projectExists && !overwrite) { + throw new Error(`Project with ID "${id}" already exists`); + } + + // Get original project name if overwriting, otherwise use formatted name + let projectName: string; + if (overwrite && projectExists) { + const existingProject = await this.getProject(id); + projectName = existingProject?.name || this.formatProjectName(id); + } else { + projectName = this.formatProjectName(id); + } + + try { + // Create project directory (or ensure it exists for overwrite) + await this.fs.mkdir(projectPath, { recursive: true }); + + // If overwriting, delete existing files except .ai directory and .git directory + if (projectExists && overwrite) { + const existingFiles = await this.getAllFiles(projectPath); + for (const file of existingFiles) { + // Preserve .ai directory and .git directory + if (!file.startsWith('.ai/') && !file.startsWith('.git/')) { + try { + await this.fs.unlink(`${projectPath}/${file}`); + } catch { + // Ignore deletion errors + } + } + } + } + + // Read the zip file + const arrayBuffer = await zipFile.arrayBuffer(); + const zip = await JSZip.loadAsync(arrayBuffer); + + // Extract all files from the zip with security validation + const extractedFiles: string[] = []; + const skippedFiles: string[] = []; + + for (const [relativePath, zipEntry] of Object.entries(zip.files)) { + // Validate the extraction path is within the project directory + const extractPath = this.join(projectPath, relativePath); + + if (!this.isPathWithinProject(extractPath, projectPath)) { + skippedFiles.push(relativePath); + continue; + } + + if (zipEntry.dir) { + // Create the directory structure + await this.fs.mkdir(extractPath, { recursive: true }); + continue; + } + + // Extract file content + const content = await zipEntry.async('uint8array'); + + // Ensure parent directory exists + const dirPath = extractPath.split('/').slice(0, -1).join('/'); + if (dirPath) { + await this.fs.mkdir(dirPath, { recursive: true }); + } + + // Write the file (this will overwrite existing files) + await this.fs.writeFile(extractPath, content); + extractedFiles.push(relativePath); + } + + if (skippedFiles.length > 0) { + console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles); + } + + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Initialize git repository if there's no .git directory + try { + await this.fs.stat(`${projectPath}/.git`); + + // If git exists and we're overwriting, stage the new files + if (overwrite) { + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + try { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } catch { + // Ignore git add errors for files that might be gitignored + } + } + } + + // Make commit for the overwrite + await this.git.commit({ + dir: projectPath, + message: `Overwrite project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + } catch { + // No .git directory found, initialize new repository + await this.git.init({ + dir: projectPath, + defaultBranch: 'main', + }); + + // Add all files to git (excluding .ai directory) + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } + } + + // Make initial commit + await this.git.commit({ + dir: projectPath, + message: `Import project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + + // Create .ai/history directory + try { + await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true }); + } catch { + // Directory might already exist + } + + return { + id, + name: projectName, + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up on error (only if this was a new project creation) + if (!projectExists) { + try { + await this.deleteDirectory(projectPath); + } catch { + // Ignore cleanup errors + } + } + throw error; + } + } + async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise { const id = customId || await this.generateUniqueProjectId(name); @@ -419,4 +606,57 @@ export class ProjectsManager { return files; } + + /** + * Safe path join that normalizes the result to prevent directory traversal + */ + private join(...paths: string[]): string { + // Simple path joining with normalization + const joined = paths.join('/').replace(/\/+/g, '/'); + + // Normalize path separators and resolve .. and . components + const parts = joined.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } + + /** + * Check if a path is within the project directory + */ + private isPathWithinProject(extractPath: string, projectPath: string): boolean { + // Normalize both paths + const normalizedExtractPath = this.normalize(extractPath); + const normalizedProjectPath = this.normalize(projectPath); + + // Check if the extract path starts with the project path + return normalizedExtractPath.startsWith(normalizedProjectPath + '/') || + normalizedExtractPath === normalizedProjectPath; + } + + /** + * Normalize a path by resolving . and .. components + */ + private normalize(path: string): string { + const parts = path.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } } \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index c030fa82..a0c39678 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -15,7 +15,6 @@ import { parseProviderModel } from '@/lib/parseProviderModel'; import type { AIMessage } from '@/lib/SessionManager'; import { saveFileToTmp } from '@/lib/fileUtils'; import type OpenAI from 'openai'; - import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { ModelSelector } from '@/components/ModelSelector'; @@ -262,7 +261,13 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); - checkForKeyFailure(error); + if (!checkForKeyFailure(error)) { + toast({ + title: "Project Creation Failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } } finally { setIsCreating(false); }