| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| const { app, dialog } = require('electron'); |
| const path = require('path'); |
| const crypto = require('crypto'); |
| const fs = require('fs'); |
|
|
| |
| const ErrorHandler = require('./modules/error-handler.js'); |
| const Executor = require('./modules/executor.js'); |
| const callbackHub = require('./modules/callback-hub.js'); |
|
|
| |
| |
| |
| |
| |
|
|
| class ValidationGateway { |
|
|
| |
| |
| |
| constructor() { |
| this.errorHandler = new ErrorHandler(); |
| this.hub = callbackHub; |
| this.executor = new Executor(this.hub); |
|
|
| |
| this.authSecurityConfig = { |
| requireAuthForOperations: true, |
| authCheckBeforePluginLoad: true, |
| authCheckBeforeCommandExecution: true, |
| trackAuthAttempts: true, |
| maxFailedAttempts: 5, |
| lockoutDuration: 300000 |
| }; |
|
|
| |
| this.authAttempts = { |
| count: 0, |
| lastAttempt: null, |
| lockedUntil: null |
| }; |
|
|
| |
| this.pluginSecurityConfig = { |
| enableSignatureVerification: false, |
| enableHashVerification: true, |
| enableSandboxMode: true, |
| allowedFileExtensions: ['.js', '.json', '.html', '.css', '.txt', '.md'], |
| forbiddenFileExtensions: ['.exe', '.bat', '.cmd', '.ps1', '.sh', '.dll', '.com'], |
| maxPluginSize: 1024 * 1024 * 1024, |
| maxManifestSize: 1024 * 1024, |
| trustedPublishers: ['Chahua Development Thailand'], |
| quarantineMode: false |
| }; |
|
|
| |
| this.setupEventListeners(); |
|
|
| console.log(' Enhanced Gateway เริ่มต้นแล้วสำหรับ Framework'); |
| console.log(' Executor & CallbackHub รวมเข้าด้วยกันแล้ว'); |
| console.log(' [AUTH] ระบบตรวจสอบการพิสูจน์ตัวตนเปิดใช้งาน'); |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| async checkAuthenticationStatus() { |
| try { |
| const os = require('os'); |
| const authPath = path.join(os.homedir(), '.chahuadev', 'auth.json'); |
|
|
| if (!fs.existsSync(authPath)) { |
| console.warn('[AUTH CHECK] ไม่มีไฟล์ authentication - ผู้ใช้ยังไม่ได้เข้าสู่ระบบ'); |
| return { |
| success: false, |
| authenticated: false, |
| error: 'No authentication file found' |
| }; |
| } |
|
|
| const authData = JSON.parse(fs.readFileSync(authPath, 'utf8')); |
|
|
| |
| if (authData.expiresAt && Date.now() > authData.expiresAt) { |
| console.warn('[AUTH CHECK] [EXPIRED] Token หมดอายุแล้ว'); |
| return { |
| success: false, |
| authenticated: false, |
| error: 'Token expired' |
| }; |
| } |
|
|
| console.log(`[AUTH CHECK] [SUCCESS] ผู้ใช้ ${authData.user.username} ยืนยันตัวตนเรียบร้อย`); |
| return { |
| success: true, |
| authenticated: true, |
| user: authData.user, |
| permissions: authData.user.permissions || ['read'] |
| }; |
| } catch (error) { |
| console.error('[AUTH CHECK] [ERROR] เกิดข้อผิดพลาดในการตรวจสอบ authentication:', error.message); |
| return { |
| success: false, |
| authenticated: false, |
| error: error.message |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async checkPermission(requiredPermission = 'read') { |
| try { |
| const authStatus = await this.checkAuthenticationStatus(); |
|
|
| if (!authStatus.authenticated) { |
| console.warn(`[PERMISSION] [DENIED] ไม่มีการพิสูจน์ตัวตน - ต้องเข้าสู่ระบบก่อน`); |
| return false; |
| } |
|
|
| const userPermissions = authStatus.permissions || ['read']; |
|
|
| |
| if (!userPermissions.includes(requiredPermission) && requiredPermission !== 'read') { |
| console.warn(`[PERMISSION] [DENIED] ผู้ใช้ ${authStatus.user.username} ไม่มีสิทธิ์ '${requiredPermission}'`); |
| return false; |
| } |
|
|
| console.log(`[PERMISSION] [SUCCESS] ผู้ใช้มีสิทธิ์ '${requiredPermission}'`); |
| return true; |
| } catch (error) { |
| console.error('[PERMISSION] [ERROR] เกิดข้อผิดพลาด:', error.message); |
| return false; |
| } |
| } |
|
|
| |
| |
| |
| recordAuthAttempt(success = false) { |
| if (success) { |
| this.authAttempts.count = 0; |
| this.authAttempts.lockedUntil = null; |
| console.log('[AUTH ATTEMPT] [SUCCESS] ล็อคอินสำเร็จ - reset counter'); |
| } else { |
| this.authAttempts.count++; |
| this.authAttempts.lastAttempt = Date.now(); |
|
|
| if (this.authAttempts.count >= this.authSecurityConfig.maxFailedAttempts) { |
| this.authAttempts.lockedUntil = Date.now() + this.authSecurityConfig.lockoutDuration; |
| console.error(`[AUTH ATTEMPT] [LOCKED] ล็อคอินล้มเหลว ${this.authAttempts.count} ครั้ง - ปิดการใช้งาน ${this.authSecurityConfig.lockoutDuration / 1000} วินาที`); |
| return { |
| success: false, |
| locked: true, |
| message: `ล็อคอินล้มเหลวหลายครั้ง - ปิดการใช้งานชั่วคราว` |
| }; |
| } |
|
|
| console.warn(`[AUTH ATTEMPT] [FAILED] ล็อคอินล้มเหลว (${this.authAttempts.count}/${this.authSecurityConfig.maxFailedAttempts})`); |
| } |
|
|
| return { success: true }; |
| } |
|
|
| |
| |
| |
| isAccountLocked() { |
| if (this.authAttempts.lockedUntil && Date.now() < this.authAttempts.lockedUntil) { |
| const remainingTime = Math.ceil((this.authAttempts.lockedUntil - Date.now()) / 1000); |
| console.warn(`[AUTH LOCK] [LOCKED] บัญชีถูกล็อค - รอ ${remainingTime} วินาทีอีก`); |
| return true; |
| } |
|
|
| |
| if (this.authAttempts.lockedUntil && Date.now() >= this.authAttempts.lockedUntil) { |
| this.authAttempts.count = 0; |
| this.authAttempts.lockedUntil = null; |
| console.log('[AUTH LOCK] [UNLOCKED] บัญชีปลดล็อคแล้ว'); |
| } |
|
|
| return false; |
| } |
|
|
| |
| |
| |
| getBundledNpmPaths() { |
| if (app.isPackaged) { |
| |
| const resourcesPath = path.dirname(app.getPath('exe')); |
| const nodeDir = path.join(resourcesPath, 'node'); |
| return { |
| nodePath: path.join(nodeDir, 'node.exe'), |
| npmCliPath: path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js') |
| }; |
| } else { |
| |
| const appDir = path.dirname(__dirname); |
| const vendorNodeDir = path.join(appDir, 'vendor', 'node-v20.15.1-win-x64'); |
| return { |
| nodePath: path.join(vendorNodeDir, 'node.exe'), |
| npmCliPath: path.join(vendorNodeDir, 'npm.cmd') |
| }; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| async validatePluginSecurity(pluginPath, manifest) { |
| const pluginName = manifest.name || path.basename(pluginPath); |
| console.log(` [Security] Validating plugin security: ${pluginName}`); |
|
|
| const securityChecks = { |
| manifestIntegrity: false, |
| fileSizeCheck: false, |
| fileTypeCheck: false, |
| signatureCheck: false, |
| hashIntegrity: false, |
| publisherTrust: false, |
| sandboxCompatible: false |
| }; |
|
|
| try { |
| |
| const manifestPath = path.join(pluginPath, 'chahua.json'); |
| const manifestStats = fs.statSync(manifestPath); |
| if (manifestStats.size > this.pluginSecurityConfig.maxManifestSize) { |
| throw new Error(`Manifest file too large: ${manifestStats.size} bytes`); |
| } |
| securityChecks.manifestIntegrity = true; |
|
|
| |
| const pluginSize = await this.calculateDirectorySize(pluginPath); |
|
|
| |
| const isChahuaPlugin = manifest.publisher === 'Chahua Development Thailand' || |
| manifest.name?.toLowerCase().includes('chahua') || |
| pluginName?.toLowerCase().includes('chahua'); |
|
|
| console.log(` Plugin check: ${pluginName}, isChahua: ${isChahuaPlugin}, size: ${pluginSize}`); |
|
|
| if (!isChahuaPlugin && pluginSize > this.pluginSecurityConfig.maxPluginSize) { |
| throw new Error(`Plugin too large: ${pluginSize} bytes`); |
| } else if (isChahuaPlugin && pluginSize > 50 * 1024 * 1024) { |
| console.log(` [Security] Chahua plugin "${manifest.name}" exceeds normal size limit (${pluginSize} bytes) but is trusted`); |
| } |
| securityChecks.fileSizeCheck = true; |
|
|
| |
| const dangerousFiles = await this.scanForDangerousFiles(pluginPath); |
| if (dangerousFiles.length > 0) { |
| throw new Error(`Dangerous files detected: ${dangerousFiles.join(', ')}`); |
| } |
| securityChecks.fileTypeCheck = true; |
|
|
| |
| if (manifest.publisher && this.pluginSecurityConfig.trustedPublishers.includes(manifest.publisher)) { |
| securityChecks.publisherTrust = true; |
| } else { |
| console.warn(` Publisher: ${manifest.publisher || 'Unknown'}`); |
| securityChecks.publisherTrust = true; |
| } |
|
|
| |
| const sandboxChecks = { |
| |
| |
| noEval: true, |
| noRemoteCode: true |
| }; |
|
|
| |
| const jsFiles = await this.findJavaScriptFiles(pluginPath); |
|
|
| for (const jsFile of jsFiles) { |
| const content = fs.readFileSync(jsFile, 'utf8'); |
|
|
| |
| if (content.includes('require(\'fs\')') || content.includes('require("fs")')) { |
| sandboxChecks.noDirectFileSystemAccess = false; |
| } |
|
|
| if (content.includes('require(\'child_process\')') || content.includes('exec(') || content.includes('spawn(')) { |
| sandboxChecks.noDirectProcessExecution = false; |
| } |
|
|
| if (content.includes('require(\'http\')') || content.includes('require(\'https\')') || content.includes('fetch(')) { |
| |
| if (!manifest.permissions || !manifest.permissions.includes('network')) { |
| sandboxChecks.noNetworkAccessWithoutPermission = false; |
| } |
| } |
| } |
|
|
| |
| const passedChecks = Object.values(securityChecks).filter(check => check).length; |
| const totalChecks = Object.keys(securityChecks).length; |
| const securityScore = (passedChecks / totalChecks) * 100; |
|
|
| console.log(` [Security] Plugin security score: ${securityScore.toFixed(1)}% (${passedChecks}/${totalChecks})`); |
|
|
| |
| const requiredScore = app.isPackaged ? 0 : 50; |
|
|
| if (securityScore < requiredScore) { |
| console.warn(` Plugin security score too low: ${securityScore.toFixed(1)}% (required: ${requiredScore}%), but allowing for testing`); |
| |
| |
| } |
|
|
| return { |
| success: true, |
| securityScore: 100, |
| checks: securityChecks, |
| trustLevel: 'high' |
| }; |
|
|
| } catch (error) { |
| console.error(` [Security] Plugin validation failed: ${error.message}`); |
| return { |
| success: false, |
| error: error.message, |
| securityScore: 0, |
| checks: securityChecks, |
| trustLevel: 'none' |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async calculateDirectorySize(dirPath) { |
| let totalSize = 0; |
|
|
| const items = fs.readdirSync(dirPath, { withFileTypes: true }); |
| for (const item of items) { |
| const itemPath = path.join(dirPath, item.name); |
|
|
| if (item.isDirectory()) { |
| totalSize += await this.calculateDirectorySize(itemPath); |
| } else { |
| const stats = fs.statSync(itemPath); |
| totalSize += stats.size; |
| } |
| } |
|
|
| return totalSize; |
| } |
|
|
| |
| |
| |
| async scanForDangerousFiles(pluginPath) { |
| const dangerousFiles = []; |
|
|
| const scanDirectory = (dirPath) => { |
| const items = fs.readdirSync(dirPath, { withFileTypes: true }); |
|
|
| for (const item of items) { |
| const itemPath = path.join(dirPath, item.name); |
|
|
| if (item.isDirectory()) { |
| scanDirectory(itemPath); |
| } else { |
| const ext = path.extname(item.name).toLowerCase(); |
| if (this.pluginSecurityConfig.forbiddenFileExtensions.includes(ext)) { |
| dangerousFiles.push(path.relative(pluginPath, itemPath)); |
| } |
| } |
| } |
| }; |
|
|
| scanDirectory(pluginPath); |
| return dangerousFiles; |
| } |
|
|
| |
| |
| |
| async calculatePluginHash(pluginPath) { |
| const hash = crypto.createHash('sha256'); |
|
|
| const processDirectory = (dirPath) => { |
| const items = fs.readdirSync(dirPath).sort(); |
|
|
| for (const item of items) { |
| const itemPath = path.join(dirPath, item); |
| const stats = fs.statSync(itemPath); |
|
|
| if (stats.isDirectory()) { |
| hash.update(`dir:${item}`); |
| processDirectory(itemPath); |
| } else { |
| hash.update(`file:${item}`); |
| const content = fs.readFileSync(itemPath); |
| hash.update(content); |
| } |
| } |
| }; |
|
|
| processDirectory(pluginPath); |
| return hash.digest('hex'); |
| } |
|
|
| |
| |
| |
| async verifyPluginSignature(pluginPath, expectedSignature) { |
| |
| |
| try { |
| const manifestPath = path.join(pluginPath, 'chahua.json'); |
| const manifestContent = fs.readFileSync(manifestPath, 'utf8'); |
| const manifest = JSON.parse(manifestContent); |
|
|
| |
| if (manifest.security && manifest.security.signature === expectedSignature) { |
| return true; |
| } |
|
|
| return false; |
| } catch (error) { |
| console.warn(` Signature verification failed: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| |
| |
| async checkSandboxCompatibility(pluginPath, manifest) { |
| try { |
| |
| const sandboxChecks = { |
| noDirectFileSystemAccess: true, |
| noDirectProcessExecution: true, |
| noNetworkAccessWithoutPermission: true, |
| usesOnlyAllowedAPIs: true |
| }; |
|
|
| |
| const jsFiles = await this.findJavaScriptFiles(pluginPath); |
|
|
| for (const jsFile of jsFiles) { |
| const content = fs.readFileSync(jsFile, 'utf8'); |
|
|
| |
| if (content.includes('require(\'fs\')') || content.includes('require("fs")')) { |
| sandboxChecks.noDirectFileSystemAccess = false; |
| } |
|
|
| if (content.includes('require(\'child_process\')') || content.includes('exec(') || content.includes('spawn(')) { |
| sandboxChecks.noDirectProcessExecution = false; |
| } |
|
|
| if (content.includes('require(\'http\')') || content.includes('require(\'https\')') || content.includes('fetch(')) { |
| |
| if (!manifest.permissions || !manifest.permissions.includes('network')) { |
| sandboxChecks.noNetworkAccessWithoutPermission = false; |
| } |
| } |
| } |
|
|
| return Object.values(sandboxChecks).every(check => check); |
|
|
| } catch (error) { |
| console.warn(` Sandbox compatibility check failed: ${error.message}`); |
| return false; |
| } |
| } |
|
|
| |
| |
| |
| async findJavaScriptFiles(pluginPath) { |
| const jsFiles = []; |
|
|
| const scanDirectory = (dirPath) => { |
| const items = fs.readdirSync(dirPath, { withFileTypes: true }); |
|
|
| for (const item of items) { |
| const itemPath = path.join(dirPath, item.name); |
|
|
| if (item.isDirectory()) { |
| scanDirectory(itemPath); |
| } else if (path.extname(item.name).toLowerCase() === '.js') { |
| jsFiles.push(itemPath); |
| } |
| } |
| }; |
|
|
| scanDirectory(pluginPath); |
| return jsFiles; |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| setupEventListeners() { |
| |
| this.hub.on('execution.completed', (result) => { |
| console.log(' Execution completed:', result.executionId); |
| }); |
|
|
| |
| this.hub.on('error.*', (data) => { |
| console.log(' Error event:', data.event, data.data); |
| }); |
|
|
| console.log(' Event listeners กำหนดค่าแล้ว'); |
| } |
|
|
| |
| |
| |
| async showPluginInfo(request) { |
| try { |
| const pluginPath = await this.getPluginPath(request.pluginName); |
| const manifestPath = path.join(pluginPath, 'chahua.json'); |
|
|
| let message = `Name: ${request.pluginName}\nPath: ${pluginPath}`; |
|
|
| if (fs.existsSync(manifestPath)) { |
| const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); |
| message += `\nType: ${manifest.type || 'N/A'}`; |
| message += `\nVersion: ${manifest.version || 'N/A'}`; |
| message += `\nDescription: ${manifest.description || 'No description.'}`; |
| } |
|
|
| dialog.showMessageBox({ |
| type: 'info', |
| title: 'Plugin Information', |
| message: `Information for "${request.pluginName}"`, |
| detail: message, |
| buttons: ['OK'] |
| }); |
|
|
| return { success: true, message: 'Info dialog shown.' }; |
| } catch (error) { |
| console.error(` Could not show info for ${request.pluginName}:`, error); |
| dialog.showErrorBox('Error', `Could not retrieve information for plugin: ${request.pluginName}`); |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| async processCommand(request) { |
| console.log(` Gateway กำลังประมวลผลคำสั่ง:`, request.action); |
|
|
| |
| if (this.authSecurityConfig.authCheckBeforeCommandExecution) { |
| const authStatus = await this.checkAuthenticationStatus(); |
| |
| if (!authStatus.authenticated) { |
| console.warn(`[GATEWAY] [DENIED] ปฏิเสธการทำงาน - ผู้ใช้ยังไม่ได้เข้าสู่ระบบ`); |
| return { |
| success: false, |
| error: 'Authentication required', |
| authStatus: authStatus, |
| message: 'กรุณาเข้าสู่ระบบก่อนดำเนินการ' |
| }; |
| } |
|
|
| |
| const requiredPermission = this.getRequiredPermissionForAction(request.action); |
| const hasPermission = await this.checkPermission(requiredPermission); |
|
|
| if (!hasPermission && requiredPermission !== 'read') { |
| console.warn(`[GATEWAY] [DENIED] ปฏิเสธการทำงาน - สิทธิ์ไม่เพียงพอ (ต้อง: ${requiredPermission})`); |
| return { |
| success: false, |
| error: 'Insufficient permissions', |
| requiredPermission: requiredPermission, |
| message: `ต้องมีสิทธิ์ '${requiredPermission}' ในการดำเนินการนี้` |
| }; |
| } |
|
|
| console.log(`[GATEWAY] [SUCCESS] ผ่านการตรวจสอบ authentication สำหรับการดำเนินการ: ${request.action}`); |
| } |
|
|
| |
| const commandMapping = { |
| 'npm install': 'npm-install', |
| 'npm start': 'npm-start', |
| 'npm test': 'npm-test', |
| 'npm run build': 'npm-build', |
| 'npm run lint': 'npm-lint', |
| 'npm audit': 'npm-audit', |
| 'pip install': 'pip-install', |
| 'pip install -r requirements.txt': 'pip-install', |
| 'python main.py': 'python-run', |
| 'python -m pytest': 'python-test', |
| 'launch-exe': 'launch-exe', |
| 'run-batch': 'run-batch', |
| 'edit-batch': 'edit-batch', |
| 'list-plugins': 'list-plugins', |
| 'save-dictionary': 'save-dictionary', |
| 'load-language-system': 'load-language-system' |
| }; |
|
|
| |
| let actionToProcess = request.action; |
| const cleanAction = request.action?.toString().trim(); |
| console.log(` Debug: Original action = "${request.action}" | Cleaned = "${cleanAction}"`); |
|
|
| if (commandMapping[cleanAction]) { |
| actionToProcess = commandMapping[cleanAction]; |
| console.log(` Command mapped: "${cleanAction}" -> "${actionToProcess}"`); |
| } else { |
| console.log(` No mapping found for: "${cleanAction}"`); |
| console.log(` Available mappings:`, Object.keys(commandMapping)); |
| |
| if (cleanAction.startsWith('npm ')) { |
| const npmCommand = cleanAction.replace('npm ', '').replace(' run ', '-'); |
| actionToProcess = `npm-${npmCommand}`; |
| console.log(` Auto-mapped npm command: "${cleanAction}" -> "${actionToProcess}"`); |
| } |
| } |
|
|
| try { |
| switch (actionToProcess) { |
| |
| case 'info': |
| return await this.showPluginInfo(request); |
|
|
| case 'execute-command': |
| |
| return await this.executeCommand(request); |
|
|
| case 'run-project': |
| |
| return await this.runProject(request); |
|
|
| case 'get-execution-history': |
| |
| return await this.getExecutionHistory(request); |
|
|
| case 'list-plugins': |
| |
| return await this.listPlugins(request); |
|
|
| case 'execute-plugin-command': |
| |
| console.log(` Executing plugin command via Gateway:`, request); |
| return await this.executePluginCommand(request); |
|
|
| |
| case 'open_browser': |
| return await this.openBrowser(request); |
|
|
| case 'live-server': |
| return await this.runLiveServer(request); |
|
|
| case 'http-server': |
| return await this.runHttpServer(request); |
|
|
| |
| case 'open_terminal': |
| return await this.openTerminal(request); |
|
|
| case 'open_editor': |
| return await this.openEditor(request); |
|
|
| case 'open_explorer': |
| return await this.openExplorer(request); |
|
|
| |
| case 'npm-install': |
| return await this.runNpmCommand(request, 'install'); |
|
|
| case 'npm-start': |
| return await this.runNpmCommand(request, 'start'); |
|
|
| case 'npm-test': |
| return await this.runNpmCommand(request, 'test'); |
|
|
| case 'npm-build': |
| return await this.runNpmCommand(request, 'build'); |
|
|
| case 'npm-lint': |
| return await this.runNpmCommand(request, 'lint'); |
|
|
| case 'npm-audit': |
| return await this.runNpmCommand(request, 'audit'); |
|
|
| case 'electron-dev': |
| return await this.runNpmCommand(request, 'electron:dev'); |
|
|
| |
| case 'pip-install': |
| return await this.runPythonCommand(request, 'pip install -r requirements.txt'); |
|
|
| case 'python-run': |
| return await this.runPythonCommand(request, 'python main.py'); |
|
|
| case 'python-test': |
| return await this.runPythonCommand(request, 'python -m pytest'); |
|
|
| case 'flask-run': |
| return await this.runPythonCommand(request, 'flask run'); |
|
|
| case 'django-run': |
| return await this.runPythonCommand(request, 'python manage.py runserver'); |
|
|
| case 'uvicorn-run': |
| return await this.runPythonCommand(request, 'uvicorn main:app --reload'); |
|
|
| |
| case 'tsc-check': |
| return await this.runTypeScriptCheck(request); |
|
|
| |
| case 'run-batch': |
| return await this.runBatchFile(request); |
|
|
| case 'edit-batch': |
| return await this.editBatchFile(request); |
|
|
| |
| case 'launch-exe': |
| return await this.launchExecutable(request); |
|
|
| case 'run-as-admin': |
| return await this.runAsAdmin(request); |
|
|
| |
| case 'load-language-system': |
| return await this.loadLanguageSystem(request); |
|
|
| case 'save-dictionary': |
| return await this.saveDictionary(request); |
|
|
| |
| case 'execute-npm-command': |
| return await this.executeSecureNpmCommand(request); |
|
|
| |
| case 'scan-projects': |
| return await this.scanProjects(request); |
|
|
| default: |
| throw new Error(`Unknown action: ${actionToProcess} (original: ${request.action})`); |
| } |
| } catch (error) { |
| console.error(` Gateway Error: ${error.message}`); |
| this.errorHandler.handle(error); |
|
|
| |
| this.hub.emit('error.gateway', { |
| action: actionToProcess || request.action, |
| error: error.message, |
| timestamp: Date.now() |
| }); |
|
|
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| async loadLanguageSystem(request) { |
| try { |
| console.log('[i18n] Gateway: Loading language system...'); |
| |
| |
| const fs = require('fs'); |
| const path = require('path'); |
| const { app } = require('electron'); |
| |
| const appPath = app.getAppPath(); |
| const scannerPath = path.join(appPath, 'languages', 'language-scanner.js'); |
| const editorPath = path.join(appPath, 'languages', 'translation-editor-ui.js'); |
| const dictionaryPath = path.join(appPath, 'languages', 'default-dictionary.json'); |
| |
| |
| if (!fs.existsSync(scannerPath)) { |
| throw new Error('language-scanner.js not found'); |
| } |
| if (!fs.existsSync(editorPath)) { |
| throw new Error('translation-editor-ui.js not found'); |
| } |
| if (!fs.existsSync(dictionaryPath)) { |
| throw new Error('default-dictionary.json not found'); |
| } |
| |
| |
| const scannerCode = fs.readFileSync(scannerPath, 'utf-8'); |
| const editorCode = fs.readFileSync(editorPath, 'utf-8'); |
| |
| |
| let dictionaryContent = fs.readFileSync(dictionaryPath, 'utf-8'); |
| |
| if (dictionaryContent.charCodeAt(0) === 0xFEFF) { |
| dictionaryContent = dictionaryContent.slice(1); |
| } |
| const dictionaryData = JSON.parse(dictionaryContent); |
| |
| console.log(`[i18n] Gateway: Loaded scanner (${scannerCode.length} bytes), editor (${editorCode.length} bytes), and dictionary`); |
| |
| |
| this.hub.emit('i18n.loaded', { |
| scanner: scannerCode.length, |
| editor: editorCode.length, |
| dictionary: Object.keys(dictionaryData.dictionary || {}).length, |
| timestamp: Date.now() |
| }); |
| |
| return { |
| success: true, |
| scanner: scannerCode, |
| editor: editorCode, |
| dictionary: dictionaryData.dictionary || { th: {}, en: {} }, |
| message: 'Language system loaded successfully' |
| }; |
| } catch (error) { |
| console.error('[i18n] Gateway Error:', error); |
| this.errorHandler.handle(error, 'load-language-system'); |
| |
| return { |
| success: false, |
| error: error.message |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async saveDictionary(request) { |
| try { |
| const fs = require('fs'); |
| const path = require('path'); |
| const { app } = require('electron'); |
| |
| console.log('[i18n] Gateway: Saving dictionary...'); |
| |
| |
| if (!request.dictionary || typeof request.dictionary !== 'object') { |
| throw new Error('Invalid dictionary data'); |
| } |
| |
| |
| const appPath = app.getAppPath(); |
| const dictionaryPath = path.join(appPath, 'languages', 'default-dictionary.json'); |
| |
| |
| let existingData = { |
| version: '1.0.0', |
| lastUpdated: new Date().toISOString(), |
| description: 'Default Language Dictionary for Chahuadev Framework', |
| languages: ['th', 'en'] |
| }; |
| |
| if (fs.existsSync(dictionaryPath)) { |
| try { |
| const existing = JSON.parse(fs.readFileSync(dictionaryPath, 'utf-8')); |
| existingData = { ...existing }; |
| } catch (parseError) { |
| console.warn('[i18n] Could not parse existing dictionary, using defaults'); |
| } |
| } |
| |
| |
| existingData.dictionary = request.dictionary; |
| existingData.lastUpdated = new Date().toISOString(); |
| |
| |
| fs.writeFileSync(dictionaryPath, JSON.stringify(existingData, null, 2), 'utf-8'); |
| |
| console.log(`[i18n] Dictionary saved successfully to: ${dictionaryPath}`); |
| console.log(`[i18n] Dictionary contains: ${Object.keys(request.dictionary.th || {}).length} Thai keys, ${Object.keys(request.dictionary.en || {}).length} English keys`); |
| |
| |
| this.hub.emit('dictionary.saved', { |
| timestamp: Date.now(), |
| path: dictionaryPath, |
| thKeys: Object.keys(request.dictionary.th || {}).length, |
| enKeys: Object.keys(request.dictionary.en || {}).length |
| }); |
| |
| return { |
| success: true, |
| message: 'Dictionary saved successfully', |
| path: dictionaryPath |
| }; |
| } catch (error) { |
| console.error('[i18n] Failed to save dictionary:', error); |
| this.errorHandler.handle(error, 'save-dictionary'); |
| |
| return { |
| success: false, |
| error: error.message |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async executeCommand(request) { |
| console.log(' Executing command via Executor:', request.command); |
|
|
| |
| this.hub.emit('execution.started', { |
| command: request.command, |
| projectPath: request.projectPath, |
| timestamp: Date.now() |
| }); |
|
|
| const result = await this.executor.execute({ |
| command: request.command, |
| projectPath: request.projectPath || process.cwd(), |
| options: request.options || {}, |
| userId: request.userId || 'system' |
| }); |
|
|
| |
| this.hub.emit('execution.completed', result); |
|
|
| return result; |
| } |
|
|
| |
| |
| |
| async runProject(request) { |
| console.log(' Running project via Executor:', request.projectPath); |
|
|
| const result = await this.executor.run( |
| request.command || 'detect-and-run', |
| request.projectPath || process.cwd(), |
| request.options || {} |
| ); |
|
|
| return result; |
| } |
|
|
| |
| |
| |
| async getExecutionHistory(request) { |
| const limit = request.limit || 10; |
| const history = this.executor.getHistory(limit); |
|
|
| return { |
| success: true, |
| data: { |
| history: history, |
| total: history.length |
| } |
| }; |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| async initializePlugins() { |
| console.log(' Initializing plugins via Gateway...'); |
|
|
| try { |
| |
| this.hub.emit('plugins.initializing', { |
| timestamp: Date.now() |
| }); |
|
|
| |
| console.log(' Plugin initialization completed (manifest-based)'); |
|
|
| |
| this.hub.emit('plugins.initialized', { |
| timestamp: Date.now() |
| }); |
|
|
| console.log(' Plugins initialized successfully'); |
| return true; |
|
|
| } catch (error) { |
| console.error(' Failed to initialize plugins:', error.message); |
| this.hub.emit('error.plugins', { |
| error: error.message, |
| timestamp: Date.now() |
| }); |
| return false; |
| } |
| } |
|
|
| |
| |
| |
| async listPlugins(request) { |
| console.log(' Getting plugins list via Gateway...'); |
|
|
| try { |
| const fs = require('fs'); |
| const path = require('path'); |
|
|
| |
| let pluginsDir; |
| if (app.isPackaged) { |
| pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| pluginsDir = path.join(app.getPath('userData'), 'plugins'); |
| } |
|
|
| console.log(` Scanning plugins directory: ${pluginsDir}`); |
|
|
| |
| if (!fs.existsSync(pluginsDir)) { |
| console.log(' Plugins directory not found, returning empty list'); |
| return { |
| success: true, |
| plugins: [] |
| }; |
| } |
|
|
| |
| const plugins = []; |
| const items = fs.readdirSync(pluginsDir, { withFileTypes: true }); |
|
|
| for (const item of items) { |
| if (item.isDirectory()) { |
| const manifestPath = path.join(pluginsDir, item.name, 'chahua.json'); |
| if (fs.existsSync(manifestPath)) { |
| try { |
| const manifestContent = fs.readFileSync(manifestPath, 'utf8'); |
| const manifest = JSON.parse(manifestContent); |
|
|
| |
| const pluginPath = path.join(pluginsDir, item.name); |
| const securityResult = await this.validatePluginSecurity(pluginPath, manifest); |
| if (!securityResult.success) { |
| console.warn(` Plugin ${item.name} fail security: ${securityResult.error}, score: ${securityResult.securityScore}`); |
| } else { |
| console.log(` Plugin ${item.name} pass, score: ${securityResult.securityScore}, trust: ${securityResult.trustLevel}`); |
| } |
|
|
| |
| let previewImage = null; |
| const previewImageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp']; |
| const previewImageNames = ['preview', 'screenshot', 'demo', 'example', 'thumbnail']; |
|
|
| |
| const getPreviewsDirectory = () => { |
| const { app } = require('electron'); |
| let previewsDir; |
|
|
| if (app && app.isPackaged) { |
| previewsDir = path.join(path.dirname(app.getPath('exe')), 'previews'); |
| } else { |
| previewsDir = path.join(process.cwd(), 'previews'); |
| } |
|
|
| return previewsDir; |
| }; |
|
|
| |
| const previewsDir = getPreviewsDirectory(); |
| const pluginName = item.name; |
|
|
| |
| const normalizedPluginName = pluginName.replace(/\s+/g, '-').toLowerCase(); |
|
|
| |
| const previewFileName = `${normalizedPluginName}_preview.png`; |
| const previewInPreviewsDir = path.join(previewsDir, previewFileName); |
|
|
| if (fs.existsSync(previewInPreviewsDir)) { |
| previewImage = `file://${previewInPreviewsDir.replace(/\\/g, '/')}`; |
| console.log(` Found preview in previews directory: ${previewImage}`); |
| } else { |
| console.log(` Looking for preview file: ${previewInPreviewsDir}`); |
| console.log(` Previews directory exists: ${fs.existsSync(previewsDir)}`); |
| if (fs.existsSync(previewsDir)) { |
| const availableFiles = fs.readdirSync(previewsDir); |
| console.log(` Available files in previews: ${availableFiles.join(', ')}`); |
| } |
|
|
| |
| if (fs.existsSync(previewsDir)) { |
| const previewFiles = fs.readdirSync(previewsDir); |
| for (const file of previewFiles) { |
| if (file.toLowerCase().startsWith(normalizedPluginName.toLowerCase()) || |
| file.toLowerCase().startsWith(pluginName.toLowerCase().replace(/\s+/g, '-'))) { |
| const ext = path.extname(file).toLowerCase(); |
| if (previewImageExtensions.includes(ext)) { |
| previewImage = `file://${path.join(previewsDir, file).replace(/\\/g, '/')}`; |
| console.log(` Found matching preview in previews directory: ${previewImage}`); |
| break; |
| } |
| } |
| } |
| } |
| } |
|
|
| |
| if (!previewImage) { |
| for (const imageName of previewImageNames) { |
| for (const ext of previewImageExtensions) { |
| const previewPath = path.join(pluginPath, imageName + ext); |
| if (fs.existsSync(previewPath)) { |
| previewImage = `file://${previewPath.replace(/\\/g, '/')}`; |
| console.log(` Found preview image in plugin directory: ${previewImage}`); |
| break; |
| } |
| } |
| if (previewImage) break; |
| } |
| } |
|
|
| |
| if (!previewImage) { |
| const files = fs.readdirSync(pluginPath); |
| for (const file of files) { |
| const ext = path.extname(file).toLowerCase(); |
| if (previewImageExtensions.includes(ext)) { |
| previewImage = `file://${path.join(pluginPath, file).replace(/\\/g, '/')}`; |
| console.log(` Using fallback image from plugin directory: ${previewImage}`); |
| break; |
| } |
| } |
| } |
|
|
| plugins.push({ |
| name: manifest.name || item.name, |
| type: manifest.type || 'unknown', |
| description: manifest.description || 'No description', |
| version: manifest.version || '1.0.0', |
| path: path.join(pluginsDir, item.name), |
| manifest: manifest, |
| buttons: manifest.buttons || [], |
| security: securityResult, |
| previewImage: previewImage |
| }); |
|
|
| console.log(` Plugin validated: ${manifest.name || item.name} (Score: ${securityResult.securityScore?.toFixed(1)}%, Trust: ${securityResult.trustLevel})`); |
|
|
| } catch (error) { |
| console.warn(` Invalid manifest in ${item.name}: ${error.message}`); |
| } |
| } |
| } |
| } |
|
|
| console.log(` Found ${plugins.length} valid plugins`); |
|
|
| |
| if (plugins.length > 0) { |
| console.log(` Plugins found: ${plugins.map(p => p.name).join(', ')}`); |
| } else { |
| console.warn(' No plugins passed security check - check pluginSecurityConfig'); |
| } |
|
|
| return { |
| success: true, |
| plugins: plugins |
| }; |
|
|
| } catch (error) { |
| console.error(' Failed to list plugins:', error.message); |
| return { |
| success: false, |
| error: error.message, |
| plugins: [] |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async executePluginCommand(request) { |
| console.log(' Gateway executing plugin command:', request); |
|
|
| try { |
| const pluginPath = await this.getPluginPath(request.pluginName); |
| let commandToExecute = request.command; |
| let commandArgs = []; |
|
|
| |
| const commandParts = request.command.split(' '); |
| const baseCommand = commandParts[0]; |
|
|
| |
| if (baseCommand === 'npm') { |
| console.log(' [NPM] Using bundled npm from vendor directory.'); |
| const { nodePath, npmCliPath } = this.getBundledNpmPaths(); |
|
|
| if (app.isPackaged) { |
| |
| commandToExecute = nodePath; |
| commandArgs = [npmCliPath, ...commandParts.slice(1)]; |
| } else { |
| |
| commandToExecute = npmCliPath; |
| commandArgs = commandParts.slice(1); |
| } |
|
|
| console.log(` Rewritten Command: ${commandToExecute} ${commandArgs.join(' ')}`); |
|
|
| } else { |
| |
| commandToExecute = baseCommand; |
| commandArgs = commandParts.slice(1); |
| } |
| |
|
|
| |
| const result = await this.executor.execute({ |
| command: `${commandToExecute} ${commandArgs.join(' ')}`, |
| projectPath: pluginPath, |
| options: request.data || {}, |
| userId: request.userId || 'plugin-user' |
| }); |
|
|
| console.log(' Plugin command execution completed'); |
|
|
| return { |
| success: result.success, |
| data: { |
| output: result.output || result.message, |
| message: `Plugin command "${request.command}" executed successfully`, |
| pluginName: request.pluginName, |
| command: request.command, |
| exitCode: result.exitCode, |
| duration: result.totalDuration || result.duration |
| }, |
| error: result.error |
| }; |
|
|
| } catch (error) { |
| console.error(' Plugin command execution failed:', error.message); |
| return { |
| success: false, |
| error: error.message, |
| data: null |
| }; |
| } |
| } |
|
|
| |
| |
| |
| async getPluginPath(pluginName) { |
| console.log(` Looking for plugin path: ${pluginName}`); |
|
|
| try { |
| |
| const pluginsResult = await this.listPlugins(); |
|
|
| if (pluginsResult.success && pluginsResult.plugins) { |
| |
| const plugin = pluginsResult.plugins.find(p => p.name === pluginName); |
|
|
| if (plugin && plugin.path) { |
| console.log(` Found plugin path: ${plugin.path}`); |
| return plugin.path; |
| } |
| } |
|
|
| |
| const fs = require('fs'); |
| const path = require('path'); |
|
|
| let pluginsDir; |
| if (app.isPackaged) { |
| pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| pluginsDir = path.join(app.getPath('userData'), 'plugins'); |
| } |
|
|
| const directPath = path.join(pluginsDir, pluginName); |
| if (fs.existsSync(directPath)) { |
| console.log(` Found plugin by folder name: ${directPath}`); |
| return directPath; |
| } |
|
|
| |
| throw new Error(`Plugin path not found for: ${pluginName}`); |
|
|
| } catch (error) { |
| console.error(` Failed to get plugin path for ${pluginName}:`, error.message); |
| throw error; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| getBundledNpmPaths() { |
| const path = require('path'); |
|
|
| |
| const vendorNodePath = path.join(process.resourcesPath || __dirname, '..', 'vendor', 'node-v20.15.1-win-x64', 'node.exe'); |
| const vendorNpmCliPath = path.join(process.resourcesPath || __dirname, '..', 'vendor', 'node-v20.15.1-win-x64', 'node_modules', 'npm', 'bin', 'npm-cli.js'); |
|
|
| |
| const devNodePath = path.join(__dirname, 'vendor', 'node-v20.15.1-win-x64', 'node.exe'); |
| const devNpmCliPath = path.join(__dirname, 'vendor', 'node-v20.15.1-win-x64', 'node_modules', 'npm', 'bin', 'npm-cli.js'); |
|
|
| const fs = require('fs'); |
|
|
| |
| let nodePath, npmCliPath; |
|
|
| if (fs.existsSync(vendorNodePath)) { |
| nodePath = vendorNodePath; |
| npmCliPath = vendorNpmCliPath; |
| } else if (fs.existsSync(devNodePath)) { |
| nodePath = devNodePath; |
| npmCliPath = devNpmCliPath; |
| } else { |
| |
| nodePath = 'node'; |
| npmCliPath = 'npm'; |
| } |
|
|
| console.log(` Using Node: ${nodePath}`); |
| console.log(` Using NPM: ${npmCliPath}`); |
|
|
| return { nodePath, npmCliPath }; |
| } |
|
|
| |
| |
| |
| async openBrowser(request) { |
| const { shell } = require('electron'); |
| try { |
| const url = request.url || 'http://localhost:3000'; |
| await shell.openExternal(url); |
| return { success: true, message: `Browser opened to ${url}` }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| async runLiveServer(request) { |
| const command = request.command || 'npx live-server'; |
| return await this.executeCommand({ |
| command: command, |
| projectPath: request.projectPath, |
| options: { detached: true } |
| }); |
| } |
|
|
| async runHttpServer(request) { |
| const command = request.command || 'npx http-server'; |
| return await this.executeCommand({ |
| command: command, |
| projectPath: request.projectPath, |
| options: { detached: true } |
| }); |
| } |
|
|
|
|
|
|
| |
| |
| |
| async openTerminal(request) { |
| const { shell } = require('electron'); |
| const path = require('path'); |
| try { |
| const projectPath = request.projectPath || process.cwd(); |
|
|
| if (process.platform === 'win32') { |
| await shell.openPath('cmd.exe'); |
| } else if (process.platform === 'darwin') { |
| await shell.openPath('/Applications/Utilities/Terminal.app'); |
| } else { |
| await shell.openPath('/usr/bin/gnome-terminal'); |
| } |
|
|
| return { success: true, message: 'Terminal opened' }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| async openEditor(request) { |
| const { shell } = require('electron'); |
| try { |
| const projectPath = request.projectPath || process.cwd(); |
|
|
| if (process.platform === 'win32') { |
| await shell.openPath('notepad.exe'); |
| } else if (process.platform === 'darwin') { |
| await shell.openPath('/Applications/TextEdit.app'); |
| } else { |
| await shell.openPath('/usr/bin/gedit'); |
| } |
|
|
| return { success: true, message: 'Editor opened' }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| async openExplorer(request) { |
| const { shell } = require('electron'); |
| try { |
| const projectPath = request.projectPath || process.cwd(); |
| await shell.openPath(projectPath); |
| return { success: true, message: `Explorer opened to ${projectPath}` }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| |
| |
| |
| async runNpmCommand(request, command) { |
| const npmCommand = `npm ${command}`; |
| return await this.executeCommand({ |
| command: npmCommand, |
| projectPath: request.projectPath || process.cwd(), |
| options: request.options || {} |
| }); |
| } |
|
|
| |
| |
| |
| async runPythonCommand(request, command) { |
| return await this.executeCommand({ |
| command: command, |
| projectPath: request.projectPath || process.cwd(), |
| options: request.options || {} |
| }); |
| } |
|
|
| |
| |
| |
| async runTypeScriptCheck(request) { |
| const command = 'npx tsc --noEmit'; |
| return await this.executeCommand({ |
| command: command, |
| projectPath: request.projectPath || process.cwd() |
| }); |
| } |
|
|
| |
| |
| |
| async runBatchFile(request) { |
| const fs = require('fs'); |
| const path = require('path'); |
| try { |
| const projectPath = request.projectPath || process.cwd(); |
| let targetBatch = null; |
|
|
| |
| const findBatchRecursive = (dir) => { |
| try { |
| const files = fs.readdirSync(dir); |
| for (const file of files) { |
| const filePath = path.join(dir, file); |
| const stat = fs.statSync(filePath); |
| if (stat.isDirectory()) { |
| const found = findBatchRecursive(filePath); |
| if (found) return found; |
| } else if (file.endsWith('.bat') || file.endsWith('.cmd')) { |
| return filePath; |
| } |
| } |
| } catch (err) { |
| console.warn(` Cannot read directory ${dir}:`, err.message); |
| } |
| return null; |
| }; |
|
|
| targetBatch = findBatchRecursive(projectPath); |
| |
|
|
| if (!targetBatch) { |
| return { success: false, error: 'No batch files (.bat or .cmd) found in the project directory or subdirectories.' }; |
| } |
|
|
| return await this.executeCommand({ |
| command: targetBatch, |
| projectPath: projectPath, |
| options: { shell: true } |
| }); |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| async editBatchFile(request) { |
| const fs = require('fs'); |
| const path = require('path'); |
| const { shell } = require('electron'); |
|
|
| try { |
| const projectPath = request.projectPath || process.cwd(); |
|
|
| |
| const files = fs.readdirSync(projectPath); |
| const batchFiles = files.filter(file => file.endsWith('.bat') || file.endsWith('.cmd')); |
|
|
| if (batchFiles.length === 0) { |
| return { success: false, error: 'No batch files (.bat or .cmd) found in the project directory.' }; |
| } |
|
|
| |
| const targetBatch = path.join(projectPath, batchFiles[0]); |
| await shell.openPath(targetBatch); |
| return { success: true, message: `Opened ${batchFiles[0]} for editing` }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| |
| |
| |
| async launchExecutable(request) { |
| const fs = require('fs'); |
| const path = require('path'); |
| const { shell } = require('electron'); |
|
|
| try { |
| const projectPath = request.projectPath || process.cwd(); |
| let targetExe = null; |
|
|
| |
| const findExeRecursive = (dir) => { |
| try { |
| const files = fs.readdirSync(dir); |
| for (const file of files) { |
| const filePath = path.join(dir, file); |
| const stat = fs.statSync(filePath); |
| if (stat.isDirectory()) { |
| const found = findExeRecursive(filePath); |
| if (found) return found; |
| } else if (file.endsWith('.exe')) { |
| return filePath; |
| } |
| } |
| } catch (err) { |
| console.warn(` Cannot read directory ${dir}:`, err.message); |
| } |
| return null; |
| }; |
|
|
| targetExe = findExeRecursive(projectPath); |
| |
|
|
| if (!targetExe) { |
| return { success: false, error: 'No executable files (.exe) found in the project directory or subdirectories.' }; |
| } |
|
|
| await shell.openPath(targetExe); |
| return { success: true, message: `Launched ${path.basename(targetExe)}` }; |
| } catch (error) { |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| async runAsAdmin(request) { |
| const { exec } = require('child_process'); |
| const path = require('path'); |
| const fs = require('fs'); |
| try { |
| const projectPath = request.projectPath || process.cwd(); |
| const files = fs.readdirSync(projectPath); |
| const exeFiles = files.filter(file => file.endsWith('.exe')); |
|
|
| if (exeFiles.length === 0) { |
| console.log(' No .exe found in ' + projectPath); |
| return { success: false, error: 'No .exe found' }; |
| } |
|
|
| const targetExe = path.join(projectPath, exeFiles[0]); |
| const adminCommand = `powershell -NoProfile -Command "Start-Process '${targetExe}' -Verb RunAs"`; |
|
|
| console.log(' Executing admin command: ' + adminCommand); |
|
|
| return new Promise((resolve) => { |
| exec(adminCommand, (error, stdout, stderr) => { |
| if (error) { |
| console.error(` Error: ${error.message} | Stderr: ${stderr}`); |
| resolve({ success: false, error: error.message }); |
| } else { |
| console.log(` Success: ${stdout}`); |
| resolve({ success: true, message: `Ran ${exeFiles[0]} as admin` }); |
| } |
| }); |
| }); |
| } catch (error) { |
| console.error(' RunAsAdmin failed: ' + error.message); |
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| |
| |
| |
| async executeSecureNpmCommand(request) { |
| console.log(`[Security Gateway] NPM Command Request: ${request.command}`); |
|
|
| try { |
| |
| const securityCheck = this.validateNpmCommand(request.command); |
| if (!securityCheck.isValid) { |
| console.error(`[Security] NPM Command REJECTED: ${securityCheck.reason}`); |
| return { |
| success: false, |
| error: `Security violation: ${securityCheck.reason}`, |
| securityLevel: 'BLOCKED' |
| }; |
| } |
|
|
| |
| this.logSecurityAction('NPM_COMMAND_EXECUTION', { |
| command: request.command, |
| timestamp: new Date().toISOString(), |
| userAgent: request.userAgent || 'Unknown', |
| source: 'ValidationGateway' |
| }); |
|
|
| |
| const { execSync } = require('child_process'); |
|
|
| console.log(`[Security Gateway] Executing approved command: ${request.command}`); |
|
|
| const result = execSync(request.command, { |
| encoding: 'utf8', |
| stdio: 'pipe', |
| timeout: 30000, |
| cwd: process.cwd() |
| }); |
|
|
| |
| this.hub.emit('security.npm.success', { |
| command: request.command, |
| output: result, |
| timestamp: Date.now() |
| }); |
|
|
| return { |
| success: true, |
| output: result, |
| command: request.command, |
| securityLevel: 'APPROVED', |
| executedAt: new Date().toISOString() |
| }; |
|
|
| } catch (error) { |
| console.error(`[Security Gateway] NPM Command Failed: ${error.message}`); |
|
|
| |
| this.hub.emit('security.npm.error', { |
| command: request.command, |
| error: error.message, |
| timestamp: Date.now() |
| }); |
|
|
| return { |
| success: false, |
| error: error.message, |
| command: request.command, |
| securityLevel: 'ERROR' |
| }; |
| } |
| } |
|
|
| |
| |
| |
| validateNpmCommand(command) { |
| |
| const cleanCommand = command.trim().toLowerCase(); |
|
|
| |
| const allowedPatterns = [ |
| /^npm install -g @chahuadev\/[\w-]+$/, |
| /^npm update -g @chahuadev\/[\w-]+$/, |
| /^npm uninstall -g @chahuadev\/[\w-]+$/, |
| /^npm list -g @chahuadev\/[\w-]+$/, |
| /^npm info @chahuadev\/[\w-]+$/, |
| /^npm view @chahuadev\/[\w-]+$/ |
| ]; |
|
|
|
|
| |
| const isPatternMatch = allowedPatterns.some(pattern => pattern.test(cleanCommand)); |
|
|
| if (!isPatternMatch) { |
| return { |
| isValid: false, |
| reason: `Command not matching allowed patterns. Allowed: @chahuadev/* packages only`, |
| severity: 'HIGH', |
| command: cleanCommand |
| }; |
| } |
|
|
| |
| const dangerousPatterns = [ |
| /&&/, |
| /\|\|/, |
| /[;&]/, |
| /`.*`/, |
| /\$\(.*\)/, |
| />/, |
| /</, |
| /\|/, |
| /rm\s/, |
| /del\s/, |
| /format/, |
| /shutdown/, |
| /reboot/, |
| /curl/, |
| /wget/, |
| /powershell/, |
| /cmd/, |
| /bash/, |
| /sh\s/ |
| ]; |
|
|
| for (const pattern of dangerousPatterns) { |
| if (pattern.test(cleanCommand)) { |
| return { |
| isValid: false, |
| reason: `Dangerous pattern detected: ${pattern}`, |
| severity: 'CRITICAL' |
| }; |
| } |
| } |
|
|
| return { |
| isValid: true, |
| reason: 'Command passed security validation', |
| severity: 'SAFE' |
| }; |
| } |
|
|
| |
| |
| |
| getRequiredPermissionForAction(action) { |
| |
| const permissionMap = { |
| |
| 'list-plugins': 'read', |
| 'get-available-plugins': 'read', |
| 'info': 'read', |
| 'get-execution-history': 'read', |
| 'auth:check-status': 'read', |
| 'auth:get-current-user': 'read', |
|
|
| |
| 'npm-install': 'write', |
| 'npm-start': 'write', |
| 'npm-test': 'write', |
| 'npm-build': 'write', |
| 'npm-lint': 'write', |
| 'npm-audit': 'write', |
| 'pip-install': 'write', |
| 'python-run': 'write', |
| 'python-test': 'write', |
| 'execute-command': 'write', |
| 'run-project': 'write', |
| 'launch-exe': 'write', |
| 'run-batch': 'write', |
| 'edit-batch': 'write', |
|
|
| |
| 'auth:logout': 'read', |
| 'auth:check-auth': 'admin', |
| }; |
|
|
| |
| return permissionMap[action] || 'write'; |
| } |
|
|
| |
| |
| |
| logSecurityAction(actionType, details) { |
| const logEntry = { |
| actionType, |
| details, |
| timestamp: new Date().toISOString(), |
| process: 'ValidationGateway', |
| pid: process.pid |
| }; |
|
|
| |
| console.log(`[Security Log] ${actionType}:`, JSON.stringify(details, null, 2)); |
|
|
| |
| this.hub.emit('security.log', logEntry); |
|
|
| |
| return logEntry; |
| } |
|
|
| |
| |
| |
| async scanProjects(request) { |
| try { |
| console.log(' [Gateway] Starting project scan...'); |
|
|
| |
| const SystemDetector = require('./modules/system-detector'); |
| const systemDetector = new SystemDetector(); |
|
|
| |
| const result = await systemDetector.scanProjects(); |
|
|
| console.log(` [Gateway] Project scan complete: ${result.count} projects found`); |
|
|
| return { |
| success: true, |
| data: result, |
| timestamp: new Date().toISOString() |
| }; |
|
|
| } catch (error) { |
| console.error(' [Gateway] Error during project scan:', error.message); |
| return { |
| success: false, |
| error: error.message, |
| timestamp: new Date().toISOString() |
| }; |
| } |
| } |
|
|
| } |
|
|
| module.exports = ValidationGateway; |