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
feat(storage): add adaptor
Ahmed Essam9625b808fb68
diff --git a/packages/app/package.json b/packages/app/package.jsonindex 6ddd4360..7218a956 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -92,7 +92,6 @@"markdown-it": "^14.1.0","markdown-it-attrs": "^4.3.1","multer": "^1.4.5-lts.1",- "multer-s3": "^3.0.1","node-cache": "^5.1.2","oauth": "^0.10.0","oauth-1.0a": "^2.2.6",@@ -149,7 +148,6 @@"@types/he": "^1.2.1","@types/lodash-es": "^4.17.12","@types/multer": "^1.4.7",- "@types/multer-s3": "^3.0.0","@types/node": "^20.4.1","@types/papaparse": "^5.3.14","@types/react": "^18.2.23",diff --git a/packages/app/src/backend/lib/s3.ts b/packages/app/src/backend/lib/s3.tsdeleted file mode 100644index a1498613..00000000--- a/packages/app/src/backend/lib/s3.ts+++ /dev/null@@ -1,19 +0,0 @@-import { S3Client, S3 } from '@aws-sdk/client-s3';-import config from '../config';-const s3Client = new S3Client({- region: config.env.AWS_S3_REGION,- credentials: {- accessKeyId: config.env.AWS_ACCESS_KEY_ID,- secretAccessKey: config.env.AWS_SECRET_ACCESS_KEY,- },-});--const abstractedS3Client = new S3({- region: config.env.AWS_S3_REGION,- credentials: {- accessKeyId: config.env.AWS_ACCESS_KEY_ID,- secretAccessKey: config.env.AWS_SECRET_ACCESS_KEY,- },-});--export { s3Client, abstractedS3Client };diff --git a/packages/app/src/backend/routes/api/page/agent-settings.ts b/packages/app/src/backend/routes/api/page/agent-settings.tsindex e91060cb..2be93bcb 100644--- a/packages/app/src/backend/routes/api/page/agent-settings.ts+++ b/packages/app/src/backend/routes/api/page/agent-settings.ts@@ -1,15 +1,20 @@+import { assetStorage } from '@src/backend/services/storage';import { randomUUID } from 'crypto';import express, { Request } from 'express';import { rateLimit } from 'express-rate-limit';import { generateLinkedInAvatarPrompt } from '../../../../shared/constants/prompts';import { includeTeamDetails } from '../../../middlewares/auth.mw';import * as falai from '../../../services/falai-helper';-import SmythPubStaticStorage from '../../../services/storage/SmythStaticStorage.class';import * as userData from '../../../services/user-data.service';import { getAgents } from '../../../services/user-data.service';-import { authHeaders, forwardToSmythAPIMiddleware, smythAPIReq } from '../../../utils';+import {+ authHeaders,+ forwardToSmythAPIMiddleware,+ md5Hash,+ posixPath,+ smythAPIReq,+} from '../../../utils';const router = express.Router();-const staticStorage = new SmythPubStaticStorage();// routes for dynamic content goes here@@ -129,13 +134,8 @@ router.put('/release-lock', async (req, res) => {res.send({ success: true });});-const uploadAvatarMw = staticStorage.getMulter({- key: (req, file) =>- SmythPubStaticStorage.path(- 'teams',- SmythPubStaticStorage.hash(req._team.id),- `avatar-${randomUUID()}`,- ),+const uploadAvatarMw = assetStorage.createUploadMw({+ key: (req, file) => posixPath('teams', md5Hash(req._team.id), `avatar-${randomUUID()}`),limits: {fileSize: 1024 * 1024 * 15, // 15MB},@@ -157,7 +157,7 @@ router.post(// @ts-ignoreconst key = req.file.key;- const publicUrl = staticStorage.getPublicUrl(key);+ const publicUrl = assetStorage.getPublicUrl(key);// save the avatar in the agent settingsawait smythAPIReq.put(@@ -192,12 +192,8 @@ router.post(prompt: generateLinkedInAvatarPrompt(),});- const key = SmythPubStaticStorage.path(- 'teams',- SmythPubStaticStorage.hash(req._team.id),- `avatar-${randomUUID()}`,- );- const uploaded = await staticStorage.saveContent({+ const key = posixPath('teams', md5Hash(req._team.id), `avatar-${randomUUID()}`);+ const uploaded = await assetStorage.saveContent({key,contentType: 'image/png',body: Buffer.from(base64Image, 'base64'),diff --git a/packages/app/src/backend/routes/api/page/chat.ts b/packages/app/src/backend/routes/api/page/chat.tsindex 9a3739ec..7044f467 100644--- a/packages/app/src/backend/routes/api/page/chat.ts+++ b/packages/app/src/backend/routes/api/page/chat.ts@@ -1,13 +1,12 @@+import { assetStorage } from '@src/backend/services/storage';import axios from 'axios';import { randomUUID } from 'crypto';import express from 'express';import config from '../../../config';import { includeTeamDetails } from '../../../middlewares/auth.mw';-import SmythPubStaticStorage from '../../../services/storage/SmythStaticStorage.class';-import { authHeaders, includeAxiosAuth, smythAPIReq } from '../../../utils';+import { authHeaders, includeAxiosAuth, md5Hash, posixPath, smythAPIReq } from '../../../utils';const router = express.Router();-const staticStorage = new SmythPubStaticStorage();const isUsingLocalServer = false;@@ -23,14 +22,9 @@ function getAgentServerURL(agentId: string, isLocal = false) {router.use([includeTeamDetails]); // is it ok?// Configure multer middleware for file uploads-const uploadFileMw = staticStorage.getMulter({+const uploadFileMw = assetStorage.createUploadMw({purge: 'DAILY',- key: (req, file) =>- SmythPubStaticStorage.path(- 'teams',- SmythPubStaticStorage.hash(req._team.id),- `file-${randomUUID()}`,- ),+ key: (req, file) => posixPath('teams', md5Hash(req._team.id), `file-${randomUUID()}`),limits: {fileSize: 1024 * 1024 * 20, // 20MB limit},@@ -72,7 +66,7 @@ router.post('/stream', async (req, res) => {const agentId = req.headers['x-agent-id'];const conversationId = req.headers['x-conversation-id'];const isAgentChat = req.headers['x-ai-agent'] === 'true';- const filePublicUrls = fileKeys.map((key) => staticStorage.getPublicUrl(key));+ const filePublicUrls = fileKeys.map((key) => assetStorage.getPublicUrl(key));if (filePublicUrls.length > 0) {message = [message, '###', 'Attachments:', ...filePublicUrls.map((url) => `- ${url}`)].join(@@ -229,7 +223,7 @@ router.post('/upload', [includeTeamDetails, uploadFileMw.single('file')], asynctry {// @ts-ignoreconst key = req.file.key;- const publicUrl = staticStorage.getPublicUrl(key);+ const publicUrl = assetStorage.getPublicUrl(key);return res.json({success: true,@@ -253,7 +247,7 @@ router.delete('/deleteFile', [includeTeamDetails], async (req, res) => {}try {- await staticStorage.deleteObject(key as string);+ await assetStorage.deleteContent({ key });return res.json({ success: true });} catch (error) {console.error('Error deleting file:', error);diff --git a/packages/app/src/backend/routes/api/page/logs.ts b/packages/app/src/backend/routes/api/page/logs.tsindex 26bf09d3..6653c2e7 100644--- a/packages/app/src/backend/routes/api/page/logs.ts+++ b/packages/app/src/backend/routes/api/page/logs.ts@@ -1,16 +1,9 @@+// TODO: move to enterprise app++import { privateStorage } from '@src/backend/services/storage';import express from 'express';-import path from 'path';-import fs from 'fs';-import config from '../../../config';-import { authHeaders, includeAxiosAuth, smythAPI } from '../../../utils';-import { AxiosError } from 'axios';-import {- checkObjectOwnership,- extractObjectKeyFromUrl,- getObjectDataByKey,- isStorageFile,-} from '../../../utils/storage.utils';-import { Team } from '../../../types';+import { authHeaders, smythAPI } from '../../../utils';+import { checkObjectOwnership } from '../../../utils/storage.utils';const router = express.Router();router.get('/:agentId', async (req, res) => {@@ -158,4 +151,50 @@ async function getSessions(req, agentId, token, page = 1, limit = 10) {}}+async function getObjectDataByKey(key: string) {+ // return new Promise(async (resolve, reject) => {+ // try {+ // const response: any = await abstractedS3Client.getObject({+ // Bucket: config.env.AWS_S3_BUCKET_NAME,+ // Key: key,+ // });+ // const request = response.Body;+ // let dataChunks = [];++ // // Listen for data events to collect the chunks+ // request.on('data', (chunk) => {+ // dataChunks.push(chunk);+ // });++ // // Handle the end of the stream and convert the chunks to a string+ // request.on('end', () => {+ // const completeData = Buffer.concat(dataChunks);+ // const bodyContent = completeData.toString('utf-8');+ // resolve(bodyContent);+ // });++ // // Error handling for the stream+ // request.on('error', (error) => {+ // console.error('Error reading the S3 object stream:', error);+ // reject(error);+ // });+ // } catch (error) {+ // reject(error);+ // }+ // });++ const stream = await privateStorage.getStream(key);++ return new Promise<string>((resolve, reject) => {+ const chunks: Buffer[] = [];++ stream.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));+ stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));+ stream.on('error', (error) => {+ console.error('Error reading the Log verbose content object stream:', error);+ reject('Error reading the Log verbose content object stream');+ });+ });+}+export default router;diff --git a/packages/app/src/backend/routes/api/upload/datasource.upload.ts b/packages/app/src/backend/routes/api/upload/datasource.upload.tsindex ccc95753..3887b763 100644--- a/packages/app/src/backend/routes/api/upload/datasource.upload.ts+++ b/packages/app/src/backend/routes/api/upload/datasource.upload.ts@@ -1,51 +1,24 @@-import { RequestHandler, Router } from 'express';-import multer, { StorageEngine } from 'multer';-import { includeAxiosAuth, smythAPIReq } from '../../../utils';-import fs from 'fs';-import { promisify } from 'util';-import { S3Client } from '@aws-sdk/client-s3';-import multerS3 from 'multer-s3';-import { s3Client, abstractedS3Client } from '../../../lib/s3';-import { v4 as uuidv4 } from 'uuid';+import { privateStorage } from '@src/backend/services/storage';+import { StorageACL } from '@src/backend/services/storage/StaticStorage';import crypto from 'crypto';-import config from '../../../config';+import { Router } from 'express';+import { v4 as uuidv4 } from 'uuid';import { includeTeamDetails } from '../../../middlewares/auth.mw';-import {- checkObjectOwnership,- extractObjectKeyFromUrl,- isStorageFile,-} from '../../../utils/storage.utils';+import { checkObjectOwnership } from '../../../utils/storage.utils';-const uploadRouter = Router();+// FILE SHOULD BE RELOCATED TO ENTERPRISE APP+// TODO: TEST:STORAGE-const storage: StorageEngine = multerS3({- s3: s3Client,- bucket: config.env.AWS_S3_BUCKET_NAME,- acl: 'private',- contentType: multerS3.AUTO_CONTENT_TYPE,+const uploadRouter = Router();- metadata: (req, file, cb) => {- cb(null, {- // @ts-ignore- userId: String(req._team.userId),- // @ts-ignore- teamId: String(req._team.id),- mimetype: file?.mimetype,- });+const uploadMw = privateStorage.createUploadMw({+ purge: 'DAILY',+ acl: StorageACL.Private,+ limits: {+ fileSize: 1024 * 1024 * 100, // 100MB},- key: async (req, file, cb) => {- // fetch team id from smyth api- // let teamId: number;- // try {- // // @ts-ignore- // const token = req.user.accessToken;- // teamId = (await smythAPIReq.get('/teams/me', includeAxiosAuth(token))).data.team.id;- // } catch (error) {- // cb(new Error('Internal Server Error'), null);- // }-- //@ts-ignore+ key: (req, file) => {const teamId = req._team.id;const uniquePart = uuidv4();@@ -54,28 +27,36 @@ const storage: StorageEngine = multerS3({.update(file.originalname + Date.now().toString()).digest('hex');- cb(null, `/datasources/teams/${teamId}/${hashedFilename}-${uniquePart}`);+ return `/datasources/teams/${teamId}/${hashedFilename}-${uniquePart}`;},-});-const upload = multer({- storage: storage,- limits: {- fileSize: 1024 * 1024 * 100, // 100MB+ metadata: (req, file) => {+ return {+ // @ts-ignore+ userId: String(req._team.userId),+ // @ts-ignore+ teamId: String(req._team.id),+ mimetype: file?.mimetype,+ };},});-uploadRouter.put('/uploads/datasources', includeTeamDetails, upload.single('file'), (req, res) => {- if (!req.file) {- return res.status(400).json({ error: 'Internal Server Error' });- }- res.json({- file: {- // @ts-ignore- key: req.file.key,- },- });-});+uploadRouter.put(+ '/uploads/datasources',+ includeTeamDetails,+ uploadMw.single('file'),+ (req, res) => {+ if (!req.file) {+ return res.status(400).json({ error: 'Internal Server Error' });+ }+ res.json({+ file: {+ // @ts-ignore+ key: req.file.key,+ },+ });+ },+);// maybe this endpoint is not necessary since the object will be deleted (S3 lifecycle)?uploadRouter.delete('/uploads/datasources', includeTeamDetails, async (req, res) => {@@ -97,9 +78,9 @@ uploadRouter.delete('/uploads/datasources', includeTeamDetails, async (req, res)}try {- const result = await abstractedS3Client.deleteObject({- Key: key,- Bucket: config.env.AWS_S3_BUCKET_NAME,+ await privateStorage.deleteContent({ key }).catch((e) => {+ console.error('Failed to delete datasource file', e);+ throw new Error('Failed to delete file');});res.json({ message: 'success' });diff --git a/packages/app/src/backend/routes/dbg/router.ts b/packages/app/src/backend/routes/dbg/router.tsindex bc4eb535..adebdbcf 100644--- a/packages/app/src/backend/routes/dbg/router.ts+++ b/packages/app/src/backend/routes/dbg/router.ts@@ -1,16 +1,11 @@-import {- GetObjectCommand,- GetObjectCommandInput,- HeadObjectCommand,- S3Client,-} from '@aws-sdk/client-s3';import axios from 'axios';import express from 'express';-import { pipeline, Readable } from 'stream';+import { pipeline } from 'stream';import { promisify } from 'util';import config from '../../config';+import { privateStorage } from '@src/backend/services/storage';import { createProxyMiddleware, Options } from 'http-proxy-middleware';import { includeTeamDetails } from '../../middlewares/auth.mw';const router = express.Router();@@ -173,7 +168,9 @@ const createSSEProxyOptions: (targetUrl: string) => Options = (targetUrl: string// Replace the existing SSE proxy route with the new implementationrouter.use('/sse', createProxyMiddleware(createSSEProxyOptions(config.env.API_SERVER)));-// TODO: refactor file-proxy implementation+// TODO: should be moved to any SRE server+//! FIX: but this will not work with self-hosted env since SRE is not guranteed to store in S3 and so this+//! needs to be reloacted to the debugger serverrouter.get('/file-proxy', includeTeamDetails, async (req, res) => {const { url } = req.query as { url: string };@@ -208,65 +205,47 @@ router.get('/file-proxy', includeTeamDetails, async (req, res) => {const rangeHeader = req.headers.range;let s3Range: string | undefined;let statusCode = 200;- let contentLength: number | undefined;+ let streamOptions: { range?: string } = {};if (rangeHeader) {- const s3Client = new S3Client({- region: config.env.AWS_S3_REGION,- credentials: {- accessKeyId: config.env.AWS_ACCESS_KEY_ID,- secretAccessKey: config.env.AWS_SECRET_ACCESS_KEY,- },- });+ // Get file size from S3 metadata (assuming we are in SaaS so SRE would store the data in S3)- // Get file size from S3 metadata- const headCommand = new HeadObjectCommand({- Bucket: config.env.AWS_S3_BUCKET_NAME,- Key: resourceId,- });- const headResponse = await s3Client.send(headCommand);- const fileSize = headResponse.ContentLength;+ const meta = await privateStorage.stat(resourceId);+ const fileSize = meta.size;- if (fileSize) {- const parts = rangeHeader.replace(/bytes=/, '').split('-');- const start = parseInt(parts[0], 10);- const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;+ const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-');+ const start = parseInt(startStr, 10);+ const end = endStr ? parseInt(endStr, 10) : fileSize - 1;- if (start >= fileSize || end >= fileSize) {- res.setHeader('Content-Range', `bytes */${fileSize}`);- return res.status(416).send('Requested Range Not Satisfiable');- }+ if (start >= fileSize || end >= fileSize) {+ res.setHeader('Content-Range', `bytes */${fileSize}`);+ return res.status(416).send('Requested Range Not Satisfiable');+ }- const chunkSize = end - start + 1;- s3Range = `bytes=${start}-${end}`;- statusCode = 206;- contentLength = chunkSize;+ const chunkSize = end - start + 1;+ streamOptions.range = `bytes=${start}-${end}`;+ statusCode = 206;- res.setHeader('Content-Range', `bytes ${start}-${end}/${fileSize}`);- res.setHeader('Content-Length', chunkSize);- }+ res.setHeader('Content-Range', `bytes ${start}-${end}/${fileSize}`);+ res.setHeader('Content-Length', chunkSize);}- // Get the S3 stream with the appropriate range- const s3Stream = await getS3Stream(resourceId, s3Range);+ // Stream via generic adapter+ const fileStream = await privateStorage.getStream(resourceId, streamOptions);// Handle 'close' event to clean up if client disconnects- res.on('close', () => {- s3Stream.destroy();- });+ res.on('close', () => (fileStream as any)?.destroy?.());// Set the status coderes.status(statusCode);// Stream the file from S3- await pipelineAsync(s3Stream, res);+ await pipelineAsync(fileStream, res);} catch (error: any) {- if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {- console.error('Error streaming file from S3:', error);- if (!res.headersSent) {- res.status(500).send('Error streaming file');- }- }+ // if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {+ console.error('Error streaming file:', error);+ if (!res.headersSent) res.status(500).send('Error streaming file');+ // }}});@@ -287,47 +266,6 @@ function URIParser(uri: string) {};}-/**- * Reads a file from S3 bucket and returns a readable stream- * @param {string} resourceId - The full path of the S3 object (e.g., 'teams/team-id/path/to/file')- * @param {string} [range] - The byte range to retrieve from S3 (e.g., 'bytes=0-1023')- * @returns {Promise<Readable>} A readable stream of the S3 object- * @throws {Error} If the object cannot be retrieved from S3- */-async function getS3Stream(resourceId: string, range?: string): Promise<Readable> {- const s3Client = new S3Client({- region: config.env.AWS_S3_REGION,- credentials: {- accessKeyId: config.env.AWS_ACCESS_KEY_ID,- secretAccessKey: config.env.AWS_SECRET_ACCESS_KEY,- },- });-- const commandParams: GetObjectCommandInput = {- Bucket: config.env.AWS_S3_BUCKET_NAME,- Key: resourceId,- };-- if (range) {- commandParams.Range = range;- }-- const command = new GetObjectCommand(commandParams);-- try {- const response = await s3Client.send(command);-- if (!response.Body) {- throw new Error('No data returned from S3');- }-- return response.Body as Readable;- } catch (error: any) {- console.error('Error reading from S3:', error);- throw new Error(`Failed to read file from S3: ${error.message}`);- }-}-/*** Get content type based on file extension*/diff --git a/packages/app/src/backend/services/falai-helper.ts b/packages/app/src/backend/services/falai-helper.tsindex 246b6283..b1bc02f1 100644--- a/packages/app/src/backend/services/falai-helper.ts+++ b/packages/app/src/backend/services/falai-helper.ts@@ -1,15 +1,14 @@import * as fal from '@fal-ai/serverless-client';+import { randomUUID } from 'crypto';+import { generateLinkedInAvatarPrompt } from '../../shared/constants/prompts';import config from '../config';import {AGENT_AVATAR_AUTO_GENERATE_IMAGE_HEIGHT,AGENT_AVATAR_AUTO_GENERATE_IMAGE_WIDTH,} from '../constants';-import { generateLinkedInAvatarPrompt } from '../../shared/constants/prompts';-import SmythPubStaticStorage from './storage/SmythStaticStorage.class';-import { randomUUID } from 'crypto';-import { authHeaders, includeAxiosAuth, smythAPIReq } from '../utils';-const staticStorage = new SmythPubStaticStorage();+import { authHeaders, md5Hash, posixPath, smythAPIReq } from '../utils';+import { assetStorage } from './storage';export async function generateImage({prompt,@@ -67,12 +66,8 @@ export async function autoGenerateAvatarForAgent(req, agentId: string, teamId: sprompt: generateLinkedInAvatarPrompt(),});- const avatarStoragePath = SmythPubStaticStorage.path(- 'teams',- SmythPubStaticStorage.hash(teamId),- `avatar-${randomUUID()}`,- );- const uploaded = await staticStorage.saveContent({+ const avatarStoragePath = posixPath('teams', md5Hash(teamId), `avatar-${randomUUID()}`);+ const uploaded = await assetStorage.saveContent({key: avatarStoragePath,contentType: 'image/png',body: Buffer.from(base64Image, 'base64'),diff --git a/packages/app/src/backend/services/storage/LocalStorage.class.ts b/packages/app/src/backend/services/storage/LocalStorage.class.tsnew file mode 100644index 00000000..fcfd976c--- /dev/null+++ b/packages/app/src/backend/services/storage/LocalStorage.class.ts@@ -0,0 +1,279 @@+import crypto from 'crypto';+import fs, { promises as fsPromises } from 'fs';+import multer from 'multer';+import path from 'path';+import appConfig from '../../config';+import {+ CreateUploadMwParams,+ DeleteContentParams,+ FileMetadata,+ SaveContentParams,+ StaticStorage,+ StorageACL,+} from './StaticStorage';++const logger = console;++/**+ * LocalStorage class provides file system-based storage functionality+ * that mirrors S3Storage but stores files locally on the server.+ *+ * Features:+ * - Stores files in public/private directories based on access control+ * - Supports file uploads via multer+ * - Implements purge policies for temporary files+ * - Provides public URL generation for web access+ */+export default class LocalStorage implements StaticStorage {+ private readonly storagePath: string;+ private readonly publicPath: string;+ private readonly privatePath: string;+ private readonly purgeJobsMap: Map<string, NodeJS.Timeout> = new Map();++ 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);++ // Ensure directories exist+ this.ensureDirectoriesExist();+ }++ /**+ * Ensures that the required storage directories exist+ */+ private async ensureDirectoriesExist(): Promise<void> {+ try {+ await fsPromises.mkdir(this.storagePath, { recursive: true });+ await fsPromises.mkdir(this.publicPath, { recursive: true });+ await fsPromises.mkdir(this.privatePath, { recursive: true });+ } catch (error) {+ logger.error('Failed to create storage directories:', error);+ throw error;+ }+ }++ /**+ * Gets the appropriate base path based on access control+ */+ private getBasePath(): string {+ return this.accessControl === StorageACL.PublicRead ? this.publicPath : this.privatePath;+ }++ /**+ * Gets the full file path for a given key+ */+ private getFilePath(key: string): string {+ // Sanitize the key to prevent directory traversal attacks+ const sanitizedKey = key.replace(/\.\.\//g, '').replace(/^\//, '');+ return path.join(this.getBasePath(), sanitizedKey);+ }++ /**+ * Generates a unique key for file uploads when not provided+ */+ private generateUniqueKey(originalName?: string): string {+ const timestamp = Date.now();+ const randomBytes = crypto.randomBytes(8).toString('hex');+ const extension = originalName ? path.extname(originalName) : '';+ return `${timestamp}-${randomBytes}${extension}`;+ }++ /**+ * Sets up purge timeout for temporary files+ */+ private setupPurgeTimeout(filePath: string, purge: 'DAILY' | 'WEEKLY' | 'MONTHLY'): void {+ const purgeDelays = {+ DAILY: 24 * 60 * 60 * 1000, // 24 hours+ WEEKLY: 7 * 24 * 60 * 60 * 1000, // 7 days+ MONTHLY: 30 * 24 * 60 * 60 * 1000, // 30 days+ };++ const delay = purgeDelays[purge];+ if (delay) {+ const timeout = setTimeout(async () => {+ try {+ await fsPromises.unlink(filePath);+ logger.info(`Purged temporary file: ${filePath}`);+ this.purgeJobsMap.delete(filePath);+ } catch (error) {+ logger.error(`Failed to purge file ${filePath}:`, error);+ }+ }, delay);++ this.purgeJobsMap.set(filePath, timeout);+ }+ }++ /**+ * Cancels purge timeout for a file+ */+ private cancelPurgeTimeout(filePath: string): void {+ const timeout = this.purgeJobsMap.get(filePath);+ if (timeout) {+ clearTimeout(timeout);+ this.purgeJobsMap.delete(filePath);+ }+ }++ /**+ * Creates a multer middleware for file uploads+ */+ public createUploadMw({ key, purge, limits, fileFilter }: CreateUploadMwParams): multer.Multer {+ const storage = multer.diskStorage({+ destination: (req, file, cb) => {+ cb(null, this.getBasePath());+ },+ filename: (req, file, cb) => {+ try {+ const fileName = typeof key === 'function' ? key(req, file) : key;+ const finalFileName = fileName || this.generateUniqueKey(file.originalname);++ // Set up purge timeout if specified+ if (purge) {+ const filePath = path.join(this.getBasePath(), finalFileName);+ // Delay the purge setup to ensure file is created first+ setTimeout(() => this.setupPurgeTimeout(filePath, purge), 1000);+ }++ cb(null, finalFileName);+ } catch (error) {+ cb(error as Error, '');+ }+ },+ });++ return multer({+ storage,+ limits,+ fileFilter,+ });+ }++ /**+ * Saves content to a file+ */+ public async saveContent({+ key,+ body,+ contentType,+ purge,+ skipAclCheck,+ }: SaveContentParams): Promise<{ success: boolean; url: string }> {+ if (!key || typeof key !== 'string') {+ throw new Error('The key must be a non-empty string.');+ }++ if (body === undefined || body === null) {+ throw new Error('Body cannot be null or undefined.');+ }++ try {+ const filePath = this.getFilePath(key);++ // Ensure directory exists+ await fsPromises.mkdir(path.dirname(filePath), { recursive: true });++ // Convert body to buffer if it's a string+ const buffer = typeof body === 'string' ? Buffer.from(body) : body;++ // Write file+ await fsPromises.writeFile(filePath, buffer);++ // Set up purge timeout if specified+ if (purge) {+ 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;+ }+ }++ /**+ * Deletes content from storage+ */+ public async deleteContent({ key }: DeleteContentParams): Promise<{ success: boolean }> {+ if (!key || typeof key !== 'string') {+ throw new Error('The key must be a non-empty string.');+ }++ try {+ const filePath = this.getFilePath(key);++ // Cancel any pending purge timeout+ this.cancelPurgeTimeout(filePath);++ // Delete the file+ await fsPromises.unlink(filePath);++ logger.info(`File successfully deleted: ${filePath}`);++ return { success: true };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ // File doesn't exist, consider it successfully deleted+ logger.info(`File not found (already deleted): ${key}`);+ return { success: true };+ }++ logger.error(`Error deleting file with key ${key}:`, error);+ throw error;+ }+ }++ /**+ * Generates a public URL for accessing the file+ */+ public getPublicUrl(key: string): string {+ 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 present+ const cleanKey = key.replace(/^\//, '');++ return `${baseUrl}/static/${accessPath}/${cleanKey}`;+ }++ /**+ * Cleanup method to clear all purge timeouts (useful for shutdown)+ */+ public cleanup(): void {+ for (const [filePath, timeout] of this.purgeJobsMap.entries()) {+ clearTimeout(timeout);+ logger.info(`Cancelled purge timeout for: ${filePath}`);+ }+ this.purgeJobsMap.clear();+ }++ async stat(key: string): Promise<FileMetadata> {+ const stats = await fs.promises.stat(this.getFilePath(key));+ return {+ size: stats.size,+ lastModified: stats.mtime,+ };+ }++ async getStream(key: string, options?: { range?: string }) {+ const filePath = path.join(this.getBasePath(), key);+ if (options?.range) {+ const [startStr, endStr] = options.range.replace(/bytes=/, '').split('-');+ const start = parseInt(startStr, 10);+ const end = endStr ? parseInt(endStr, 10) : undefined;+ return fs.createReadStream(filePath, { start, end });+ }+ return fs.createReadStream(filePath);+ }+}diff --git a/packages/app/src/backend/services/storage/README.md b/packages/app/src/backend/services/storage/README.mdnew file mode 100644index 00000000..866adc24--- /dev/null+++ b/packages/app/src/backend/services/storage/README.md@@ -0,0 +1,163 @@+# 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 requireddiff --git a/packages/app/src/backend/services/storage/S3Storage.class.ts b/packages/app/src/backend/services/storage/S3Storage.class.tsindex cb953393..738ecc1a 100644--- a/packages/app/src/backend/services/storage/S3Storage.class.ts+++ b/packages/app/src/backend/services/storage/S3Storage.class.ts@@ -1,132 +1,79 @@import {- S3Client,- GetObjectCommand,- PutObjectCommand,DeleteObjectCommand,- CreateBucketCommand,- HeadBucketCommand,+ DeleteObjectCommandInput,+ GetObjectCommand,HeadObjectCommand,- GetObjectCommandInput,- GetObjectCommandOutput,+ PutObjectCommand,PutObjectCommandInput,- DeleteObjectCommandInput,+ S3Client,} from '@aws-sdk/client-s3';-import type { Readable } from 'stream';-+import multer from 'multer';+import { Readable } from 'stream';import appConfig from '../../config';-import type { S3StorageConfig } from '../../types';+import { S3_DAILY_PURGE_LIFECYCLE_TAG } from '../../constants';+import multerS3, { AUTO_CONTENT_TYPE } from '../../lib/multer-s3';+import {+ CreateUploadMwParams,+ DeleteContentParams,+ FileMetadata,+ SaveContentParams,+ StaticStorage,+ StorageACL,+} from './StaticStorage';const logger = console;-interface Metadata {- [key: string]: string;+interface AWSConfig {+ bucket: string;+ region: string;+ accessKeyId: string;+ secretAccessKey: string;}-/**- * The S3Storage class provides a simplified interface for interacting with AWS S3 Storage.- * It encapsulates the AWS S3 Client, providing methods for common operations on a specified S3 bucket.- *- * @class S3Storage- *- * @param {S3StorageConfig} config - Configuration for AWS S3, including access keys and region.- * This configuration is used to instantiate the AWS S3 Client.- *- * @param {string} bucket - The name of the AWS S3 Bucket to be used for storage operations.- * All operations performed using an instance of this class will target this bucket.- *- * This class is designed to abstract the underlying AWS SDK calls, providing a simpler and more intuitive way to interact with AWS S3.- */--export default class S3Storage {+export default class S3Storage implements StaticStorage {protected client: S3Client;+ protected bucket: string;constructor(- protected readonly bucket: string,- protected config?: Partial<S3StorageConfig>,+ // protected readonly bucket: string,+ // protected config?: Partial<S3StorageConfig>,+ protected readonly accessControl: StorageACL,) {- const region = config?.region || appConfig.env.AWS_S3_REGION;- const accessKeyId = config?.accessKeyId || appConfig.env.AWS_ACCESS_KEY_ID;- const secretAccessKey = config?.secretAccessKey || appConfig.env.AWS_SECRET_ACCESS_KEY;-- if (!region || !accessKeyId || !secretAccessKey) {- const msg = 'AWS S3 Region, Access Key ID, or Secret Access Key is missing';-- logger.error(msg);- throw new Error(msg);- }-- this.client = new S3Client({ region, credentials: { accessKeyId, secretAccessKey } });- this.bucket = bucket;- }-- private async bucketExists(): Promise<boolean> {- try {- const command = new HeadBucketCommand({ Bucket: this.bucket });-- await this.client.send(command);-- return true;- } catch (error: any) {- if (- error.name === 'NotFound' ||- error.name === 'NoSuchBucket' ||- error.$metadata.httpStatusCode === 404- ) {- return false; // The bucket does not exist- }-- logger.error(`Error checking if bucket (${this.bucket}) exists: `, error);- throw error;- }- }+ const privConfig: AWSConfig = {+ bucket: appConfig.env.AWS_S3_BUCKET_NAME,+ region: appConfig.env.AWS_S3_REGION,+ accessKeyId: appConfig.env.AWS_ACCESS_KEY_ID,+ secretAccessKey: appConfig.env.AWS_SECRET_ACCESS_KEY,+ };- private async createBucket(): Promise<any> {- try {- const command = new CreateBucketCommand({ Bucket: this.bucket });- const response = await this.client.send(command);+ const pubConfig: AWSConfig = {+ bucket: appConfig.env.AWS_S3_PUB_BUCKET_NAME,+ region: appConfig.env.AWS_S3_PUB_REGION,+ accessKeyId: appConfig.env.AWS_ACCESS_KEY_ID,+ secretAccessKey: appConfig.env.AWS_SECRET_ACCESS_KEY,+ };- return response;- } catch (error) {- logger.error(`Error creating bucket (${this.bucket}): `, error);- throw error;- }- }+ const matchConfig: AWSConfig = accessControl === StorageACL.PublicRead ? pubConfig : privConfig;- public async ensureBucketExists() {- try {- const exists = await this.bucketExists();+ if (!matchConfig.region || !matchConfig.accessKeyId || !matchConfig.secretAccessKey) {+ const msg = 'AWS S3 Region, Access Key ID, or Secret Access Key is missing';- if (!exists) {- await this.createBucket();- }- } catch (error) {- throw error;+ logger.error(msg);+ // throw new Error(msg);}- }- public async getObject(- key: string,- otherParams: Partial<GetObjectCommandInput> = {},- ): Promise<GetObjectCommandOutput> {- if (!key || typeof key !== 'string') throw new Error('The key must be a non-empty string.');-- const params = {- Bucket: this.bucket,- Key: key,- ...otherParams,- };+ this.client = new S3Client({+ region: matchConfig.region,+ credentials: {+ accessKeyId: matchConfig.accessKeyId,+ secretAccessKey: matchConfig.secretAccessKey,+ },+ });- try {- const command = new GetObjectCommand(params);- const response = await this.client.send(command);- return response;- } catch (error) {- logger.error(`Error getting object with key ${key}: `, error);- throw error;- }+ this.bucket = matchConfig.bucket;}- public async putObject(+ private async putObject(key: string,body: string | Uint8Array | Buffer | Readable,otherParams: Partial<PutObjectCommandInput> = {},@@ -152,7 +99,7 @@ export default class S3Storage {}}- public async deleteObject(+ private async deleteObject(key: string,otherParams: Partial<DeleteObjectCommandInput> = {},): Promise<any> {@@ -175,27 +122,89 @@ export default class S3Storage {}}- public async getMetadata(- key: string,- otherParams: Partial<GetObjectCommandInput> = {},- ): Promise<Metadata | undefined> {- if (!key || typeof key !== 'string') throw new Error('The key must be a non-empty string.');+ public createUploadMw(params: CreateUploadMwParams): multer.Multer {+ const upload = multer({+ storage: multerS3({+ s3: this.client,+ bucket: this.bucket,+ acl: params.acl || undefined,+ key: async (req, file, cb) => {+ const keyStr = typeof params.key === 'function' ? params.key(req, file) : params.key;+ cb(null, keyStr);+ },+ metadata: (req, file, cb) => {+ const metadataContent =+ typeof params.metadata === 'function' ? params.metadata(req, file) : params.metadata;+ cb(null, metadataContent);+ },+ contentType: AUTO_CONTENT_TYPE,+ tagging: params.purge === 'DAILY' ? S3_DAILY_PURGE_LIFECYCLE_TAG : undefined,+ }),+ limits: params.limits,+ fileFilter: params.fileFilter,+ });++ return upload;+ }- const params = {- Bucket: this.bucket,- Key: key,- ...otherParams,+ public async saveContent({+ key,+ body,+ contentType,+ purge,+ skipAclCheck,+ }: SaveContentParams): Promise<any> {+ let otherParams: Partial<PutObjectCommandInput> = {};++ if (!skipAclCheck) {+ const acl = this.accessControl === StorageACL.PublicRead ? 'public-read' : 'private';+ otherParams.ACL = acl;+ }++ // set content type if provided+ if (contentType) otherParams.ContentType = contentType;++ // set lifecycle if cleanup provided+ const purgeMap = {+ DAILY: S3_DAILY_PURGE_LIFECYCLE_TAG,};- try {- // Fetch only Metadata with HeadObjectCommand- const command = new HeadObjectCommand(params);- const response = await this.client.send(command);+ if (purgeMap[purge]) otherParams.Tagging = purgeMap[purge];- return response?.Metadata;- } catch (error: any) {- logger.error(`Error getting metadata with key ${key}: `, error);- throw error;- }+ await this.putObject(key, body, otherParams);++ return { success: true, url: this.getPublicUrl(key) };+ }++ public async deleteContent({ key }: DeleteContentParams): Promise<{ success: boolean }> {+ await this.deleteObject(key);+ return { success: true };+ }++ public getPublicUrl(key: string): string {+ return `https://${appConfig.env.AWS_S3_PUB_BUCKET_NAME}/${key}`;+ }++ async stat(key: string): Promise<FileMetadata> {+ const res = await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }));++ return {+ size: res.ContentLength ?? 0,+ contentType: res.ContentType,+ lastModified: res.LastModified,+ etag: res.ETag,+ metadata: res.Metadata,+ };+ }++ async getStream(key: string, options?: { range?: string }) {+ const res = await this.client.send(+ new GetObjectCommand({+ Bucket: this.bucket,+ Key: key,+ Range: options?.range,+ }),+ );+ return res.Body as NodeJS.ReadableStream;}}diff --git a/packages/app/src/backend/services/storage/SmythStaticStorage.class.ts b/packages/app/src/backend/services/storage/SmythStaticStorage.class.tsdeleted file mode 100644index 1d333c5f..00000000--- a/packages/app/src/backend/services/storage/SmythStaticStorage.class.ts+++ /dev/null@@ -1,133 +0,0 @@-import { PutObjectCommandInput } from '@aws-sdk/client-s3';-import path from 'path';-import { Readable } from 'stream';-import crypto from 'crypto';--import S3Storage from './S3Storage.class';-import { stream2buffer } from '../utils.service';-import type { Metadata } from '../../types';-import appConfig from '../../config';-import { S3_DAILY_PURGE_LIFECYCLE_TAG } from '../../constants';-import multer, { StorageEngine } from 'multer';-import multerS3, { AUTO_CONTENT_TYPE } from '../../lib/multer-s3';--// TODO: make user ID required when available--type AclRules = Metadata;--/**- * The SmythStorage class extends the S3Storage class to provide an additional layer of abstraction.- * It ensures proper access control and maintains an organized folder structure within the S3 bucket.- *- * @class SmythStorage- *- * This class is designed to handle specific storage requirements for the Smyth application, including:- * - Enforcing access control rules.- * - Organizing stored objects into specific folders for better manageability.- */-export default class SmythPubStaticStorage extends S3Storage {- constructor() {- super(appConfig.env.AWS_S3_PUB_BUCKET_NAME || '', { region: appConfig.env.AWS_S3_PUB_REGION });- }-- public static hash(data: string | Buffer): string {- const hash = crypto.createHash('md5');- hash.update(data);- return hash.digest('hex');- }-- public async getContent(- key: string,- responseType = 'stream',- ): Promise<{- data: Buffer | Readable | undefined;- lastModified: Date | undefined;- contentType: string | undefined;- }> {- const response = await super.getObject(key);-- const body = response?.Body;-- if (responseType === 'buffer') {- if (body && body instanceof Readable) {- return {- data: await stream2buffer(body),- lastModified: response?.LastModified,- contentType: response?.ContentType,- };- }- }-- return {- data: body as Readable,- lastModified: response?.LastModified,- contentType: response?.ContentType,- };- }-- public static path(...paths: string[]): string {- // use path.posix.join to ensure forward slashes- return path.posix.join(...paths);- }-- public async saveContent({- key,- body,- contentType,- purge,- skipAclCheck,- }: {- key: string;- body: any;- contentType?: string;- purge?: 'DAILY' | 'WEEKLY' | 'MONTHLY';- skipAclCheck?: boolean;- }): Promise<any> {- let otherParams: Partial<PutObjectCommandInput> = {};-- if (!skipAclCheck) otherParams.ACL = 'public-read';-- // set content type if provided- if (contentType) otherParams.ContentType = contentType;-- // set lifecycle if cleanup provided- if (purge === 'DAILY') otherParams.Tagging = S3_DAILY_PURGE_LIFECYCLE_TAG;-- await super.putObject(key, body, otherParams);-- return { success: true, url: `https://${appConfig.env.AWS_S3_PUB_BUCKET_NAME}/${key}` };- }-- public getMulter({- key,- purge,- limits,- fileFilter,- }: {- limits?: multer.Options['limits'];- purge?: 'DAILY' | 'WEEKLY' | 'MONTHLY';- fileFilter?: multer.Options['fileFilter'];- key: string | ((req: any, file: Express.Multer.File) => string);- }): multer.Multer {- const upload = multer({- storage: multerS3({- s3: this.client,- bucket: this.bucket,- key: async (req, file, cb) => {- const keyStr = typeof key === 'function' ? key(req, file) : key;- cb(null, keyStr);- },- contentType: AUTO_CONTENT_TYPE,- tagging: purge === 'DAILY' ? S3_DAILY_PURGE_LIFECYCLE_TAG : undefined,- }),- limits,- fileFilter,- });-- return upload;- }-- public getPublicUrl(key: string): string {- return `https://${appConfig.env.AWS_S3_PUB_BUCKET_NAME}/${key}`;- }-}diff --git a/packages/app/src/backend/services/storage/StaticStorage.ts b/packages/app/src/backend/services/storage/StaticStorage.tsnew file mode 100644index 00000000..284d351a--- /dev/null+++ b/packages/app/src/backend/services/storage/StaticStorage.ts@@ -0,0 +1,48 @@+import multer from 'multer';++export enum StorageACL {+ PublicRead = 'public-read',+ Private = 'private',+}++export interface CreateUploadMwParams {+ limits?: multer.Options['limits'];+ purge?: 'DAILY' | 'WEEKLY' | 'MONTHLY';+ fileFilter?: multer.Options['fileFilter'];+ key: string | ((req: any, file: Express.Multer.File) => string);+ metadata?: any | ((req: any, file: Express.Multer.File) => any);+ acl?: StorageACL;+}++export interface SaveContentParams {+ key: string;+ body: any;+ contentType?: string;+ purge?: 'DAILY' | 'WEEKLY' | 'MONTHLY';+ skipAclCheck?: boolean;+}++export interface DeleteContentParams {+ key: string;+}++export interface FileMetadata {+ size: number;+ contentType?: string;+ lastModified?: Date;+ etag?: string;+ metadata?: any;+}++export interface StaticStorage {+ createUploadMw(params: CreateUploadMwParams): multer.Multer; // make this return type not bound to multer++ saveContent(params: SaveContentParams): Promise<{ success: boolean; url: string }>;++ deleteContent(params: DeleteContentParams): Promise<{ success: boolean }>;++ getPublicUrl(key: string): string;++ stat(fileKey: string): Promise<FileMetadata>;+ getStream(fileKey: string, options?: { range?: string }): Promise<NodeJS.ReadableStream>;+}diff --git a/packages/app/src/backend/services/storage/index.ts b/packages/app/src/backend/services/storage/index.tsnew file mode 100644index 00000000..380460ad--- /dev/null+++ b/packages/app/src/backend/services/storage/index.ts@@ -0,0 +1,41 @@+// storage/index.ts+import appConfig from '../../config';+import LocalStorage from './LocalStorage.class';+import S3Storage from './S3Storage.class';+import { StaticStorage, StorageACL } from './StaticStorage';++export class StorageFactory {+ static createStorage(accessControl: StorageACL): StaticStorage {+ const adapter = StorageFactory.determineAdapter();++ switch (adapter) {+ case 's3':+ return new S3Storage(accessControl);+ case 'local':+ return new LocalStorage(accessControl);+ default:+ return new LocalStorage(accessControl); // fallback to local storage+ }+ }++ static determineAdapter(): 's3' | 'local' {+ console.info('Determining storage adapter...');+ const s3RequiredConfig = [+ appConfig.env.AWS_S3_BUCKET_NAME,+ appConfig.env.AWS_S3_REGION,+ appConfig.env.AWS_ACCESS_KEY_ID,+ appConfig.env.AWS_SECRET_ACCESS_KEY,+ ];++ const s3ReadyToInit = s3RequiredConfig.every((config) => Boolean(config));++ const adaptorName = s3ReadyToInit ? 's3' : 'local';++ console.info(`Using ${adaptorName.toUpperCase()} storage adapter`);++ return adaptorName;+ }+}++export const assetStorage = StorageFactory.createStorage(StorageACL.PublicRead);+export const privateStorage = StorageFactory.createStorage(StorageACL.Private);diff --git a/packages/app/src/backend/utils/general.utils.ts b/packages/app/src/backend/utils/general.utils.tsindex beeb93a9..fe208733 100644--- a/packages/app/src/backend/utils/general.utils.ts+++ b/packages/app/src/backend/utils/general.utils.ts@@ -1,4 +1,5 @@import crypto from 'crypto';+import path from 'path';import config from '../config';export const kebabToCapitalize = (input) => {@@ -98,3 +99,14 @@ export const isDevEnv = (): boolean => {export const isProdEnv = (): boolean => {return config.env.NODE_ENV === 'PROD';};++export const posixPath = (...paths: string[]): string => {+ // use path.posix.join to ensure forward slashes+ return path.posix.join(...paths);+};++export const md5Hash = (data: string | Buffer): string => {+ const hash = crypto.createHash('md5');+ hash.update(data);+ return hash.digest('hex');+};diff --git a/packages/app/src/backend/utils/storage.utils.ts b/packages/app/src/backend/utils/storage.utils.tsindex 36223dc8..fdc7df37 100644--- a/packages/app/src/backend/utils/storage.utils.ts+++ b/packages/app/src/backend/utils/storage.utils.ts@@ -1,11 +1,4 @@-import config from '../config';-import { abstractedS3Client } from '../lib/s3';--export const isStorageFile = (url: string) => {- const urlObject = new URL(url);-- return urlObject.protocol === 'storage:' || urlObject.protocol === 's3:';-};+import { privateStorage } from '../services/storage';export const checkObjectOwnership = async (key: string,@@ -17,63 +10,38 @@ export const checkObjectOwnership = async (userId: string;},) => {- console.log('details', teamId, userId);- // const key = new URL(url).pathname;- const object = await abstractedS3Client- .headObject({- Bucket: config.env.AWS_S3_BUCKET_NAME,- Key: key,- })- .catch((err) => {- throw new Error('File not found');- });+ // console.log('details', teamId, userId);+ // // const key = new URL(url).pathname;+ // const object = await abstractedS3Client+ // .headObject({+ // Bucket: config.env.AWS_S3_BUCKET_NAME,+ // Key: key,+ // })+ // .catch((err) => {+ // throw new Error('File not found');+ // });++ // if (!object || Object.keys(object.Metadata).length === 0) {+ // throw new Error('File not found');+ // }++ // console.log('metadata', object.Metadata);++ // if (object.Metadata?.teamid != teamId || object.Metadata?.userid != userId) {+ // throw new Error('File not found');+ // }++ const meta = await privateStorage.stat(key).catch((e) => {+ throw new Error('File not found');+ });- if (!object || Object.keys(object.Metadata).length === 0) {+ if (Object.keys(meta.metadata).length === 0) {throw new Error('File not found');}- console.log('metadata', object.Metadata);+ console.log(`S3 OBJECT ${key} METADATA: `, meta.metadata);- if (object.Metadata?.teamid != teamId || object.Metadata?.userid != userId) {+ if (meta.metadata?.teamid != teamId || meta.metadata?.userid != userId) {throw new Error('File not found');}};--export const getObjectDataByKey = (key: string) => {- return new Promise(async (resolve, reject) => {- try {- const response: any = await abstractedS3Client.getObject({- Bucket: config.env.AWS_S3_BUCKET_NAME,- Key: key,- });- const request = response.Body;- let dataChunks = [];-- // Listen for data events to collect the chunks- request.on('data', (chunk) => {- dataChunks.push(chunk);- });-- // Handle the end of the stream and convert the chunks to a string- request.on('end', () => {- const completeData = Buffer.concat(dataChunks);- const bodyContent = completeData.toString('utf-8');- resolve(bodyContent);- });-- // Error handling for the stream- request.on('error', (error) => {- console.error('Error reading the S3 object stream:', error);- reject(error);- });- } catch (error) {- reject(error);- }- });-};--export const extractObjectKeyFromUrl = (url: string) => {- const urlObject = new URL(url);-- return urlObject.pathname;-};