This commit is contained in:
Chad Curtis committed 2025-10-21 14:40:06 +00:00
1 parent e47413559b
commit e1da355392
4 files changed
+315 -986

No files matched your search

-288
View File
@@ -1,288 +0,0 @@
# Full System Import Feature
Shakespeare now includes a comprehensive **Full System Import** feature that allows users to completely replace their entire workspace with a previously exported backup. This is like loading a physical disk into the hardware of Shakespeare.
## Overview
The Full System Import feature provides:
- **Complete workspace replacement** - All current data is wiped and replaced
- **Settings restoration** - Restores themes, preferences, and all localStorage data
- **Temporary import workspace** - Uses a separate IndexedDB database for safe processing
- **Security validation** - Prevents directory traversal and malicious file paths
- **Progress tracking** - Real-time feedback during the import process
- **Atomic operation** - Either succeeds completely or fails safely with cleanup
## How It Works
### 1. **Export Structure Validation**
Before any import begins, the system validates that the ZIP file contains a valid Shakespeare export:
- **Required directories**: `projects/`, `config/`, `tmp/` (or localStorage data)
- **Settings data**: `localStorage.json` containing all browser settings
- **Security checks**: No directory traversal (`../`) or unsafe paths
- **File validation**: Only files in allowed directories are accepted
- **Structure verification**: Ensures the export matches Shakespeare's filesystem layout
### 2. **Temporary Import Processing**
The import process uses a temporary IndexedDB database to safely process the import:
```
Temporary Database: shakespeare-import-{timestamp}
├── Extracted ZIP contents
├── Path validation
├── Structure verification
└── Data integrity checks
```
### 3. **Atomic Replacement**
Once validation is complete, the system performs an atomic replacement:
1. **Clear current system** - All existing data is deleted
2. **Copy from temporary** - Validated data is copied to the main filesystem
3. **Cleanup temporary** - The temporary database is deleted
4. **Page reload** - The interface refreshes to show the new data
## Import Process Stages
The import process goes through several stages with progress reporting:
1. **Extracting** (0-10%) - Reading and extracting the ZIP file
2. **Validating** (10-20%) - Validating export structure and security
3. **Creating Temp** (20-30%) - Setting up temporary import workspace
4. **Importing** (30-70%) - Extracting files to temporary storage
5. **Replacing** (70-90%) - Replacing current system with imported data
6. **Restoring Settings** (90-95%) - Restoring themes, preferences, and localStorage
7. **Cleanup** (95-100%) - Removing temporary files and finalizing
## Security Features
### Path Validation
The system prevents malicious imports through comprehensive path validation:
```typescript
// Blocked patterns
../../../etc/passwd // Directory traversal
projects/../../../system/ // Traversal within allowed directories
/absolute/path/outside/ // Absolute paths outside structure
```
### Allowed File Locations
Only files in these directories and specific root files are accepted:
- `projects/` - User projects and source code
- `config/` - AI settings, Git credentials, preferences
- `tmp/` - Temporary files and scratch space
- `localStorage.json` - Browser settings and preferences (root level)
### Structure Validation
The import validates the complete directory structure:
```
Valid Shakespeare Export:
├── projects/
│ └── {project-id}/
│ ├── package.json
│ ├── src/
│ └── ...
├── config/
│ ├── ai.json
│ ├── git.json
│ └── ...
├── tmp/
│ └── ...
└── localStorage.json # Settings and preferences
```
## User Interface
### Data Settings Integration
The Full System Import feature is integrated into the **Data Settings** page (`/settings/data`):
- **Warning alerts** about data loss
- **File upload interface** with drag-and-drop support
- **Validation results** showing project count, file count, and any errors
- **Progress tracking** during the import process
- **Confirmation dialogs** for destructive operations
### Import Dialog Features
- **Drag & Drop**: Drop ZIP files directly onto the dialog
- **File Validation**: Real-time validation with detailed feedback
- **Progress Display**: Stage-by-stage progress with file counts
- **Error Handling**: Clear error messages and safe failure handling
- **Confirmation**: Multi-step confirmation for destructive operations
## API Usage
### Programmatic Import
```typescript
import { importFullSystem, validateExportFile } from '@/lib/fullSystemImport';
// Validate before importing
const validation = await validateExportFile(zipFile);
if (!validation.isValid) {
console.error('Invalid export:', validation.errors);
return;
}
// Import with progress tracking
await importFullSystem(zipFile, fs, (progress) => {
console.log(`${progress.stage}: ${progress.progress}% - ${progress.message}`);
});
```
### Validation Results
```typescript
interface ImportValidation {
isValid: boolean;
hasProjects: boolean;
hasConfig: boolean;
projectCount: number;
totalFiles: number;
errors: string[];
warnings: string[];
}
```
## Error Handling
The system handles various error scenarios gracefully:
### Import Errors
- **Invalid ZIP format** - File is not a valid ZIP archive
- **Missing structure** - Required directories are missing
- **Security violations** - Unsafe file paths detected
- **Corruption** - Files cannot be extracted or are corrupted
### Recovery
- **Automatic cleanup** - Temporary databases are always cleaned up
- **Safe failure** - Original data remains intact if import fails
- **Error reporting** - Detailed error messages help diagnose issues
- **Rollback** - No partial imports; either succeeds completely or fails safely
## Technical Implementation
### Core Classes
- **`FullSystemImporter`** - Main import orchestration class
- **`LightningFSAdapter`** - Filesystem interface adapter
- **`JSRuntimeFS`** - Unified filesystem interface
### Key Methods
- **`validateExport()`** - Validates ZIP file structure and security
- **`importFullSystem()`** - Orchestrates the complete import process
- **`createTempFilesystem()`** - Sets up temporary import workspace
- **`directImport()`** - Direct import for test environments
### Browser Compatibility
- **IndexedDB required** - Uses IndexedDB for temporary storage
- **File API support** - Requires modern File API with `arrayBuffer()`
- **ZIP processing** - Uses JSZip library for archive handling
- **Progress tracking** - Real-time progress updates via callbacks
## Use Cases
### Complete Workspace Migration
- **Device switching** - Move entire workspace to new device
- **Backup restoration** - Restore from complete backup
- **Environment setup** - Set up identical development environment
### Data Recovery
- **Corruption recovery** - Restore from known good backup
- **Accidental deletion** - Recover lost projects and settings
- **Version rollback** - Return to previous workspace state
### Team Collaboration
- **Workspace sharing** - Share complete project setups
- **Template distribution** - Distribute configured environments
- **Onboarding** - Set up new team members with standard workspace
## What Gets Exported/Imported
The Full System Export/Import includes:
### Virtual Filesystem Data
- **All projects** - Complete project files and directories
- **Configuration** - AI settings, Git credentials, user preferences
- **Temporary files** - Any files in the `/tmp` directory
### Browser Storage Data (localStorage.json)
- **Theme settings** - Light/dark/system theme preferences
- **Language preferences** - Interface language selection
- **Project favorites** - Starred/favorited projects
- **AI provider configurations** - API keys and provider settings
- **Git credentials** - Repository access credentials
- **Nostr login data** - Authentication and relay preferences
- **Application preferences** - All other localStorage-stored settings
- **Session data** - Temporary application state
## Limitations
- **Complete replacement only** - Cannot merge with existing data
- **Browser storage limits** - Limited by IndexedDB quota
- **Single ZIP format** - Only accepts ZIP files from Shakespeare exports
- **No selective import** - Imports everything or nothing
## Best Practices
### Before Importing
1. **Export current data** - Always backup before importing
2. **Validate the import** - Check validation results carefully
3. **Verify source** - Ensure the ZIP is from a trusted source
4. **Check storage space** - Ensure sufficient browser storage
### After Importing
1. **Verify data integrity** - Check that all projects loaded correctly
2. **Test functionality** - Ensure all features work as expected
3. **Update settings** - Reconfigure any environment-specific settings
4. **Create new backup** - Export the imported data as a new backup
## Troubleshooting
### Common Issues
- **"Invalid export format"** - ZIP doesn't contain Shakespeare structure
- **"Unsafe file path"** - ZIP contains directory traversal attempts
- **"Storage quota exceeded"** - Not enough browser storage space
- **"Import failed"** - General import error, check browser console
### Solutions
- **Re-export from source** - Create a fresh export from the source
- **Clear browser storage** - Free up space by clearing old data
- **Check browser support** - Ensure browser supports required APIs
- **Use smaller exports** - Break large workspaces into smaller pieces
## Future Enhancements
Potential future improvements to the Full System Import feature:
- **Selective import** - Choose which parts to import
- **Merge capabilities** - Merge with existing data instead of replacing
- **Compression options** - Support for different archive formats
- **Cloud storage** - Direct import from cloud storage services
- **Incremental imports** - Import only changed files
- **Backup scheduling** - Automatic export and import scheduling
---
The Full System Import feature provides a robust, secure way to completely replace a Shakespeare workspace, making it easy to migrate between devices, restore from backups, or set up identical development environments.
+159 -242
View File
@@ -3,13 +3,11 @@ 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, AlertTriangle, Trash2, CheckCircle, XCircle, Info, Loader2, HardDrive } from 'lucide-react';
import { Upload, AlertTriangle, Trash2, CheckCircle, XCircle, Loader2, HardDrive } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { cn } from '@/lib/utils';
import { importFullSystem, validateExportFile, type ImportProgress, type ImportValidation } from '@/lib/fullSystemImport';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
interface FullSystemImportDialogProps {
@@ -20,6 +18,17 @@ interface FullSystemImportDialogProps {
onOpenChange?: (open: boolean) => void;
}
interface ImportState {
selectedFile: File | null;
validation: ImportValidation | null;
isImporting: boolean;
importProgress: ImportProgress | null;
error: string | null;
isDragOver: boolean;
showWarningDialog: boolean;
importComplete: boolean;
}
export function FullSystemImportDialog({
onImport,
disabled = false,
@@ -32,66 +41,78 @@ export function FullSystemImportDialog({
const isOpen = open !== undefined ? open : internalIsOpen;
const setIsOpen = onOpenChange || setInternalIsOpen;
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [validation, setValidation] = useState<ImportValidation | null>(null);
const [isValidating, setIsValidating] = useState(false);
const [isImporting, setIsImporting] = useState(false);
const [importProgress, setImportProgress] = useState<ImportProgress | null>(null);
const [error, setError] = useState<string | null>(null);
const [isDragOver, setIsDragOver] = useState(false);
const [showWarningDialog, setShowWarningDialog] = useState(false);
const [importComplete, setImportComplete] = useState(false);
// Consolidated state management
const [state, setState] = useState<ImportState>({
selectedFile: null,
validation: null,
isImporting: false,
importProgress: null,
error: null,
isDragOver: false,
showWarningDialog: false,
importComplete: false
});
const fileInputRef = useRef<HTMLInputElement>(null);
const { toast } = useToast();
const { fs } = useFS();
const updateState = (updates: Partial<ImportState>) => {
setState(prev => ({ ...prev, ...updates }));
};
const handleFileSelect = async (file: File) => {
// Only accept zip files
if (!file.name.toLowerCase().endsWith('.zip')) {
setError('Please select a ZIP file');
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
setSelectedFile(file);
setError(null);
setValidation(null);
setImportComplete(false);
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
// Validate the file
setIsValidating(true);
try {
const validationResult = await validateExportFile(file);
setValidation(validationResult);
updateState({ validation: validationResult });
if (!validationResult.isValid) {
setError(`Invalid export file: ${validationResult.errors.join(', ')}`);
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to validate file');
} finally {
setIsValidating(false);
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
}
};
// Drag and drop handlers
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(true);
updateState({ isDragOver: true });
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
updateState({ isDragOver: false });
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
updateState({ isDragOver: false });
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
handleFileSelect(files[0]);
const file = files[0];
if (!file.name.toLowerCase().endsWith('.zip')) {
updateState({ error: 'Please select a ZIP file', selectedFile: file, validation: null, importComplete: false });
return;
}
updateState({ selectedFile: file, error: null, validation: null, importComplete: false });
validateExportFile(file).then(validationResult => {
updateState({ validation: validationResult });
if (!validationResult.isValid) {
updateState({ error: `Invalid export: ${validationResult.errors.slice(0, 2).join(', ')}` });
}
}).catch(err => {
updateState({ error: err instanceof Error ? err.message : 'Failed to validate file' });
});
}
}, []);
@@ -100,88 +121,76 @@ export function FullSystemImportDialog({
};
const handleFileRemove = () => {
setSelectedFile(null);
setValidation(null);
setError(null);
setImportComplete(false);
updateState({ selectedFile: null, validation: null, error: null, importComplete: false });
};
const handleImportStart = () => {
if (!selectedFile || !validation?.isValid) return;
setShowWarningDialog(true);
if (!state.selectedFile || !state.validation?.isValid) return;
updateState({ showWarningDialog: true });
};
const handleImportConfirm = async () => {
if (!selectedFile) return;
if (!state.selectedFile) return;
setShowWarningDialog(false);
setIsImporting(true);
setImportProgress(null);
setError(null);
updateState({ showWarningDialog: false, isImporting: true, importProgress: null, error: null });
try {
await importFullSystem(selectedFile, fs, (progress) => {
setImportProgress(progress);
await importFullSystem(state.selectedFile, fs, (progress) => {
updateState({ importProgress: progress });
});
setImportComplete(true);
updateState({ importComplete: true });
toast({
title: 'System Import Successful',
description: 'Your Shakespeare workspace has been completely restored from the export file.',
title: 'Import Successful',
description: 'Your workspace has been completely restored.',
});
// Call onImport callback if provided
if (onImport) {
onImport();
}
if (onImport) onImport();
// Close dialog after a short delay to show success
setTimeout(() => {
setIsOpen(false);
// Reload the page to refresh all data
window.location.reload();
}, 2000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import system');
setImportProgress(null);
const errorMsg = err instanceof Error ? err.message : 'Import failed';
updateState({ error: errorMsg, importProgress: null, isImporting: false });
toast({
title: 'Import Failed',
description: err instanceof Error ? err.message : 'Failed to import system',
description: errorMsg,
variant: 'destructive',
});
} finally {
setIsImporting(false);
}
};
const handleClose = () => {
if (!isImporting) {
if (!state.isImporting) {
setIsOpen(false);
setSelectedFile(null);
setValidation(null);
setError(null);
setImportProgress(null);
setImportComplete(false);
updateState({
selectedFile: null,
validation: null,
error: null,
importProgress: null,
importComplete: false
});
}
};
const getStageDescription = (stage: ImportProgress['stage']): string => {
switch (stage) {
case 'extracting': return 'Extracting ZIP file...';
case 'validating': return 'Validating export structure...';
case 'creating_temp': return 'Setting up temporary workspace...';
case 'importing': return 'Importing files to temporary storage...';
case 'replacing': return 'Replacing current system and restoring settings...';
case 'cleanup': return 'Cleaning up temporary files...';
case 'complete': return 'Import completed successfully!';
default: return 'Processing...';
}
const descriptions = {
extracting: 'Extracting ZIP file...',
validating: 'Validating export...',
creating_temp: 'Setting up workspace...',
importing: 'Importing files...',
replacing: 'Replacing system...',
cleanup: 'Cleaning up...',
complete: 'Import completed!'
};
return descriptions[stage] || 'Processing...';
};
// Only render DialogTrigger if this component is being used in uncontrolled mode
const isControlled = open !== undefined && onOpenChange !== undefined;
return (
@@ -200,37 +209,33 @@ export function FullSystemImportDialog({
</DialogTrigger>
)}
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<HardDrive className="h-5 w-5 text-destructive" />
Import Complete Shakespeare System
Import Complete System
</DialogTitle>
<DialogDescription>
Replace your entire Shakespeare workspace with a previously exported backup.
This will permanently delete all current projects, settings, and data.
Replace your entire workspace with a backup. This will permanently delete all current data.
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
{/* Warning Alert */}
<div className="space-y-4">
<Alert className="border-destructive/50 bg-destructive/5">
<AlertTriangle className="h-4 w-4 text-destructive" />
<AlertDescription className="text-destructive">
<strong>Warning:</strong> This action will completely wipe your current Shakespeare workspace and replace it with the imported data.
All current projects, AI settings, Git credentials, and preferences will be permanently lost.
<strong>Warning:</strong> This will completely wipe your current workspace and replace it with imported data.
</AlertDescription>
</Alert>
{!isImporting && !importComplete && (
{!state.isImporting && !state.importComplete && (
<>
{/* File Upload Area */}
<div
className={cn(
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
selectedFile && validation?.isValid && "border-green-500/50 bg-green-500/5",
selectedFile && validation && !validation.isValid && "border-destructive/50 bg-destructive/5"
"relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer",
state.isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50",
state.selectedFile && state.validation?.isValid && "border-green-500/50 bg-green-500/5",
state.selectedFile && state.validation && !state.validation.isValid && "border-destructive/50 bg-destructive/5"
)}
onClick={handleClickUpload}
onDragOver={handleDragOver}
@@ -248,15 +253,13 @@ export function FullSystemImportDialog({
}}
accept=".zip"
className="hidden"
disabled={isImporting || isValidating}
disabled={state.isImporting}
/>
<div className="space-y-3">
<div className="flex justify-center">
{isValidating ? (
<Loader2 className="h-8 w-8 text-primary animate-spin" />
) : selectedFile ? (
validation?.isValid ? (
{state.selectedFile ? (
state.validation?.isValid ? (
<CheckCircle className="h-8 w-8 text-green-600" />
) : (
<XCircle className="h-8 w-8 text-destructive" />
@@ -267,24 +270,18 @@ export function FullSystemImportDialog({
</div>
<div>
{selectedFile ? (
{state.selectedFile ? (
<div className="space-y-2">
<p className="text-sm font-medium">
{selectedFile.name}
</p>
<p className="text-sm font-medium">{state.selectedFile.name}</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
{(state.selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
{isValidating && (
<p className="text-xs text-primary">Validating...</p>
)}
<button
onClick={(e) => {
e.stopPropagation();
handleFileRemove();
}}
className="text-xs text-destructive hover:underline"
disabled={isValidating}
>
Remove file
</button>
@@ -292,10 +289,10 @@ export function FullSystemImportDialog({
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop your Shakespeare export ZIP here or click to browse
Drop ZIP file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
Only ZIP files exported from Shakespeare Data Settings
Only Shakespeare export ZIP files
</p>
</div>
)}
@@ -303,200 +300,120 @@ export function FullSystemImportDialog({
</div>
</div>
{/* Validation Results */}
{validation && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm flex items-center gap-2">
{validation.isValid ? (
<CheckCircle className="h-4 w-4 text-green-600" />
) : (
<XCircle className="h-4 w-4 text-destructive" />
)}
Export Validation
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Projects:</span>
<Badge variant="secondary" className="ml-2">
{validation.projectCount}
</Badge>
</div>
<div>
<span className="text-muted-foreground">Total Files:</span>
<Badge variant="secondary" className="ml-2">
{validation.totalFiles}
</Badge>
</div>
<div>
<span className="text-muted-foreground">Has Config:</span>
<Badge variant={validation.hasConfig ? "default" : "secondary"} className="ml-2">
{validation.hasConfig ? 'Yes' : 'No'}
</Badge>
</div>
<div>
<span className="text-muted-foreground">Valid:</span>
<Badge variant={validation.isValid ? "default" : "destructive"} className="ml-2">
{validation.isValid ? 'Yes' : 'No'}
</Badge>
</div>
{state.validation && (
<div className="text-sm space-y-2 p-3 bg-muted rounded">
<div className="flex justify-between">
<span>Projects:</span>
<span className="font-medium">{state.validation.projectCount}</span>
</div>
<div className="flex justify-between">
<span>Files:</span>
<span className="font-medium">{state.validation.totalFiles}</span>
</div>
<div className="flex justify-between">
<span>Valid:</span>
<span className={cn("font-medium", state.validation.isValid ? "text-green-600" : "text-destructive")}>
{state.validation.isValid ? 'Yes' : 'No'}
</span>
</div>
{state.validation.errors.length > 0 && (
<div className="text-xs text-destructive">
{state.validation.errors.slice(0, 2).join(', ')}
</div>
{validation.errors.length > 0 && (
<div className="space-y-1">
<p className="text-sm font-medium text-destructive">Errors:</p>
<ul className="text-xs text-destructive space-y-1">
{validation.errors.map((error, index) => (
<li key={index} className="flex items-start gap-1">
<span>•</span>
<span>{error}</span>
</li>
))}
</ul>
</div>
)}
{validation.warnings.length > 0 && (
<div className="space-y-1">
<p className="text-sm font-medium text-amber-600">Warnings:</p>
<ul className="text-xs text-amber-600 space-y-1">
{validation.warnings.map((warning, index) => (
<li key={index} className="flex items-start gap-1">
<span>•</span>
<span>{warning}</span>
</li>
))}
</ul>
</div>
)}
</CardContent>
</Card>
)}
</div>
)}
{/* Error Display */}
{error && (
{state.error && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
<AlertDescription>{state.error}</AlertDescription>
</Alert>
)}
{/* Action Buttons */}
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
onClick={handleImportStart}
disabled={!selectedFile || !validation?.isValid || isValidating}
disabled={!state.selectedFile || !state.validation?.isValid}
variant="destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Replace Entire System
Replace System
</Button>
</div>
</>
)}
{/* Import Progress */}
{isImporting && importProgress && (
{state.isImporting && state.importProgress && (
<div className="space-y-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
{getStageDescription(importProgress.stage)}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<Progress value={importProgress.progress} className="w-full" />
<div className="flex justify-between text-xs text-muted-foreground">
<span>{importProgress.message}</span>
<span>{Math.round(importProgress.progress)}%</span>
</div>
{importProgress.filesProcessed && importProgress.totalFiles && (
<div className="text-xs text-muted-foreground text-center">
Processing file {importProgress.filesProcessed} of {importProgress.totalFiles}
</div>
)}
<div className="text-xs text-muted-foreground">
<strong>Current Stage:</strong> {importProgress.stage.replace('_', ' ').toUpperCase()}
</div>
</CardContent>
</Card>
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin" />
{getStageDescription(state.importProgress.stage)}
</div>
<Progress value={state.importProgress.progress} className="w-full" />
<div className="flex justify-between text-xs text-muted-foreground">
<span>{state.importProgress.message}</span>
<span>{Math.round(state.importProgress.progress)}%</span>
</div>
</div>
<Alert>
<Info className="h-4 w-4" />
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Please do not close this window or navigate away during the import process.
This may take several minutes depending on the size of your data.
Please do not close this window during import.
</AlertDescription>
</Alert>
</div>
)}
{/* Success State */}
{importComplete && (
<Card className="border-green-500/50 bg-green-500/5">
<CardContent className="pt-6">
<div className="flex items-center gap-3 text-green-600">
<CheckCircle className="h-6 w-6" />
<div>
<p className="font-medium">Import Completed Successfully!</p>
<p className="text-sm text-muted-foreground">
Your Shakespeare workspace has been restored. The page will reload automatically.
</p>
</div>
</div>
</CardContent>
</Card>
{state.importComplete && (
<Alert className="border-green-500/50 bg-green-500/5">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-600">
Import completed successfully! Reloading page...
</AlertDescription>
</Alert>
)}
</div>
</DialogContent>
</Dialog>
{/* Confirmation Dialog */}
<AlertDialog open={showWarningDialog} onOpenChange={setShowWarningDialog}>
<AlertDialog open={state.showWarningDialog} onOpenChange={(open) => updateState({ showWarningDialog: open })}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-destructive" />
Confirm Complete System Replacement
Confirm System Replacement
</AlertDialogTitle>
<AlertDialogDescription className="space-y-3">
<p>
You are about to <strong>completely replace</strong> your Shakespeare workspace with the imported data.
You are about to <strong>completely replace</strong> your workspace with imported data.
</p>
<div className="bg-destructive/10 border border-destructive/20 rounded p-3">
<p className="text-sm font-medium text-destructive mb-2">This will permanently delete:</p>
<ul className="list-disc list-inside text-sm text-destructive space-y-1">
<li>All current projects and their files</li>
<li>AI provider settings and API keys</li>
<li>Git credentials and repository settings</li>
<li>User preferences and theme settings</li>
<li>All cached data and temporary files</li>
<li>All current projects and files</li>
<li>AI settings and API keys</li>
<li>Git credentials and preferences</li>
<li>All cached data</li>
</ul>
</div>
{validation && (
{state.validation && (
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded p-3">
<p className="text-sm font-medium text-green-800 dark:text-green-200 mb-2">Import will restore:</p>
<ul className="list-disc list-inside text-sm text-green-700 dark:text-green-300 space-y-1">
<li>{validation.projectCount} projects</li>
<li>{validation.totalFiles} total files</li>
{validation.hasConfig && <li>Settings, themes, and preferences</li>}
</ul>
<p className="text-sm font-medium text-green-800 dark:text-green-200">
Import will restore {state.validation.projectCount} projects and {state.validation.totalFiles} files
</p>
</div>
)}
<p className="text-destructive font-medium">
This action cannot be undone. Are you absolutely sure?
This action cannot be undone. Are you sure?
</p>
</AlertDialogDescription>
</AlertDialogHeader>
+50 -172
View File
@@ -3,24 +3,21 @@ import JSZip from 'jszip';
import { FullSystemImporter, validateExportFile } from './fullSystemImport';
import type { JSRuntimeFS } from './JSRuntime';
// Mock filesystem implementation for testing
// Simplified mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files = new Map<string, Uint8Array | string>();
private dirs = new Set<string>();
constructor() {
this.dirs.add('/');
}
private dirs = new Set<string>(['/']);
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options?: { encoding?: string } | string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`ENOENT: no such file or directory, open '${path}'`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8' || encoding) {
if (content instanceof Uint8Array) {
return new TextDecoder().decode(content);
@@ -28,14 +25,10 @@ class MockFS implements JSRuntimeFS {
return content as string;
}
if (typeof content === 'string') {
return new TextEncoder().encode(content);
}
return content;
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
// Ensure parent directory exists
const dirPath = path.split('/').slice(0, -1).join('/') || '/';
this.dirs.add(dirPath);
this.files.set(path, data);
@@ -45,11 +38,11 @@ class MockFS implements JSRuntimeFS {
async readdir(path: string, options: { withFileTypes: true }): Promise<Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>> {
const items: string[] = [];
const prefix = path === '/' ? '/' : `${path}/`;
// Find files and directories in this path
for (const filePath of this.files.keys()) {
if (filePath.startsWith(path === '/' ? '/' : path + '/')) {
const relativePath = filePath.slice(path === '/' ? 1 : path.length + 1);
if (filePath.startsWith(prefix)) {
const relativePath = filePath.slice(prefix.length);
const firstSegment = relativePath.split('/')[0];
if (firstSegment && !items.includes(firstSegment)) {
items.push(firstSegment);
@@ -58,8 +51,8 @@ class MockFS implements JSRuntimeFS {
}
for (const dirPath of this.dirs) {
if (dirPath.startsWith(path === '/' ? '/' : path + '/') && dirPath !== path) {
const relativePath = dirPath.slice(path === '/' ? 1 : path.length + 1);
if (dirPath.startsWith(prefix) && dirPath !== path) {
const relativePath = dirPath.slice(prefix.length);
const firstSegment = relativePath.split('/')[0];
if (firstSegment && !items.includes(firstSegment)) {
items.push(firstSegment);
@@ -139,71 +132,42 @@ class MockFS implements JSRuntimeFS {
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
async readlink(): Promise<string> {
throw new Error('Symlinks not supported');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
async symlink(): Promise<void> {
throw new Error('Symlinks not supported');
}
// Helper method to clear the filesystem
clear(): void {
this.files.clear();
this.dirs.clear();
this.dirs.add('/');
}
// Helper method to populate with test data
populate(): void {
this.dirs.add('/projects');
this.dirs.add('/projects/test-project');
this.dirs.add('/config');
this.dirs.add('/tmp');
this.files.set('/projects/test-project/package.json', JSON.stringify({
name: 'test-project',
version: '1.0.0'
}));
this.files.set('/projects/test-project/src/index.ts', 'console.log("Hello World");');
this.files.set('/config/ai.json', JSON.stringify({ provider: 'openai' }));
this.files.set('/config/git.json', JSON.stringify({ credentials: [] }));
}
}
// Helper function to create a valid export ZIP
// Helper functions
async function createValidExportZip(): Promise<File> {
const zip = new JSZip();
// Add project structure
zip.folder('projects');
zip.folder('projects/test-project');
// Add project
zip.folder('projects/test-project/src');
zip.file('projects/test-project/package.json', JSON.stringify({
name: 'test-project',
version: '1.0.0'
}));
zip.file('projects/test-project/src/index.ts', 'console.log("Hello World");');
zip.file('projects/test-project/package.json', JSON.stringify({ name: 'test-project' }));
zip.file('projects/test-project/src/index.ts', 'console.log("Hello");');
// Add config
zip.folder('config');
zip.file('config/ai.json', JSON.stringify({ provider: 'openai' }));
zip.file('config/git.json', JSON.stringify({ credentials: [] }));
// Add tmp directory
zip.folder('tmp');
// Add localStorage data
// Add localStorage
zip.file('localStorage.json', JSON.stringify({
'nostr:app-config': JSON.stringify({ theme: 'dark', relayUrl: 'wss://relay.example.com', deployServer: 'test.com' }),
'project-favorites': JSON.stringify(['test-project'])
'nostr:app-config': JSON.stringify({ theme: 'dark' })
}));
const content = await zip.generateAsync({ type: 'arraybuffer' });
// Create a proper File-like object with arrayBuffer method
const fileObj = {
name: 'shakespeare-export.zip',
return {
name: 'export.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
@@ -211,26 +175,20 @@ async function createValidExportZip(): Promise<File> {
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => fileObj,
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
return fileObj;
}
// Helper function to create an invalid export ZIP
async function createInvalidExportZip(): Promise<File> {
const zip = new JSZip();
// Add some random files that don't match Shakespeare structure
zip.file('random.txt', 'This is not a Shakespeare export');
zip.file('../../../etc/passwd', 'malicious content'); // Path traversal attempt
zip.file('../../../etc/passwd', 'malicious');
zip.file('random.txt', 'invalid');
const content = await zip.generateAsync({ type: 'arraybuffer' });
// Create a proper File-like object with arrayBuffer method
const fileObj = {
name: 'invalid-export.zip',
return {
name: 'invalid.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
@@ -238,28 +196,22 @@ async function createInvalidExportZip(): Promise<File> {
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => fileObj,
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
return fileObj;
}
describe('FullSystemImporter', () => {
let mockFS: MockFS;
let importer: FullSystemImporter;
let progressCallbacks: Array<{ stage: string; progress: number; message: string }>;
beforeEach(() => {
mockFS = new MockFS();
progressCallbacks = [];
importer = new FullSystemImporter((progress) => {
progressCallbacks.push(progress);
});
importer = new FullSystemImporter();
});
describe('validateExportFile', () => {
it('should validate a correct Shakespeare export', async () => {
it('should validate correct export', async () => {
const validZip = await createValidExportZip();
const validation = await validateExportFile(validZip);
@@ -270,68 +222,18 @@ describe('FullSystemImporter', () => {
expect(validation.errors).toHaveLength(0);
});
it('should reject an invalid export', async () => {
it('should reject invalid export', async () => {
const invalidZip = await createInvalidExportZip();
const validation = await validateExportFile(invalidZip);
expect(validation.isValid).toBe(false);
expect(validation.errors.length).toBeGreaterThan(0);
expect(validation.errors.some(error => error.includes('directory structure'))).toBe(true);
});
it('should detect unsafe file paths', async () => {
it('should block unsafe paths', async () => {
const zip = new JSZip();
zip.file('../../../etc/passwd', 'malicious content');
zip.file('projects/test/package.json', '{}');
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
name: 'malicious.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => file,
bytes: async () => new Uint8Array(content)
} as File;
const validation = await validateExportFile(file);
expect(validation.isValid).toBe(false);
expect(validation.errors.some(error => error.includes('Unsafe file path'))).toBe(true);
});
});
describe('importFullSystem', () => {
it.skip('should successfully import a valid export', async () => {
// Skip this test due to complexity with IndexedDB in test environment
// The functionality is tested manually and works in browser environment
});
it('should reject invalid exports', async () => {
const invalidZip = await createInvalidExportZip();
await expect(importer.importFullSystem(invalidZip, mockFS)).rejects.toThrow('Invalid export file');
});
it.skip('should clear existing data before import', async () => {
// Skip this test due to complexity with IndexedDB in test environment
});
it.skip('should report progress throughout the import', async () => {
// Skip this test due to complexity with IndexedDB in test environment
});
});
describe('path security', () => {
it('should prevent directory traversal attacks', async () => {
const zip = new JSZip();
zip.file('projects/test/package.json', '{}');
zip.file('../../../etc/passwd', 'malicious');
zip.file('projects/test/../../../etc/shadow', 'malicious');
zip.file('projects/test/package.json', '{}');
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
@@ -343,48 +245,22 @@ describe('FullSystemImporter', () => {
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => file,
bytes: async () => new Uint8Array(content)
} as File;
await expect(importer.importFullSystem(file, mockFS)).rejects.toThrow('Invalid export file');
});
it('should only allow files in valid directories', async () => {
const zip = new JSZip();
zip.file('projects/test/package.json', '{}');
zip.file('config/ai.json', '{}');
zip.file('tmp/temp.txt', 'temp');
zip.file('invalid/file.txt', 'should not be allowed');
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
name: 'test.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
webkitRelativePath: '',
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => file,
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
const validation = await validateExportFile(file);
expect(validation.isValid).toBe(false);
expect(validation.errors.some(e => e.includes('Unsafe path'))).toBe(true);
});
it('should accept localStorage-only exports', async () => {
it('should accept localStorage-only export', async () => {
const zip = new JSZip();
zip.file('localStorage.json', JSON.stringify({
'nostr:app-config': JSON.stringify({ theme: 'dark' }),
'project-favorites': JSON.stringify([])
}));
zip.file('localStorage.json', JSON.stringify({ theme: 'dark' }));
const content = await zip.generateAsync({ type: 'arraybuffer' });
const file = {
name: 'settings-export.zip',
name: 'settings.zip',
type: 'application/zip',
size: content.byteLength,
lastModified: Date.now(),
@@ -392,7 +268,7 @@ describe('FullSystemImporter', () => {
arrayBuffer: async () => content,
stream: () => new ReadableStream(),
text: async () => '',
slice: () => file,
slice: () => ({} as File),
bytes: async () => new Uint8Array(content)
} as File;
@@ -401,14 +277,16 @@ describe('FullSystemImporter', () => {
expect(validation.hasConfig).toBe(true);
});
});
});
describe('convenience functions', () => {
it('should export validateExportFile function', async () => {
const validZip = await createValidExportZip();
const validation = await validateExportFile(validZip);
describe('importFullSystem', () => {
it('should reject invalid exports', async () => {
const invalidZip = await createInvalidExportZip();
await expect(importer.importFullSystem(invalidZip, mockFS)).rejects.toThrow('Invalid export');
});
expect(validation).toBeDefined();
expect(typeof validation.isValid).toBe('boolean');
it.skip('should import valid export', async () => {
// Skip due to IndexedDB complexity in test environment
// Functionality tested manually in browser
});
});
});
+106 -284
View File
@@ -4,7 +4,7 @@ import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
export interface ImportProgress {
stage: 'extracting' | 'validating' | 'creating_temp' | 'importing' | 'replacing' | 'cleanup' | 'complete';
stage: 'extracting' | 'validating' | 'importing' | 'cleanup' | 'complete';
progress: number;
message: string;
filesProcessed?: number;
@@ -23,16 +23,12 @@ export interface ImportValidation {
export class FullSystemImporter {
private onProgress?: (progress: ImportProgress) => void;
private tempFS?: JSRuntimeFS;
private tempFSName?: string;
constructor(onProgress?: (progress: ImportProgress) => void) {
this.onProgress = onProgress;
}
/**
* Validate a ZIP file to ensure it's a valid Shakespeare export
*/
async validateExport(zipFile: File): Promise<ImportValidation> {
const result: ImportValidation = {
isValid: false,
@@ -50,20 +46,16 @@ export class FullSystemImporter {
const files = Object.keys(zip.files);
result.totalFiles = files.length;
// Check for required directory structure or localStorage data
const hasRootStructure = files.some(path =>
// Check for valid structure
const hasValidStructure = files.some(path =>
path.startsWith('projects/') ||
path.startsWith('config/') ||
path.startsWith('tmp/') ||
path === 'projects' ||
path === 'config' ||
path === 'tmp'
path === 'localStorage.json'
);
const hasLocalStorageData = files.includes('localStorage.json');
if (!hasRootStructure && !hasLocalStorageData) {
result.errors.push('Invalid export format: Missing required directory structure and localStorage data');
if (!hasValidStructure) {
result.errors.push('Invalid export: Missing required structure');
return result;
}
@@ -81,48 +73,34 @@ export class FullSystemImporter {
result.projectCount = projectDirs.size;
result.hasProjects = result.projectCount > 0;
// Check for config files
// Check for config
result.hasConfig = files.some(path =>
path.startsWith('config/ai.json') ||
path.startsWith('config/git.json')
) || hasLocalStorageData;
path.startsWith('config/') || path === 'localStorage.json'
);
// Validate file paths for security
// Security validation
for (const path of files) {
if (this.isUnsafePath(path)) {
result.errors.push(`Unsafe file path detected: ${path}`);
result.errors.push(`Unsafe path: ${path}`);
}
// Check if file is in valid directory structure
if (!path.endsWith('/') && !this.isValidFilePath(path)) {
result.errors.push(`File in invalid location: ${path}`);
if (!path.endsWith('/') && !this.isValidFilePath(path) && path !== 'localStorage.json') {
result.errors.push(`Invalid location: ${path}`);
}
}
// Add warnings for missing components
if (!result.hasProjects) {
result.warnings.push('No projects found in export');
}
if (!result.hasConfig) {
result.warnings.push('No configuration files found in export');
}
result.isValid = result.errors.length === 0;
return result;
} catch (error) {
result.errors.push(`Failed to read ZIP file: ${error instanceof Error ? error.message : 'Unknown error'}`);
result.errors.push(`Failed to read ZIP: ${error instanceof Error ? error.message : 'Unknown error'}`);
return result;
}
}
/**
* Import a complete Shakespeare export, replacing the current system
*/
async importFullSystem(zipFile: File, currentFS: JSRuntimeFS): Promise<void> {
try {
// Stage 1: Extract and validate
this.reportProgress('extracting', 0, 'Extracting ZIP file...');
// Extract and validate
this.reportProgress('extracting', 0, 'Extracting ZIP...');
const arrayBuffer = await zipFile.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
@@ -130,222 +108,150 @@ export class FullSystemImporter {
const validation = await this.validateExport(zipFile);
if (!validation.isValid) {
throw new Error(`Invalid export file: ${validation.errors.join(', ')}`);
throw new Error(`Invalid export: ${validation.errors.slice(0, 2).join(', ')}`);
}
// For test environments or when IndexedDB is not available, use direct import
// Check if we can use direct import (simpler path)
const isTestEnvironment = typeof window === 'undefined' || typeof indexedDB === 'undefined';
if (isTestEnvironment) {
// Direct import without temporary filesystem
this.reportProgress('replacing', 30, 'Replacing current system...');
await this.directImport(zip, currentFS, validation.totalFiles);
this.reportProgress('replacing', 90, 'Restoring settings and preferences...');
await this.restoreLocalStorage(zip);
this.reportProgress('complete', 100, 'Import completed successfully!');
return;
} else {
await this.tempImport(zip, currentFS, validation.totalFiles);
}
// Stage 2: Create temporary filesystem
this.reportProgress('creating_temp', 20, 'Creating temporary import workspace...');
await this.createTempFilesystem();
if (!this.tempFS) {
throw new Error('Failed to create temporary filesystem');
}
// Stage 3: Import to temporary filesystem
this.reportProgress('importing', 30, 'Importing files to temporary workspace...');
await this.importToTempFilesystem(zip, validation.totalFiles);
// Stage 4: Validate imported data
this.reportProgress('validating', 70, 'Validating imported data...');
await this.validateImportedData();
// Stage 5: Replace current system
this.reportProgress('replacing', 80, 'Replacing current system...');
await this.replaceCurrentSystem(currentFS);
// Stage 6: Restore localStorage
this.reportProgress('replacing', 90, 'Restoring settings and preferences...');
// Restore localStorage
await this.restoreLocalStorage(zip);
// Stage 7: Cleanup
this.reportProgress('cleanup', 95, 'Cleaning up temporary files...');
await this.cleanupTempFilesystem();
this.reportProgress('complete', 100, 'Import completed successfully!');
this.reportProgress('complete', 100, 'Import completed!');
} catch (error) {
// Cleanup on error
await this.cleanupTempFilesystem();
await this.cleanup();
throw error;
}
}
/**
* Create a temporary filesystem for import processing
*/
private async createTempFilesystem(): Promise<void> {
private async tempImport(zip: JSZip, currentFS: JSRuntimeFS, totalFiles: number): Promise<void> {
// Create temporary filesystem
this.reportProgress('importing', 20, 'Setting up workspace...');
this.tempFSName = `shakespeare-import-${Date.now()}`;
const tempLightningFS = new LightningFS(this.tempFSName);
this.tempFS = new LightningFSAdapter(tempLightningFS.promises);
const tempFS = new LightningFSAdapter(tempLightningFS.promises);
// Create basic directory structure
await this.tempFS.mkdir('/projects', { recursive: true });
await this.tempFS.mkdir('/config', { recursive: true });
await this.tempFS.mkdir('/tmp', { recursive: true });
}
/**
* Import ZIP contents to temporary filesystem
*/
private async importToTempFilesystem(zip: JSZip, totalFiles: number): Promise<void> {
if (!this.tempFS) {
throw new Error('Temporary filesystem not initialized');
}
// Create directories
await tempFS.mkdir('/projects', { recursive: true });
await tempFS.mkdir('/config', { recursive: true });
await tempFS.mkdir('/tmp', { recursive: true });
// Extract files to temp filesystem
let filesProcessed = 0;
const files = Object.entries(zip.files);
for (const [relativePath, zipEntry] of files) {
// Validate path security
if (this.isUnsafePath(relativePath)) {
throw new Error(`Unsafe file path: ${relativePath}`);
throw new Error(`Unsafe path: ${relativePath}`);
}
const fullPath = `/${relativePath}`;
if (zipEntry.dir) {
// Create directory
await this.tempFS.mkdir(fullPath, { recursive: true });
await tempFS.mkdir(fullPath, { recursive: true });
} else {
// Extract file
const content = await zipEntry.async('uint8array');
// Ensure parent directory exists
const dirPath = fullPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await this.tempFS.mkdir(dirPath, { recursive: true });
await tempFS.mkdir(dirPath, { recursive: true });
}
// Write file
await this.tempFS.writeFile(fullPath, content);
await tempFS.writeFile(fullPath, content);
}
filesProcessed++;
const progress = 30 + (filesProcessed / totalFiles) * 40; // 30-70% range
this.reportProgress('importing', progress, `Importing files... (${filesProcessed}/${totalFiles})`, filesProcessed, totalFiles);
const progress = 20 + (filesProcessed / totalFiles) * 60;
this.reportProgress('importing', progress, `Importing files... (${filesProcessed}/${totalFiles})`);
}
// Replace current system
this.reportProgress('importing', 85, 'Replacing system...');
await this.replaceSystem(tempFS, currentFS);
// Cleanup
this.reportProgress('cleanup', 95, 'Cleaning up...');
await this.cleanup();
}
/**
* Validate the imported data in temporary filesystem
*/
private async validateImportedData(): Promise<void> {
if (!this.tempFS) {
throw new Error('Temporary filesystem not initialized');
}
private async directImport(zip: JSZip, currentFS: JSRuntimeFS, totalFiles: number): Promise<void> {
this.reportProgress('importing', 30, 'Clearing current system...');
await this.clearSystem(currentFS);
try {
// Check that core directories exist
await this.tempFS.stat('/projects');
await this.tempFS.stat('/config');
await this.tempFS.stat('/tmp');
let filesProcessed = 0;
const files = Object.entries(zip.files);
// Validate project structure
const projects = await this.tempFS.readdir('/projects');
for (const projectId of projects) {
const projectPath = `/projects/${projectId}`;
const projectStat = await this.tempFS.stat(projectPath);
if (!projectStat.isDirectory()) {
throw new Error(`Invalid project structure: ${projectId} is not a directory`);
}
// Check for essential project files (package.json is common)
try {
await this.tempFS.stat(`${projectPath}/package.json`);
} catch {
// package.json is not required, but log if missing
console.warn(`Project ${projectId} does not have package.json`);
}
for (const [relativePath, zipEntry] of files) {
if (this.isUnsafePath(relativePath)) {
throw new Error(`Unsafe path: ${relativePath}`);
}
} catch (error) {
throw new Error(`Validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
const fullPath = `/${relativePath}`;
if (zipEntry.dir) {
await currentFS.mkdir(fullPath, { recursive: true });
} else {
const content = await zipEntry.async('uint8array');
const dirPath = fullPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await currentFS.mkdir(dirPath, { recursive: true });
}
await currentFS.writeFile(fullPath, content);
}
filesProcessed++;
const progress = 30 + (filesProcessed / totalFiles) * 65;
this.reportProgress('importing', progress, `Importing files... (${filesProcessed}/${totalFiles})`);
}
}
/**
* Replace the current filesystem with the imported data
*/
private async replaceCurrentSystem(currentFS: JSRuntimeFS): Promise<void> {
if (!this.tempFS) {
throw new Error('Temporary filesystem not initialized');
}
// Step 1: Clear current system
await this.clearCurrentSystem(currentFS);
// Step 2: Copy from temporary filesystem to current filesystem
await this.copyFilesystem(this.tempFS, currentFS, '/', '/');
private async replaceSystem(tempFS: JSRuntimeFS, currentFS: JSRuntimeFS): Promise<void> {
await this.clearSystem(currentFS);
await this.copyFilesystem(tempFS, currentFS, '/', '/');
}
/**
* Clear the current filesystem completely
*/
private async clearCurrentSystem(fs: JSRuntimeFS): Promise<void> {
private async clearSystem(fs: JSRuntimeFS): Promise<void> {
try {
// Get all top-level directories
const entries = await fs.readdir('/', { withFileTypes: true });
for (const entry of entries) {
const fullPath = `/${entry.name}`;
if (entry.isDirectory()) {
await this.deleteDirectoryRecursive(fs, fullPath);
await this.deleteDirectory(fs, fullPath);
} else {
await fs.unlink(fullPath);
}
}
} catch (error) {
// If readdir fails, the filesystem might be empty or corrupted
console.warn('Failed to clear current system:', error);
console.warn('Failed to clear system:', error);
}
}
/**
* Recursively delete a directory and all its contents
*/
private async deleteDirectoryRecursive(fs: JSRuntimeFS, dirPath: string): Promise<void> {
private async deleteDirectory(fs: JSRuntimeFS, dirPath: string): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
await this.deleteDirectoryRecursive(fs, fullPath);
await this.deleteDirectory(fs, fullPath);
} else {
await fs.unlink(fullPath);
}
}
await fs.rmdir(dirPath);
} catch (error) {
console.warn(`Failed to delete directory ${dirPath}:`, error);
console.warn(`Failed to delete ${dirPath}:`, error);
}
}
/**
* Copy entire filesystem from source to destination
*/
private async copyFilesystem(sourceFS: JSRuntimeFS, destFS: JSRuntimeFS, sourcePath: string, destPath: string): Promise<void> {
try {
const entries = await sourceFS.readdir(sourcePath, { withFileTypes: true });
// Ensure destination directory exists
if (destPath !== '/') {
await destFS.mkdir(destPath, { recursive: true });
}
@@ -363,41 +269,48 @@ export class FullSystemImporter {
}
}
} catch (error) {
throw new Error(`Failed to copy filesystem: ${error instanceof Error ? error.message : 'Unknown error'}`);
throw new Error(`Copy failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Clean up temporary filesystem
*/
private async cleanupTempFilesystem(): Promise<void> {
private async cleanup(): Promise<void> {
if (this.tempFSName) {
try {
// Delete the temporary IndexedDB database
const deleteRequest = indexedDB.deleteDatabase(this.tempFSName);
await new Promise<void>((resolve, reject) => {
deleteRequest.onsuccess = () => resolve();
deleteRequest.onerror = () => reject(deleteRequest.error);
deleteRequest.onblocked = () => {
console.warn('Temporary database deletion blocked');
resolve(); // Continue anyway
};
deleteRequest.onblocked = () => resolve();
});
} catch (error) {
console.warn('Failed to cleanup temporary filesystem:', error);
console.warn('Cleanup failed:', error);
}
}
this.tempFS = undefined;
this.tempFSName = undefined;
}
/**
* Check if a file path is unsafe (contains directory traversal)
*/
private async restoreLocalStorage(zip: JSZip): Promise<void> {
try {
const localStorageFile = zip.file('localStorage.json');
if (!localStorageFile) return;
const localStorageContent = await localStorageFile.async('text');
const localStorageData = JSON.parse(localStorageContent);
localStorage.clear();
for (const [key, value] of Object.entries(localStorageData)) {
try {
localStorage.setItem(key, value as string);
} catch (error) {
console.warn(`Failed to restore ${key}:`, error);
}
}
} catch (error) {
console.warn('Failed to restore localStorage:', error);
}
}
private isUnsafePath(path: string): boolean {
// Normalize path and check for directory traversal
const normalized = path.replace(/\/+/g, '/');
// Check for directory traversal patterns
@@ -405,7 +318,7 @@ export class FullSystemImporter {
return true;
}
// Check for absolute paths outside of allowed structure
// Check for absolute paths outside allowed structure
if (normalized.startsWith('/') && !normalized.match(/^\/(projects|config|tmp)\//)) {
return true;
}
@@ -413,99 +326,13 @@ export class FullSystemImporter {
return false;
}
/**
* Check if a file path is in a valid directory structure
*/
private isValidFilePath(path: string): boolean {
// Normalize path
const normalized = path.replace(/\/+/g, '/');
// Allow localStorage.json at root level
if (normalized === 'localStorage.json') {
return true;
}
// Check if file is in allowed directories
return normalized.startsWith('projects/') ||
normalized.startsWith('config/') ||
normalized.startsWith('tmp/');
}
/**
* Direct import without temporary filesystem (for tests and simple cases)
*/
private async directImport(zip: JSZip, currentFS: JSRuntimeFS, totalFiles: number): Promise<void> {
// Clear current system
await this.clearCurrentSystem(currentFS);
let filesProcessed = 0;
const files = Object.entries(zip.files);
for (const [relativePath, zipEntry] of files) {
// Validate path security
if (this.isUnsafePath(relativePath)) {
throw new Error(`Unsafe file path: ${relativePath}`);
}
const fullPath = `/${relativePath}`;
if (zipEntry.dir) {
// Create directory
await currentFS.mkdir(fullPath, { recursive: true });
} else {
// Extract file
const content = await zipEntry.async('uint8array');
// Ensure parent directory exists
const dirPath = fullPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await currentFS.mkdir(dirPath, { recursive: true });
}
// Write file
await currentFS.writeFile(fullPath, content);
}
filesProcessed++;
const progress = 30 + (filesProcessed / totalFiles) * 65; // 30-95% range
this.reportProgress('replacing', progress, `Importing files... (${filesProcessed}/${totalFiles})`, filesProcessed, totalFiles);
}
}
/**
* Restore localStorage data from the ZIP
*/
private async restoreLocalStorage(zip: JSZip): Promise<void> {
try {
const localStorageFile = zip.file('localStorage.json');
if (!localStorageFile) {
// No localStorage data in export, skip restoration
return;
}
const localStorageContent = await localStorageFile.async('text');
const localStorageData = JSON.parse(localStorageContent) as Record<string, string>;
// Clear current localStorage
localStorage.clear();
// Restore localStorage data
for (const [key, value] of Object.entries(localStorageData)) {
try {
localStorage.setItem(key, value);
} catch (error) {
console.warn(`Failed to restore localStorage key "${key}":`, error);
}
}
} catch (error) {
console.warn('Failed to restore localStorage data:', error);
// Don't fail the entire import if localStorage restoration fails
}
}
/**
* Report progress to callback
*/
private reportProgress(stage: ImportProgress['stage'], progress: number, message: string, filesProcessed?: number, totalFiles?: number): void {
if (this.onProgress) {
this.onProgress({
@@ -519,9 +346,7 @@ export class FullSystemImporter {
}
}
/**
* Convenience function to import a full system
*/
// Convenience functions
export async function importFullSystem(
zipFile: File,
currentFS: JSRuntimeFS,
@@ -531,9 +356,6 @@ export async function importFullSystem(
await importer.importFullSystem(zipFile, currentFS);
}
/**
* Convenience function to validate an export file
*/
export async function validateExportFile(zipFile: File): Promise<ImportValidation> {
const importer = new FullSystemImporter();
return await importer.validateExport(zipFile);