SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
fix localstorage connector
Ahmed Essam92c43778e45a
diff --git a/.gitignore b/.gitignoreindex 49611e4b..302e58f2 100644--- a/.gitignore+++ b/.gitignore@@ -1,4 +1,5 @@_data+uploads.cursor# Logslogsdiff --git a/.vscode/launch.json b/.vscode/launch.jsonindex 3b9542be..ea3de4c4 100644--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -6,7 +6,7 @@"request": "launch","name": "SmythOS UI Backend","skipFiles": ["<node_internals>/**"],- "preLaunchTask": "cd ${workspaceFolder}/packages/app && npm run bundle:backend",+ "preLaunchTask": "cd ${workspaceFolder}/packages/app && pnpm run bundle:backend","program": "${workspaceFolder}/packages/app/dist/server/index.js","outFiles": ["${workspaceFolder}/packages/app/dist/server/**/*.js"],"sourceMap": true,diff --git a/packages/app/src/backend/index.ts b/packages/app/src/backend/index.tsindex 4d9fa1f0..0888eb3a 100644--- a/packages/app/src/backend/index.ts+++ b/packages/app/src/backend/index.ts@@ -45,6 +45,7 @@ app.use(maintenanceCheckMiddleware);app.use(compression());app.use('/', express.static('dist/static'));app.use('/assets', express.static('dist/assets'));+app.use('/uploads', express.static('uploads'));app.get('/health', (_, res) => {return res.status(200).send({diff --git a/packages/app/src/backend/services/storage/LocalStorage.class.ts b/packages/app/src/backend/services/storage/LocalStorage.class.tsindex fcfd976c..f4651158 100644--- a/packages/app/src/backend/services/storage/LocalStorage.class.ts+++ b/packages/app/src/backend/services/storage/LocalStorage.class.ts@@ -32,16 +32,32 @@ export default class LocalStorage implements StaticStorage {constructor(protected readonly accessControl: StorageACL) {// Base storage path from config or default to user data directory- this.storagePath = appConfig.env.DATA_PATH || path.join(process.cwd(), 'data');- this.publicPath = path.join(this.storagePath, StorageACL.PublicRead);- this.privatePath = path.join(this.storagePath, StorageACL.Private);+ this.storagePath = path.join('uploads');+ this.publicPath = path.join(this.storagePath, 'public');+ this.privatePath = path.join(this.storagePath, 'private');- // Ensure directories exist- this.ensureDirectoriesExist();+ // Ensure directories exist synchronously during initialization+ this.ensureDirectoriesExistSync();}/**- * Ensures that the required storage directories exist+ * Ensures that the required storage directories exist (synchronous version for constructor)+ */+ private ensureDirectoriesExistSync(): void {+ try {+ fs.mkdirSync(this.storagePath, { recursive: true });+ fs.mkdirSync(this.publicPath, { recursive: true });+ fs.mkdirSync(this.privatePath, { recursive: true });++ logger.info('Storage directories created successfully');+ } catch (error) {+ logger.error('Failed to create storage directories:', error);+ throw error;+ }+ }++ /**+ * Ensures that the required storage directories exist (async version)*/private async ensureDirectoriesExist(): Promise<void> {try {@@ -66,8 +82,13 @@ export default class LocalStorage implements StaticStorage {*/private getFilePath(key: string): string {// Sanitize the key to prevent directory traversal attacks+ // Remove any ../ patterns and leading slashesconst sanitizedKey = key.replace(/\.\.\//g, '').replace(/^\//, '');- return path.join(this.getBasePath(), sanitizedKey);+ const fullPath = path.join(this.getBasePath(), sanitizedKey);++ logger.info(`Path mapping: ${key} -> ${sanitizedKey} -> ${fullPath}`);++ return fullPath;}/**@@ -117,38 +138,182 @@ export default class LocalStorage implements StaticStorage {}}+ /**+ * Gets file extension from MIME type+ */+ private getExtensionFromMimeType(mimeType: string): string {+ const mimeToExt: { [key: string]: string } = {+ // Images+ 'image/jpeg': '.jpg',+ 'image/jpg': '.jpg',+ 'image/png': '.png',+ 'image/gif': '.gif',+ 'image/webp': '.webp',+ 'image/svg+xml': '.svg',+ 'image/bmp': '.bmp',+ 'image/tiff': '.tiff',+ 'image/tif': '.tif',+ 'image/ico': '.ico',+ 'image/x-icon': '.ico',++ // Documents+ 'application/pdf': '.pdf',+ 'application/msword': '.doc',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',+ 'application/vnd.ms-excel': '.xls',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',+ 'application/vnd.ms-powerpoint': '.ppt',+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',++ // Text+ 'text/plain': '.txt',+ 'text/html': '.html',+ 'text/css': '.css',+ 'text/javascript': '.js',+ 'text/csv': '.csv',++ // Data+ 'application/json': '.json',+ 'application/xml': '.xml',+ 'application/zip': '.zip',+ 'application/x-rar-compressed': '.rar',+ 'application/x-7z-compressed': '.7z',++ // Video+ 'video/mp4': '.mp4',+ 'video/webm': '.webm',+ 'video/ogg': '.ogv',+ 'video/avi': '.avi',+ 'video/mov': '.mov',+ 'video/wmv': '.wmv',++ // Audio+ 'audio/mpeg': '.mp3',+ 'audio/wav': '.wav',+ 'audio/ogg': '.ogg',+ 'audio/m4a': '.m4a',+ 'audio/flac': '.flac',+ };++ return mimeToExt[mimeType.toLowerCase()] || '';+ }+/*** Creates a multer middleware for file uploads*/public createUploadMw({ key, purge, limits, fileFilter }: CreateUploadMwParams): multer.Multer {+ // Store the key and file info for each request to make it available later+ const requestStorage = new Map();+const storage = multer.diskStorage({- destination: (req, file, cb) => {- cb(null, this.getBasePath());+ destination: async (req, file, cb) => {+ try {+ const fileName = typeof key === 'function' ? key(req, file) : key;+ const baseFileName = fileName || this.generateUniqueKey(file.originalname);++ // Get proper extension from MIME type+ const extension = this.getExtensionFromMimeType(file.mimetype);++ // Create final filename with extension+ const finalFileName =+ extension && !baseFileName.toLowerCase().endsWith(extension.toLowerCase())+ ? baseFileName + extension+ : baseFileName;++ // Store the final filename and file info for this request+ requestStorage.set(req, {+ finalFileName,+ mimetype: file.mimetype,+ originalname: file.originalname,+ });++ logger.info(`File upload destination prepared:`, {+ originalKey: fileName,+ baseFileName,+ mimetype: file.mimetype,+ extension,+ finalFileName,+ });++ // Get the full file path and extract directory+ const filePath = this.getFilePath(finalFileName);+ const dirPath = path.dirname(filePath);++ // Ensure the directory exists+ await fsPromises.mkdir(dirPath, { recursive: true });++ cb(null, dirPath);+ } catch (error) {+ cb(error as Error, '');+ }},filename: (req, file, cb) => {try {- const fileName = typeof key === 'function' ? key(req, file) : key;- const finalFileName = fileName || this.generateUniqueKey(file.originalname);+ // Retrieve the data we stored earlier+ const storedData = requestStorage.get(req);++ if (!storedData) {+ throw new Error('Unable to retrieve file data');+ }++ // Extract just the filename part (not the full path)+ const justFileName = path.basename(storedData.finalFileName);// Set up purge timeout if specifiedif (purge) {- const filePath = path.join(this.getBasePath(), finalFileName);+ const filePath = this.getFilePath(storedData.finalFileName);// Delay the purge setup to ensure file is created firstsetTimeout(() => this.setupPurgeTimeout(filePath, purge), 1000);}- cb(null, finalFileName);+ logger.info(`File upload filename set:`, {+ originalname: file.originalname,+ mimetype: file.mimetype,+ storedFileName: storedData.finalFileName,+ diskFileName: justFileName,+ });++ cb(null, justFileName);} catch (error) {cb(error as Error, '');}},});- return multer({+ const upload = multer({storage,limits,fileFilter,});++ // Wrap the multer middleware to add the key to the file object+ return {+ ...upload,+ single: (fieldName: string) => {+ const singleMiddleware = upload.single(fieldName);+ return (req, res, next) => {+ singleMiddleware(req, res, (err) => {+ if (err) return next(err);++ // Add the key property to the file object if file was uploaded+ if (req.file && requestStorage.has(req)) {+ const storedData = requestStorage.get(req);+ (req.file as any).key = storedData.finalFileName;++ // Clean up the stored data+ requestStorage.delete(req);+ }++ next();+ });+ };+ },+ // Add other multer methods if needed+ array: upload.array,+ fields: upload.fields,+ none: upload.none,+ any: upload.any,+ } as multer.Multer;}/**@@ -171,9 +336,18 @@ export default class LocalStorage implements StaticStorage {try {const filePath = this.getFilePath(key);+ const dirPath = path.dirname(filePath);// Ensure directory exists- await fsPromises.mkdir(path.dirname(filePath), { recursive: true });+ await fsPromises.mkdir(dirPath, { recursive: true });++ // Verify directory was created+ try {+ await fsPromises.access(dirPath);+ } catch (accessError) {+ logger.error(`Directory creation failed: ${dirPath}`, accessError);+ throw new Error(`Failed`);+ }// Convert body to buffer if it's a stringconst buffer = typeof body === 'string' ? Buffer.from(body) : body;@@ -186,14 +360,13 @@ export default class LocalStorage implements StaticStorage {this.setupPurgeTimeout(filePath, purge);}- logger.info(`File successfully saved: ${filePath}`);-return {success: true,url: this.getPublicUrl(key),};} catch (error) {logger.error(`Error saving file with key ${key}:`, error);+throw error;}}@@ -215,8 +388,6 @@ export default class LocalStorage implements StaticStorage {// Delete the fileawait fsPromises.unlink(filePath);- logger.info(`File successfully deleted: ${filePath}`);-return { success: true };} catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') {@@ -225,7 +396,6 @@ export default class LocalStorage implements StaticStorage {return { success: true };}- logger.error(`Error deleting file with key ${key}:`, error);throw error;}}@@ -234,17 +404,20 @@ export default class LocalStorage implements StaticStorage {* Generates a public URL for accessing the file*/public getPublicUrl(key: string): string {+ if (!key || typeof key !== 'string') {+ throw new Error('Key is required and must be a non-empty string for URL generation.');+ }+if (this.accessControl === StorageACL.Private) {throw new Error('Private files are not accessible via public URL.');}- const accessPath = StorageACL.PublicRead;const baseUrl = appConfig.env.UI_SERVER || `http://localhost:${appConfig.env.PORT || 3000}`;// Remove leading slash from key if presentconst cleanKey = key.replace(/^\//, '');- return `${baseUrl}/static/${accessPath}/${cleanKey}`;+ return `${baseUrl}/uploads/public/${cleanKey}`;}/**@@ -267,7 +440,7 @@ export default class LocalStorage implements StaticStorage {}async getStream(key: string, options?: { range?: string }) {- const filePath = path.join(this.getBasePath(), key);+ const filePath = this.getFilePath(key);if (options?.range) {const [startStr, endStr] = options.range.replace(/bytes=/, '').split('-');const start = parseInt(startStr, 10);diff --git a/packages/app/src/backend/services/storage/README.md b/packages/app/src/backend/services/storage/README.mddeleted file mode 100644index 866adc24..00000000--- a/packages/app/src/backend/services/storage/README.md+++ /dev/null@@ -1,163 +0,0 @@-# Storage Services Documentation--This directory contains storage service implementations for handling file uploads and management.--## Available Storage Implementations--### S3Storage-- **Purpose**: AWS S3 cloud storage-- **Use case**: Production environments with cloud infrastructure-- **Features**: Cloud storage, automatic scaling, lifecycle management via AWS--### LocalStorage-- **Purpose**: Local file system storage-- **Use case**: Development, testing, or self-hosted deployments-- **Features**: Local file storage, automatic directory creation, built-in purge policies--## Usage--The storage system uses a factory pattern that automatically selects the appropriate storage implementation based on configuration:--```typescript-import { publicStorage, privateStorage } from '@src/backend/services/storage';--// The storage implementation is automatically selected based on environment variables-// - S3Storage when PUBLIC_STORAGE_DRIVER=s3-// - LocalStorage otherwise (default)-```--### Configuration--#### For S3Storage-Set the following environment variables:-```env-PUBLIC_STORAGE_DRIVER=s3-AWS_ACCESS_KEY_ID=your_access_key-AWS_SECRET_ACCESS_KEY=your_secret_key-AWS_S3_BUCKET_NAME=your_private_bucket-AWS_S3_PUB_BUCKET_NAME=your_public_bucket-AWS_S3_REGION=us-east-1-AWS_S3_PUB_REGION=us-east-1-```--#### For LocalStorage-Set the data path (optional):-```env-DATA_PATH=/path/to/storage/directory-# If not set, defaults to ~/smyth-ui-data-```--### Storage Structure--When using LocalStorage, files are organized as follows:-```-{DATA_PATH}/-├── public/ # Files accessible via public URLs-│ └── uploads/-└── private/ # Protected files (require authentication)- └── internal/-```--### File Upload Example--```typescript-import { publicStorage } from '@src/backend/services/storage';--// Create upload middleware-const uploadMw = publicStorage.createUploadMw({- key: (req, file) => `uploads/${Date.now()}-${file.originalname}`,- purge: 'DAILY', // Auto-delete after 24 hours- limits: {- fileSize: 10 * 1024 * 1024, // 10MB limit- },- fileFilter: (req, file, cb) => {- // Accept images only- if (file.mimetype.startsWith('image/')) {- cb(null, true);- } else {- cb(new Error('Only image files are allowed'));- }- },-});--// Use in route-app.post('/upload', uploadMw.single('file'), (req, res) => {- const publicUrl = publicStorage.getPublicUrl(req.file.filename);- res.json({ url: publicUrl });-});-```--### Direct File Operations--```typescript-// Save content directly-const result = await publicStorage.saveContent({- key: 'documents/report.pdf',- body: pdfBuffer,- contentType: 'application/pdf',- purge: 'WEEKLY', // Auto-delete after 7 days-});--console.log('File saved:', result.url);--// Delete content-await publicStorage.deleteContent({- key: 'documents/report.pdf',-});-```--### Purge Policies--Both storage implementations support automatic cleanup:--- **DAILY**: Files are deleted after 24 hours-- **WEEKLY**: Files are deleted after 7 days-- **MONTHLY**: Files are deleted after 30 days--For S3Storage, this uses AWS lifecycle policies.-For LocalStorage, this uses Node.js timers for cleanup.--### URL Generation--```typescript-// Generate public URL for a stored file-const publicUrl = publicStorage.getPublicUrl('uploads/image.jpg');-// LocalStorage: http://localhost:3000/static/public/uploads/image.jpg-// S3Storage: https://your-bucket.s3.amazonaws.com/uploads/image.jpg-```--### Security Features--#### LocalStorage Security-- **Path Traversal Protection**: Automatically sanitizes file keys to prevent `../` attacks-- **Directory Isolation**: Public and private files are stored in separate directories-- **Access Control**: Private storage requires authentication middleware--#### S3Storage Security-- **IAM Policies**: Uses AWS IAM for access control-- **Bucket Policies**: Separate buckets for public and private content-- **Encryption**: Supports server-side encryption--## Migration--### From S3 to Local-1. Set `PUBLIC_STORAGE_DRIVER` to empty or remove it-2. Ensure `DATA_PATH` is configured-3. Restart the application--### From Local to S3-1. Set `PUBLIC_STORAGE_DRIVER=s3`-2. Configure AWS credentials-3. Restart the application--## Monitoring and Cleanup--### LocalStorage-- Files are automatically organized by access control-- Purge jobs run automatically based on policy-- Call `localStorage.cleanup()` on application shutdown to clear pending timers--### S3Storage-- Uses AWS CloudWatch for monitoring-- Lifecycle policies handle automatic cleanup-- No manual cleanup required