const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron'); // เพิ่ม Menu และ shell const path = require('path'); const fs = require('fs'); const os = require('os'); // เพิ่ม os const crypto = require('crypto'); // เพิ่ม crypto const https = require('https'); // เพิ่มสำหรับ OAuth Device Flow const { spawn, exec } = require('child_process'); // เพิ่มสำหรับ manifest generator และ terminal // Ignore dev flags in packaged builds so distributed binaries cannot be forced into dev mode. if (app.isPackaged) { process.argv = process.argv.filter(arg => arg !== '--dev-mode' && arg !== '--dev'); } // ====================================================================== // ขั้นตอนที่ 1: เตรียมระบบติดตาม API (ไม่เริ่มทันที) // ====================================================================== // ตรวจสอบ Dev Mode ให้เร็วที่สุด const isDevMode = !app.isPackaged || process.argv.includes('--dev-mode'); console.log(` Developer Mode: ${isDevMode ? 'ENABLED' : 'DISABLED'} (${!app.isPackaged ? 'Development' : process.argv.includes('--dev-mode') ? '--dev-mode flag' : 'Production'})`); // [COMMENTED] โหลด ApiTraceDebugger แต่ยังไม่เริ่มทำงาน (จะเริ่มใน app.whenReady()) // [REASON] ออฟไลน์ Auth System ใช้อยู่แล้ว - คอมเมนท์ไว้ เผื่อต้องใช้ในอนาคต // const ApiTraceDebugger = require('./ApiTraceDebugger'); // console.log('[API TRACE] ระบบติดตาม API พร้อมใช้งาน (จะเริ่มหลัง app.whenReady())'); // Stub ApiTraceDebugger เพื่อป้องกัน error const ApiTraceDebugger = { start: () => console.log('[API TRACE] (Disabled - using Offline Auth)'), stop: () => console.log('[API TRACE] (Disabled)') }; // ====================================================================== // ขั้นตอนที่ 2: โหลดโมดูลอื่นๆ ของแอปพลิเคชันตามปกติ // ====================================================================== // โมดูลเหล่านี้จะถูกโหลดก่อน แต่ยังไม่ได้ใช้งาน API มากนัก // Direct Integration - ไม่ต้อง spawn app.js แล้ว! const ValidationGateway = require('./validation_gateway'); // ========== FORT-KNOX LEVEL SECURITY SYSTEM ========== // เพิ่ม Tamper Detector const TamperDetector = require('./modules/tamper-detector'); /** * OFFLINE DEMO AUTHENTICATION CLIENT (ปิด OAuth Device Flow ชั่วคราว) * สำหรับการทดสอบและการพัฒนาโดยไม่ต้องเชื่อมต่อ chahuadev.com */ class OfflineAuthClient { constructor() { this.storagePath = path.join(os.homedir(), '.chahuadev', 'auth.json'); this.demoUsers = { 'admin': { username: 'admin', password: 'demo123', userId: 'usr_admin_001', email: 'admin@chahuadev.local', role: 'Administrator', avatar: '[ADMIN]', permissions: ['read', 'write', 'admin'] }, 'developer': { username: 'developer', password: 'demo123', userId: 'usr_dev_001', email: 'dev@chahuadev.local', role: 'Developer', avatar: '[DEV]', permissions: ['read', 'write'] }, 'user': { username: 'user', password: 'demo123', userId: 'usr_user_001', email: 'user@chahuadev.local', role: 'User', avatar: '[USER]', permissions: ['read'] } }; this.ensureStorageDirectory(); console.log('[OFFLINE AUTH] [SUCCESS] OFFLINE AUTH MODE (เดโมสำหรับการพัฒนา) - ไม่ต้องเชื่อมต่อ chahuadev.com'); } /** * สร้าง directory สำหรับเก็บข้อมูล authentication */ ensureStorageDirectory() { const dir = path.dirname(this.storagePath); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } } /** * OFFLINE: เริ่มต้นการล็อคอินแบบออฟไลน์ (จำลองแบบ Device Flow) */ async startDeviceFlow() { console.log(' [OFFLINE AUTH] Device Flow simulation started'); // จำลองการสร้าง device code const deviceCode = 'OFFLINE-' + crypto.randomBytes(16).toString('hex').toUpperCase(); const userCode = 'DEMO-' + Math.random().toString(36).substring(2, 8).toUpperCase(); const mockResponse = { success: true, deviceCode: deviceCode, userCode: userCode, expiresIn: 600, interval: 5, message: ' กรุณาป้อน User Code: ' + userCode, instruction: 'ใช้ชื่อผู้ใช้: admin/developer/user พร้อม password: demo123' }; console.log(' [OFFLINE AUTH] Mock Device Code:', deviceCode); console.log(' [OFFLINE AUTH] Mock User Code:', userCode); return mockResponse; } /** * OFFLINE: การยืนยันการล็อคอินแบบออฟไลน์ */ async authenticateOffline(username, password) { console.log(` [OFFLINE AUTH] Attempting login: ${username}`); // ตรวจสอบ username และ password const user = this.demoUsers[username]; if (!user || user.password !== password) { console.error(' [OFFLINE AUTH] Invalid credentials'); return { success: false, error: 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง' }; } // สร้าง mock tokens const mockTokens = { accessToken: 'mock_access_' + crypto.randomBytes(32).toString('hex'), refreshToken: 'mock_refresh_' + crypto.randomBytes(32).toString('hex'), expiresIn: 86400, // 24 hours user: { username: user.username, userId: user.userId, email: user.email, role: user.role, avatar: user.avatar, permissions: user.permissions }, authenticated: true, authenticatedAt: new Date().toISOString() }; // บันทึก tokens await this.saveTokens(mockTokens); console.log(' [OFFLINE AUTH] Login successful:', user.username); return { success: true, status: 'approved', data: mockTokens }; } /** * OFFLINE: จำลอง polling device status */ async pollDeviceStatus(deviceCode) { console.log(' [OFFLINE AUTH] Polling device status (offline mode)'); // ในโหมดออฟไลน์ เราจะรีเทิร์นสถานะรอการยืนยัน return { success: true, status: 'pending', message: 'รอการใส่ชื่อผู้ใช้และรหัสผ่าน' }; } /** * บันทึก tokens ลงไฟล์ */ async saveTokens(tokens) { try { const authData = { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, expiresAt: Date.now() + (tokens.expiresIn * 1000), user: tokens.user, savedAt: new Date().toISOString(), authMode: 'offline-demo' }; fs.writeFileSync(this.storagePath, JSON.stringify(authData, null, 2), 'utf8'); console.log(' [OFFLINE AUTH] Tokens saved:', this.storagePath); return { success: true }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to save tokens:', error); return { success: false, error: error.message }; } } /** * โหลด tokens จากไฟล์ */ async loadTokens() { try { if (!fs.existsSync(this.storagePath)) { return { success: false, error: 'No saved tokens found' }; } const authData = JSON.parse(fs.readFileSync(this.storagePath, 'utf8')); // ตรวจสอบว่า token หมดอายุหรือไม่ if (authData.expiresAt && Date.now() > authData.expiresAt) { console.log(' [OFFLINE AUTH] Token expired'); return { success: false, error: 'Token expired' }; } console.log(' [OFFLINE AUTH] Tokens loaded:', authData.user.username); return { success: true, data: authData }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to load tokens:', error); return { success: false, error: error.message }; } } /** * ลบ tokens (logout) */ async removeTokens() { try { if (fs.existsSync(this.storagePath)) { fs.unlinkSync(this.storagePath); } console.log(' [OFFLINE AUTH] Logged out successfully'); return { success: true }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to remove tokens:', error); return { success: false, error: error.message }; } } } /** * Anti-Debugging Protection System * ป้องกันการใช้เครื่องมือดีบักและ reverse engineering */ class AntiDebuggingSystem { constructor() { this.checkInterval = null; // ปรับปรุงการตรวจสอบ developer mode ให้ครอบคลุมมากขึ้น this.isDevMode = this.detectDeveloperMode(); this.suspiciousActivityCount = 0; this.maxSuspiciousActivity = 3; // เริ่มต้นระบบตรวจจับการแก้ไข this.tamperDetector = new TamperDetector(); console.log(this.isDevMode ? ' Anti-Debugging: Development mode detected' : ' Anti-Debugging: Production mode active'); } /** * ระบบตรวจสอบ Developer Mode ที่ครอบคลุม * ตรวจสอบจากหลายแหล่งเพื่อความแม่นยำ */ detectDeveloperMode() { const indicators = { // 1. Process arguments hasDevArgs: process.argv.includes('--dev-mode') || process.argv.includes('--dev'), // 2. Application packaging status isUnpackaged: !app.isPackaged, // 3. Environment variables hasDevEnv: process.env.NODE_ENV === 'development' || process.env.CHAHUA_DEV === 'true', // 4. Development port detection hasDevPort: process.env.PORT && (process.env.PORT === '3000' || process.env.PORT === '8080'), // 5. Debug mode flags hasDebugFlag: process.execArgv.some(arg => arg.includes('--inspect') || arg.includes('--debug')), // 6. Development dependencies hasDevDeps: false // จะตรวจสอบเพิ่มเติมใน package.json ถ้าจำเป็น }; // Log detection results for debugging console.log(' Developer Mode Detection Results:', indicators); // Return true if any indicator suggests development mode return Object.values(indicators).some(Boolean); } /** * เริ่มระบบป้องกันการดีบัก */ start(mainWindow) { if (this.isDevMode) { console.log(' Anti-Debugging: Disabled in development mode'); return; } console.log(' Starting Anti-Debugging protection...'); this.mainWindow = mainWindow; // เริ่มระบบตรวจจับการแก้ไขไฟล์ this.tamperDetector.startMonitoring(); // ตรวจสอบทุกๆ 2 วินาที this.checkInterval = setInterval(() => { this.performSecurityChecks(); }, 2000); // ตรวจสอบ DevTools events if (mainWindow && mainWindow.webContents) { mainWindow.webContents.on('devtools-opened', () => { this.handleSuspiciousActivity('DevTools opened'); }); mainWindow.webContents.on('devtools-focused', () => { this.handleSuspiciousActivity('DevTools focused'); }); } } /** * ทำการตรวจสอบความปลอดภัย */ performSecurityChecks() { try { // ตรวจสอบ DevTools if (this.mainWindow && this.mainWindow.webContents && this.mainWindow.webContents.isDevToolsOpened()) { this.handleSuspiciousActivity('DevTools detected as open'); return; } // ตรวจสอบ debugging tools ใน process list (Windows) if (process.platform === 'win32') { this.checkForDebuggingProcesses(); } // ตรวจสอบ performance timing anomalies (อาจมี debugger ทำให้ช้า) this.checkPerformanceAnomalies(); } catch (error) { console.warn(' Anti-Debugging check error:', error.message); } } /** * ตรวจสอบ process ที่น่าสงสัย */ checkForDebuggingProcesses() { const suspiciousProcesses = [ 'cheatengine', 'x64dbg', 'x32dbg', 'ollydbg', 'windbg', 'processhacker', 'pestudio', 'ida64', 'ida32', 'ghidra' ]; // ใช้ tasklist command เพื่อดู running processes exec('tasklist', (error, stdout) => { if (error) return; const runningProcesses = stdout.toLowerCase(); for (const suspiciousProcess of suspiciousProcesses) { if (runningProcesses.includes(suspiciousProcess)) { this.handleSuspiciousActivity(`Debugging tool detected: ${suspiciousProcess}`); return; } } }); } /** * ตรวจสอบ performance anomalies */ checkPerformanceAnomalies() { const start = Date.now(); // สร้าง simple computation let sum = 0; for (let i = 0; i < 10000; i++) { sum += Math.random(); } const duration = Date.now() - start; // ถ้าใช้เวลานานกว่าปกติมาก อาจมี debugger if (duration > 100) { // ปกติควรใช้เวลาไม่เกิน 10-20ms this.handleSuspiciousActivity(`Performance anomaly detected: ${duration}ms`); } } /** * จัดการเมื่อพบกิจกรรมน่าสงสัย */ handleSuspiciousActivity(reason) { this.suspiciousActivityCount++; console.warn(` Security Alert [${this.suspiciousActivityCount}/${this.maxSuspiciousActivity}]: ${reason}`); if (this.suspiciousActivityCount >= this.maxSuspiciousActivity) { console.error(' Security breach detected! Shutting down application...'); // แสดง warning dialog ก่อนปิด if (this.mainWindow) { dialog.showErrorBox( 'Security Alert', 'Security violation detected. Application will now close for protection.' ); } // ปิดแอปทันที process.exit(1); } } /** * หยุดระบบป้องกัน */ stop() { if (this.checkInterval) { clearInterval(this.checkInterval); this.checkInterval = null; console.log(' Anti-Debugging protection stopped'); } // หยุดระบบตรวจจับการแก้ไข if (this.tamperDetector) { this.tamperDetector.stopMonitoring(); } } } /** * IPC Command Sanitization System * ป้องกันการโจมตีแบบ Command Injection ผ่าน IPC */ class IPCSecuritySystem { constructor() { // รายการคำสั่งที่อนุญาตให้รันผ่าน child_process this.allowedCommands = new Set([ 'node', 'npm', 'git', 'where', 'which', 'echo', 'dir', 'ls', 'cd', 'pwd', 'whoami', 'hostname', 'ipconfig', 'ping', 'powershell', // สำหรับ Run as Admin 'explorer' // สำหรับ Open Folder ]); // Pattern ที่อันตราย this.dangerousPatterns = [ /rm\s+-rf/i, // ลบไฟล์ /del\s+\/[sq]/i, // Windows delete /format\s+[cd]:/i, // Format drive /shutdown/i, // Shutdown /reboot/i, // Reboot />\s*nul/i, // Redirect อันตราย /`[^`]*`/, // Command substitution /\$\([^)]*\)/, // Command substitution /eval\s*\(/i, // Eval /exec\s*\(/i // Exec ]; console.log(' IPC Security System initialized'); } /** * ตรวจสอบและทำความสะอาดคำสั่ง */ sanitizeCommand(command, options = {}) { if (!command || typeof command !== 'string') { throw new Error('Invalid command: Command must be a non-empty string'); } const trimmedCommand = command.trim(); // เพิ่ม: ยกเว้นสำหรับ powershell ที่มี -Command และ Start-Process (ปลอดภัยสำหรับ Run as Admin) if (trimmedCommand.startsWith('powershell -Command "Start-Process')) { console.log(' Allowed safe powershell command for admin mode'); return { original: command, sanitized: trimmedCommand, baseCommand: 'powershell', isAllowed: true }; } // ตรวจสอบ dangerous patterns for (const pattern of this.dangerousPatterns) { if (pattern.test(trimmedCommand)) { throw new Error(`Dangerous command pattern detected: ${pattern.source}`); } } // แยกคำสั่งหลักออกมา const commandParts = trimmedCommand.split(/\s+/); const baseCommand = commandParts[0].toLowerCase(); // ตรวจสอบว่าคำสั่งหลักอยู่ใน whitelist หรือไม่ if (!this.allowedCommands.has(baseCommand)) { throw new Error(`Command not allowed: ${baseCommand}`); } // ตรวจสอบ path traversal if (trimmedCommand.includes('../') || trimmedCommand.includes('..\\')) { throw new Error('Path traversal detected in command'); } // จำกัดความยาวคำสั่ง if (trimmedCommand.length > 500) { throw new Error('Command too long (max 500 characters)'); } console.log(` Command sanitized: ${baseCommand}`); return { original: command, sanitized: trimmedCommand, baseCommand: baseCommand, isAllowed: true }; } /** * เพิ่มคำสั่งที่อนุญาต */ addAllowedCommand(command) { this.allowedCommands.add(command.toLowerCase()); console.log(` Added allowed command: ${command}`); } /** * ลบคำสั่งที่อนุญาต */ removeAllowedCommand(command) { this.allowedCommands.delete(command.toLowerCase()); console.log(` Removed allowed command: ${command}`); } /** * ดูรายการคำสั่งที่อนุญาต */ getAllowedCommands() { return Array.from(this.allowedCommands); } } // สร้าง instance ของระบบป้องกัน const antiDebugging = new AntiDebuggingSystem(); const ipcSecurity = new IPCSecuritySystem(); // Import generate-manifests function for production builds const { generateManifests } = require('./generate-manifests.js'); // ฟังก์ชันตรวจสอบ Digital Signature และ Integrity function checkAppIntegrity() { console.log(' Verifying application integrity & signature...'); // ข้าม checksum verification ในโหมด development if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode detected - skipping checksum verification'); return true; } try { // --- 1. อ่านไฟล์ทั้งหมดที่จำเป็น --- // Security files are now stored inside ASAR for better protection let checksumsPath, signaturePath, publicKeyPath; if (app.isPackaged) { // Production: อ่านจากใน ASAR (ปลอดภัย) checksumsPath = path.join(__dirname, 'checksums.json'); signaturePath = path.join(__dirname, 'checksums.sig'); publicKeyPath = path.join(__dirname, 'public_key.pem'); console.log(' Production mode: Reading security files from ASAR'); } else { // Development: อ่านจาก project root checksumsPath = path.join(__dirname, 'checksums.json'); signaturePath = path.join(__dirname, 'checksums.sig'); publicKeyPath = path.join(__dirname, 'public_key.pem'); console.log(' Development mode: Reading security files from project root'); } // ตรวจสอบว่าไฟล์ security มีอยู่หรือไม่ if (!fs.existsSync(checksumsPath) || !fs.existsSync(signaturePath) || !fs.existsSync(publicKeyPath)) { console.log(' Security files not found - skipping integrity check (Development mode?)'); return true; // ในโหมดพัฒนาหรือไม่มีไฟล์ security ให้ผ่าน } const storedChecksumsJson = fs.readFileSync(checksumsPath, 'utf8'); const signature = fs.readFileSync(signaturePath, 'utf8'); const publicKey = fs.readFileSync(publicKeyPath, 'utf8'); // --- 2. ตรวจสอบลายเซ็นก่อน (Verify Signature) --- const verifier = crypto.createVerify('sha256'); verifier.update(storedChecksumsJson); verifier.end(); if (!verifier.verify(publicKey, signature, 'hex')) { // ถ้าลายเซ็นไม่ถูกต้อง แสดงว่า checksums.json ถูกแก้ไข! dialog.showErrorBox('Security Alert', 'Checksum file signature is invalid. The application has been tampered with.'); return false; } console.log(' Signature verification passed.'); // --- 3. ถ้าลายเซ็นถูกต้อง ค่อยตรวจสอบ Integrity ของไฟล์ --- const storedChecksums = JSON.parse(storedChecksumsJson); for (const filePath in storedChecksums) { const fullPath = path.join(__dirname, filePath); if (!fs.existsSync(fullPath)) { console.log(` Security file missing: ${filePath} - skipping check`); continue; // ข้ามไฟล์ที่ไม่มี แทนที่จะ error } const fileContent = fs.readFileSync(fullPath); const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex'); if (currentHash !== storedChecksums[filePath]) { // ถ้า Hash ไม่ตรงกัน แสดงว่าไฟล์ถูกแก้ไข! dialog.showErrorBox('Security Alert', `File tampering detected: ${filePath}. The program will now exit.`); return false; } } console.log(' All file integrity checks passed.'); return true; } catch (error) { console.error(' Security check error:', error.message); // ในกรณีที่เกิดข้อผิดพลาดในการตรวจสอบ ให้ผ่านในโหมดพัฒนา if (!app.isPackaged) { console.log(' Development mode: Skipping security check due to error'); return true; } dialog.showErrorBox('Fatal Error', `A critical error occurred during security check: ${error.message}`); return false; } } const isPackaged = app.isPackaged; // เก็บ isDev ไว้เพื่อ backward compatibility const isDev = isDevMode; // Build Dashboard - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately) // ฟังก์ชันสำหรับหาตำแหน่ง node.exe และ npm-cli.js ที่ถูกต้อง (เวอร์ชันอัปเดต) function getBundledNpmPaths() { if (isPackaged) { // เมื่อ Pack แอปแล้ว: ชี้ไปที่ไฟล์ที่เราฝังไว้ใน resources const nodeDir = path.join(process.resourcesPath, 'node'); return { nodePath: path.join(nodeDir, 'node.exe'), npmCliPath: path.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js') }; } else { // ตอนพัฒนา: ใช้ npm ของเครื่องตามปกติ return { nodePath: 'node', // ใช้ node ของระบบ npmCliPath: 'npm' // ใช้ npm ของระบบ (วิธีนี้จะเปลี่ยนไปเล็กน้อย) }; } } let mainWindow; // [CLEANED] Removed authentication window variables and functions let splashWindow; // เพิ่มตัวแปรสำหรับ splash window let debugWindow; // เพิ่มตัวแปรสำหรับ debug window // --- CMD Logger สำหรับแสดงผล Log ใน CMD Window --- const cmdLogger = { info: (message, ...args) => { // แสดงผลข้อความเป็นสีเขียวใน CMD console.log('\x1b[32m%s\x1b[0m', `[INFO] ${message}`, ...args); }, warn: (message, ...args) => { // แสดงผลข้อความเป็นสีเหลือง console.warn('\x1b[33m%s\x1b[0m', `[WARN] ${message}`, ...args); }, error: (message, ...args) => { // แสดงผลข้อความเป็นสีแดง console.error('\x1b[31m%s\x1b[0m', `[ERROR] ${message}`, ...args); }, debug: (message, ...args) => { // แสดงผลเฉพาะใน Dev Mode const isDevMode = process.argv.includes('--dev-mode') || process.argv.includes('--dev') || !app.isPackaged; if (isDevMode) { console.log('\x1b[36m%s\x1b[0m', `[DEBUG] ${message}`, ...args); } } }; // Initialize Core Components - Simplified for ValidationGateway-centric architecture const validationGateway = new ValidationGateway(); // ASAR-Safe Path Helper Functions function getAppBasePath() { if (app.isPackaged) { // Production: ใช้ path ข้างนอก app.asar return path.dirname(app.getPath('exe')); } else { // Development: ใช้ __dirname ปกติ return __dirname; } } function getUnpackedPath(relativePath) { if (app.isPackaged) { // Production: ไฟล์ที่ unpack อยู่ใน app.asar.unpacked const appPath = app.getAppPath(); return path.join(path.dirname(appPath), 'app.asar.unpacked', relativePath); } else { // Development: ใช้ path ปกติ return path.join(__dirname, relativePath); } } function getResourcePath(relativePath) { if (app.isPackaged) { // Production: resources อยู่ใน app.asar (สำหรับไฟล์ที่ไม่ต้อง unpack) return path.join(app.getAppPath(), relativePath); } else { // Development: ใช้ path ปกติ return path.join(__dirname, relativePath); } } // Create splash screen window first function createSplashWindow() { // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles) const iconPath = isPackaged ? path.join(getAppBasePath(), 'icon.png') : getResourcePath('icon.png'); // เส้นทางไฟล์ที่ถูกต้องสำหรับ splash.html (extraFiles) const splashPath = isPackaged ? path.join(getAppBasePath(), 'splash.html') : path.join(__dirname, 'splash.html'); splashWindow = new BrowserWindow({ width: 600, height: 500, frame: false, alwaysOnTop: true, transparent: false, resizable: false, center: true, webPreferences: { nodeIntegration: false, contextIsolation: true }, icon: iconPath }); splashWindow.loadFile(splashPath); splashWindow.show(); console.log(' Splash screen created and shown'); console.log(` Icon path: ${iconPath}`); console.log(` Splash path: ${splashPath}`); // Close splash and create main window after loading completes setTimeout(() => { createMainWindow(); if (splashWindow && !splashWindow.isDestroyed()) { splashWindow.close(); splashWindow = null; console.log(' Splash closed, main window created'); } }, 4000); // Slightly longer to match progress animation return splashWindow; } function createMainWindow() { // เส้นทางไฟล์ที่ถูกต้องสำหรับ icon.png (extraFiles) const iconPath = isPackaged ? path.join(getAppBasePath(), 'icon.png') : getResourcePath('icon.png'); mainWindow = new BrowserWindow({ width: 1400, height: 900, minWidth: 800, minHeight: 600, title: 'Chahuadev Framework - Plugin Management System', icon: iconPath, autoHideMenuBar: true, webPreferences: { nodeIntegration: false, contextIsolation: true, enableRemoteModule: false, preload: getResourcePath('preload.js'), webSecurity: true, sandbox: true, webviewTag: true // เพิ่มบรรทัดนี้เพื่อเปิดใช้งาน }, show: false }); // Load the framework interface mainWindow.loadFile('app.html'); console.log(` Main window icon path: ${iconPath}`); // Show when ready mainWindow.once('ready-to-show', () => { mainWindow.show(); console.log(' Chahuadev Framework Desktop App ready!'); // เริ่มระบบป้องกันการดีบัก (Fort-Knox Level Security) antiDebugging.start(mainWindow); }); // Handle window closed mainWindow.on('closed', () => { mainWindow = null; // หยุดระบบป้องกัน antiDebugging.stop(); // Cleanup all plugins cleanupAllPlugins(); }); // Development tools if (process.env.NODE_ENV === 'development') { mainWindow.webContents.openDevTools(); } } // Build Dashboard Functions - เฉพาะโหมดพัฒนา (Removed - Use builder.html separately) // Create Developer Menu - เฉพาะโหมดพัฒนา function createDeveloperMenu() { if (!isDevMode) return; // เฉพาะโหมดพัฒนาเท่านั้น const mainMenu = Menu.buildFromTemplate([ { label: 'เครื่องมือนักพัฒนา', submenu: [ { role: 'toggleDevTools', label: 'เปิด/ปิด DevTools' }, { role: 'reload', label: 'โหลดใหม่' }, { role: 'forceReload', label: 'บังคับโหลดใหม่' }, { type: 'separator' } ] }, { label: 'มุมมอง', submenu: [ { role: 'resetZoom', label: 'รีเซ็ตการซูม' }, { role: 'zoomIn', label: 'ซูมเข้า' }, { role: 'zoomOut', label: 'ซูมออก' }, { type: 'separator' }, { role: 'togglefullscreen', label: 'เปิด/ปิดเต็มจอ' } ] } ]); Menu.setApplicationMenu(mainMenu); console.log(' Developer menu created'); } // Cleanup All Plugins - Now handled by ValidationGateway async function cleanupAllPlugins() { console.log(' Cleaning up all plugins...'); try { // ValidationGateway will handle plugin cleanup console.log(' Plugin cleanup delegated to ValidationGateway'); } catch (error) { console.error(' Plugin cleanup failed:', error.message); } } // ระบบตรวจสอบ Runtime Integrity เป็นระยะๆ let runtimeIntegrityInterval = null; let integrityCheckCount = 0; const MAX_INTEGRITY_CHECKS = 10; // จำกัดจำนวนครั้งเพื่อไม่ให้กินทรัพยากรมากเกินไป function startRuntimeIntegrityChecks() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode: Skipping runtime integrity checks'); return; } console.log(' Starting periodic runtime integrity checks...'); runtimeIntegrityInterval = setInterval(() => { integrityCheckCount++; if (integrityCheckCount > MAX_INTEGRITY_CHECKS) { console.log(' Runtime integrity check limit reached, stopping periodic checks'); stopRuntimeIntegrityChecks(); return; } console.log(` Runtime integrity check #${integrityCheckCount}...`); try { // ตรวจสอบไฟล์สำคัญ const criticalFiles = [ 'main.js', 'preload.js', 'package.json' ]; const storedChecksumsPath = path.join(__dirname, 'checksums.json'); if (!fs.existsSync(storedChecksumsPath)) { console.log(' Checksums file not found for runtime check'); return; } const storedChecksums = JSON.parse(fs.readFileSync(storedChecksumsPath, 'utf8')); for (const fileName of criticalFiles) { if (!storedChecksums[fileName]) continue; const filePath = path.join(__dirname, fileName); if (!fs.existsSync(filePath)) continue; const fileContent = fs.readFileSync(filePath); const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex'); if (currentHash !== storedChecksums[fileName]) { console.error(` RUNTIME TAMPERING DETECTED: ${fileName}`); handleRuntimeTampering(fileName); return; } } console.log(` Runtime integrity check #${integrityCheckCount} passed`); } catch (error) { console.warn(` Runtime integrity check #${integrityCheckCount} failed:`, error.message); } }, 30000); // ตรวจสอบทุก 30 วินาที } function stopRuntimeIntegrityChecks() { if (runtimeIntegrityInterval) { clearInterval(runtimeIntegrityInterval); runtimeIntegrityInterval = null; console.log(' Runtime integrity checks stopped'); } } function handleRuntimeTampering(fileName) { console.error(` CRITICAL SECURITY ALERT: Runtime tampering detected in ${fileName}`); // แสดงแจ้งเตือนและปิดโปรแกรม dialog.showErrorBox( 'Security Alert', `Runtime tampering detected in ${fileName}. The application will now exit for security reasons.` ); // ล็อกเหตุการณ์ const logEntry = { timestamp: new Date().toISOString(), event: 'RUNTIME_TAMPERING_DETECTED', file: fileName, checkNumber: integrityCheckCount }; try { const securityLogPath = path.join(app.getPath('userData'), 'security-events.log'); fs.appendFileSync(securityLogPath, JSON.stringify(logEntry) + '\n'); } catch (error) { console.error('Failed to log security event:', error); } // ปิดโปรแกรมทันที app.quit(); } // เพิ่มฟังก์ชันตรวจสอบการเปลี่ยนแปลงในหน่วยความจำ (Memory Protection) function enableMemoryProtection() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { return; } console.log(' Enabling memory protection...'); // ตรวจสอบการเปลี่ยนแปลง critical functions const originalFunctions = { require: typeof global.require === 'function' ? global.require.toString() : '', eval: typeof global.eval === 'function' ? global.eval.toString() : '', Function: typeof global.Function === 'function' ? global.Function.toString() : '' }; setInterval(() => { try { // ตรวจสอบว่า critical functions ถูกแก้ไขหรือไม่ const currentRequire = typeof global.require === 'function' ? global.require.toString() : ''; const currentEval = typeof global.eval === 'function' ? global.eval.toString() : ''; const currentFunction = typeof global.Function === 'function' ? global.Function.toString() : ''; if (originalFunctions.require && currentRequire !== originalFunctions.require || originalFunctions.eval && currentEval !== originalFunctions.eval || originalFunctions.Function && currentFunction !== originalFunctions.Function) { console.error(' MEMORY TAMPERING DETECTED: Critical functions modified'); handleRuntimeTampering('critical-functions'); } } catch (error) { console.warn('Memory protection check failed:', error.message); } }, 60000); // ตรวจสอบทุก 1 นาที } // Supply Chain Security - ตรวจสอบ Dependencies async function checkSupplyChainSecurity() { // ข้ามในโหมดพัฒนา if (!app.isPackaged || process.argv.includes('--dev-mode')) { console.log(' Development mode: Skipping supply chain security check'); return true; } console.log(' Checking supply chain security...'); try { const packageJsonPath = path.join(__dirname, 'package.json'); const packageLockPath = path.join(__dirname, 'package-lock.json'); if (!fs.existsSync(packageJsonPath) || !fs.existsSync(packageLockPath)) { console.log(' Package files not found for supply chain check'); return true; } const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); const packageLock = JSON.parse(fs.readFileSync(packageLockPath, 'utf8')); // ตรวจสอบ Critical Dependencies const criticalDependencies = [ 'electron', 'express', 'crypto', 'fs-extra', 'archiver' ]; for (const dep of criticalDependencies) { if (packageJson.dependencies[dep]) { const installedVersion = packageLock.packages[`node_modules/${dep}`]?.version; if (!installedVersion) { console.warn(` Critical dependency ${dep} not found in package-lock.json`); continue; } // ตรวจสอบ known vulnerabilities (simplified check) if (await checkKnownVulnerabilities(dep, installedVersion)) { console.error(` Known vulnerability detected in ${dep}@${installedVersion}`); return false; } } } // ตรวจสอบ Package Integrity const lockFileHash = crypto.createHash('sha256') .update(fs.readFileSync(packageLockPath)) .digest('hex'); const expectedLockHashPath = path.join(__dirname, 'package-lock.hash'); if (fs.existsSync(expectedLockHashPath)) { const expectedHash = fs.readFileSync(expectedLockHashPath, 'utf8').trim(); if (lockFileHash !== expectedHash) { console.error(' Package-lock.json integrity check failed'); return false; } } else { // สร้าง hash file สำหรับครั้งแรก fs.writeFileSync(expectedLockHashPath, lockFileHash); console.log(' Created package-lock.hash for future integrity checks'); } console.log(' Supply chain security check passed'); return true; } catch (error) { console.error(' Supply chain security check failed:', error.message); return false; } } // ตรวจสอบ known vulnerabilities (simplified implementation) async function checkKnownVulnerabilities(packageName, version) { // รายการ packages ที่มี known issues (อัปเดตตามความเป็นจริง) const knownVulnerablePackages = { 'electron': { '<28.0.0': 'CVE-2023-xxxxx' }, 'express': { '<4.18.0': 'CVE-2022-xxxxx' } // เพิ่มรายการตามความจำเป็น }; const vulnInfo = knownVulnerablePackages[packageName]; if (!vulnInfo) return false; // ตรวจสอบเวอร์ชันที่มีปัญหา (simplified version comparison) for (const [vulnerableVersion, cve] of Object.entries(vulnInfo)) { if (vulnerableVersion.startsWith('<')) { const targetVersion = vulnerableVersion.slice(1); if (compareVersions(version, targetVersion) < 0) { console.error(` ${packageName}@${version} has ${cve}`); return true; } } } return false; } // เปรียบเทียบเวอร์ชัน (simplified) function compareVersions(version1, version2) { const v1parts = version1.split('.').map(Number); const v2parts = version2.split('.').map(Number); for (let i = 0; i < Math.max(v1parts.length, v2parts.length); i++) { const v1part = v1parts[i] || 0; const v2part = v2parts[i] || 0; if (v1part < v2part) return -1; if (v1part > v2part) return 1; } return 0; } // App event handlers app.whenReady().then(async () => { console.log(' Electron app ready, performing security checks...'); // ขั้นตอนที่ 1: ตรวจสอบ Digital Signature และ Integrity ก่อน const integrityOk = checkAppIntegrity(); if (!integrityOk) { console.log(' App integrity check failed. Shutting down.'); app.quit(); return; } // ขั้นตอนที่ 2: ตรวจสอบ Supply Chain Security const supplyChainOk = await checkSupplyChainSecurity(); if (!supplyChainOk) { console.log(' Supply chain security check failed. Shutting down.'); dialog.showErrorBox('Security Alert', 'Supply chain security check failed. Please contact support.'); app.quit(); return; } // เริ่มระบบตรวจสอบ Runtime Integrity startRuntimeIntegrityChecks(); // เปิดใช้งาน Memory Protection enableMemoryProtection(); // เพิ่ม: เริ่มการทำงานของระบบดีบั๊กเฉพาะใน Dev Mode (ปิดชั่วคราว) if (isDevMode && false) { // ปิดชั่วคราวเพื่อแก้ปัญหาการค้าง try { ApiTraceDebugger.start(); console.log('[API TRACE] ระบบติดตาม API เริ่มทำงานแล้ว (Real-time Logging)'); } catch (error) { console.error('[API TRACE] ไม่สามารถเริ่มระบบติดตาม API ได้:', error.message); } } else if (isDevMode) { console.log('[API TRACE] ระบบติดตาม API ถูกปิดชั่วคราว (กำลังแก้ไขปัญหา)'); } // ขั้นตอนที่ 3: Initialize Plugins via Gateway try { await validationGateway.initializePlugins(); console.log(' Plugins initialized via Gateway'); } catch (error) { console.warn(' Plugin initialization skipped:', error.message); } // Auto-scan projects on startup try { await handleScanProjects(); console.log(' Auto project scan completed'); } catch (error) { console.warn(' Auto project scan failed:', error.message); } // Create UI createSplashWindow(); // แก้ไขตรงนี้: เรียกใช้ createDeveloperMenu() เฉพาะใน Dev Mode if (isDevMode) { createDeveloperMenu(); } else { // ในโหมดผู้ใช้ ให้ตั้งค่าเมนูเป็น null เพื่อลบเมนูทั้งหมด Menu.setApplicationMenu(null); } app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createSplashWindow(); } }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('before-quit', async () => { console.log(' App shutting down...'); if (isDevMode) { ApiTraceDebugger.stop(); } await cleanupAllPlugins(); stopRuntimeIntegrityChecks(); }); // IPC handlers for desktop app functionality ipcMain.handle('get-app-version', () => { return app.getVersion(); }); // ========== OFFLINE DEMO AUTH IPC HANDLERS ========== // สร้าง OfflineAuthClient instance (แทนที่ DeviceAuthClient) let offlineAuthClient = null; /** * Initialize Offline Auth Client */ function getOfflineAuthClient() { if (!offlineAuthClient) { offlineAuthClient = new OfflineAuthClient(); } return offlineAuthClient; } /** * IPC Handler: เริ่มต้น Offline Auth (Dashboard) */ ipcMain.handle('auth:start-device-flow', async () => { try { console.log(' [OFFLINE AUTH] Initializing demo auth screen...'); const client = getOfflineAuthClient(); const result = await client.startDeviceFlow(); return { success: true, data: result }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to initialize:', error); return { success: false, error: error.message }; } }); /** * IPC Handler: Offline Authentication (ล็อคอินแบบออฟไลน์) */ ipcMain.handle('auth:offline-login', async (event, { username, password }) => { try { if (!username || !password) { throw new Error('ชื่อผู้ใช้และรหัสผ่านจำเป็น'); } const client = getOfflineAuthClient(); const result = await client.authenticateOffline(username, password); if (result.success && result.data) { console.log(' [OFFLINE AUTH] User authenticated successfully'); // Inject tokens to webview try { await injectTokensToWebview(result.data); console.log(' [OFFLINE AUTH] Tokens injected to webviews'); } catch (injectError) { console.warn(' [OFFLINE AUTH] Token injection failed:', injectError.message); } } return result; } catch (error) { console.error(' [OFFLINE AUTH] Login failed:', error); return { success: false, error: error.message }; } }); /** * IPC Handler: Polling Device Status (รอ user approve) - Offline Mode */ ipcMain.handle('auth:poll-device', async (event, deviceCode) => { try { if (!deviceCode) { throw new Error('Device code is required'); } const client = getOfflineAuthClient(); const result = await client.pollDeviceStatus(deviceCode); return { success: true, data: result }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to poll device status:', error); return { success: false, error: error.message }; } }); /** * IPC Handler: ดึงข้อมูล User ปัจจุบัน */ ipcMain.handle('auth:get-current-user', async () => { try { const client = getOfflineAuthClient(); const tokenData = await client.loadTokens(); if (tokenData.success) { return { success: true, data: tokenData.data.user, authenticated: true }; } else { return { success: true, data: null, authenticated: false, error: tokenData.error }; } } catch (error) { console.error(' [OFFLINE AUTH] Failed to get current user:', error); return { success: false, error: error.message, authenticated: false }; } }); /** * IPC Handler: Logout (ลบ tokens) */ ipcMain.handle('auth:logout', async () => { try { console.log(' [OFFLINE AUTH] Logging out...'); const client = getOfflineAuthClient(); await client.removeTokens(); return { success: true, message: 'Logged out successfully' }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to logout:', error); return { success: false, error: error.message }; } }); /** * IPC Handler: ตรวจสอบสถานะ Authentication */ ipcMain.handle('auth:check-status', async () => { try { const client = getOfflineAuthClient(); const tokenData = await client.loadTokens(); return { success: true, authenticated: tokenData.success, user: tokenData.success ? tokenData.data.user : null, tokenExists: tokenData.success, error: tokenData.success ? null : tokenData.error }; } catch (error) { console.error(' [OFFLINE AUTH] Failed to check auth status:', error); return { success: false, authenticated: false, error: error.message }; } }); /** * Inject authentication tokens to webview * @param {Object} tokens - Token data to inject */ async function injectTokensToWebview(tokens) { console.log(' [Webview] Injecting tokens to active webviews'); try { if (!mainWindow || !mainWindow.webContents) { throw new Error('Main window not available'); } // Send tokens to all webviews through the main window mainWindow.webContents.send('auth:inject-to-webviews', tokens); console.log(' [Webview] Tokens sent to webviews'); return { success: true }; } catch (error) { console.error(' [Webview] Token injection failed:', error); throw error; } } // [CLEANED] Removed old authentication IPC handlers - replaced with new Device Flow handlers above ipcMain.handle('webview:inject-tokens', async (event, { webviewId, tokens }) => { console.log(`[WEBVIEW] Injecting tokens to webview ${webviewId}...`); try { await injectTokensToWebview(tokens); return { success: true }; } catch (error) { return { success: false, error: error.message }; } }); // Handle webview request for auth tokens ipcMain.handle('webview:request-auth-tokens', async (event) => { console.log(' [Webview] Webview requesting auth tokens'); try { const client = getDeviceAuthClient(); const tokenData = await client.loadTokens(); if (tokenData.success) { // Send tokens back to the requesting webview event.sender.send('auth:inject-tokens', tokenData.data); console.log(' [Webview] Tokens sent to requesting webview'); return { success: true }; } else { console.log(' [Webview] No valid tokens found'); return { success: false, error: 'No authentication tokens found' }; } } catch (error) { console.error(' [Webview] Failed to retrieve tokens:', error); return { success: false, error: error.message }; } }); ipcMain.handle('show-message-box', async (event, options) => { const { dialog } = require('electron'); return await dialog.showMessageBox(mainWindow, options); }); ipcMain.handle('open-external', async (event, url) => { if (!url || typeof url !== 'string') { console.warn('Invalid URL provided to open-external:', url); return false; } try { console.log('Opening external URL:', url); await shell.openExternal(url); return true; } catch (error) { console.error('Failed to open external URL:', error); return false; } }); const API_BASE_URL = 'https://chahuadev.com'; // [เพิ่มใหม่] IPC Handler สำหรับส่ง Path ของ preload-webview.js ipcMain.handle('get-preload-webview-path', () => { try { const preloadPath = path.join(__dirname, 'preload-webview.js'); console.log(`[IPC] Providing webview preload path: ${preloadPath}`); return preloadPath; } catch (error) { console.error(' Error getting webview preload path:', error); return null; } }); ipcMain.handle('get-preload-path', () => { try { const preloadPath = path.join(__dirname, 'preload-webview.js'); console.log(`[IPC] Providing preload path: ${preloadPath}`); return preloadPath; } catch (error) { console.error(' Error getting preload path:', error); return null; } }); ipcMain.handle('get-system-info', async () => { const os = require('os'); return { platform: os.platform(), arch: os.arch(), release: os.release(), hostname: os.hostname(), userInfo: os.userInfo(), cpus: os.cpus().length, totalMemory: os.totalmem(), freeMemory: os.freemem() }; }); // --- WebView Action Handler --- ipcMain.handle('handle-webview-action', async (event, message) => { console.log(`[Main] Received action from WebView: ${message.action}`); if (message.action === 'install-plugin') { const pluginData = message.payload; console.log(`[Main] Starting Framework installation for:`, pluginData); try { const pluginId = pluginData.id || pluginData.pluginId || pluginData.name; console.log(`[Main] Installing Framework with NPM for plugin: ${pluginId}`); // ติดตั้ง Framework ผ่าน NPM const { execSync } = require('child_process'); console.log(`[Framework Install] Running: npm install -g @chahuadev/framework`); // รัน npm install command const result = execSync('npm install -g @chahuadev/framework', { encoding: 'utf8', stdio: 'pipe' }); console.log(` [Framework Install] NPM Output:`, result); console.log(` [Framework Install] Framework installed successfully`); // แจ้งให้ UI ทราบผลลัพธ์ if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` ติดตั้ง Chahua Framework สำเร็จ`); mainWindow.webContents.send('refresh-plugins'); } return { success: true, installMethod: 'npm' }; } catch (error) { console.error('[Main] Framework installation error:', error); // แจ้งข้อผิดพลาดให้ UI if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดในการติดตั้ง Framework: ${error.message}`); } return { success: false, error: error.message }; } } return { success: false, error: 'Unknown action' }; }); // SECURE NPM COMMAND EXECUTION - ผ่าน ValidationGateway ipcMain.handle('execute-npm-command', async (event, command) => { try { console.log(`[Main] NPM Command Request: ${command}`); // ส่งคำขอไปยัง ValidationGateway เพื่อตรวจสอบความปลอดภัย const result = await validationGateway.processCommand({ action: 'execute-npm-command', command: command, userAgent: 'Electron-App', timestamp: new Date().toISOString() }); // แจ้งผลลัพธ์ให้ UI if (mainWindow && mainWindow.webContents) { if (result.success) { // ดึงชื่อแอปจากคำสั่งเพื่อแสดงใน notification const appMatch = command.match(/@chahuadev\/([\w-]+)/); const appName = appMatch ? appMatch[1] : 'Chahua App'; const actionMatch = command.match(/^npm\s+(install|update|uninstall)/); const action = actionMatch ? actionMatch[1] : 'process'; let message = ' ดำเนินการสำเร็จ'; if (action === 'install') message = ` ติดตั้ง ${appName} สำเร็จ`; else if (action === 'update') message = ` อัปเดต ${appName} สำเร็จ`; else if (action === 'uninstall') message = ` ถอนการติดตั้ง ${appName} สำเร็จ`; mainWindow.webContents.send('show-notification', message); } else { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาด: ${result.error}`); } } return result; } catch (error) { console.error(`[Main] NPM Command Handler Failed:`, error.message); // แจ้งข้อผิดพลาดให้ UI if (mainWindow && mainWindow.webContents) { mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดภายใน: ${error.message}`); } return { success: false, error: error.message, command: command, securityLevel: 'SYSTEM_ERROR' }; } }); // IPC Handler: Run Manifest Generator (Production-Safe) ipcMain.handle('run-manifest-generator', async () => { try { console.log(' [IPC] Running manifest generator function directly...'); // 1. คำนวณ Path ของโฟลเดอร์ plugins ที่ถูกต้อง - FIX: ใช้ app.isPackaged let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); } // ตรวจสอบและสร้างโฟลเดอร์หากยังไม่มี if (!fs.existsSync(pluginsDir)) { fs.mkdirSync(pluginsDir, { recursive: true }); } console.log(` [IPC] Using plugins directory: ${pluginsDir}`); // 2. ส่ง Path ที่ถูกต้องเข้าไปในฟังก์ชัน await generateManifests(pluginsDir); // 3. สั่งให้ ValidationGateway โหลดปลั๊กอินใหม่! try { await validationGateway.initializePlugins(); // สั่งให้ Gateway โหลดปลั๊กอินใหม่! console.log(' Plugins reloaded via Gateway'); } catch (error) { console.warn(' Plugin reload skipped:', error.message); } console.log(' Manifest generation and plugin reload completed.'); return { success: true, output: `Manifest generation completed successfully in:\n${pluginsDir}`, message: 'Manifests generated successfully and plugin list reloaded.' }; } catch (error) { console.error(` Manifest generator failed during direct call: ${error.message}`); return { success: false, error: error.message }; } }); // IPC Handler: System Check for In-App Diagnostics ipcMain.handle('run-system-check', async () => { try { console.log(' [IPC] Running system check and auto-repair...'); // คำนวณ Path ของโฟลเดอร์ plugins let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); } // ใช้ Project Inspector เพื่อวิเคราะห์ปลั๊กอิน const projectInspector = require('./utils/project-inspector'); const analysis = await projectInspector.analyzeProject(pluginsDir); let repairResults = []; // การซ่อมแซมอัตโนมัติ if (analysis.totalIssues > 0) { console.log(` Found ${analysis.totalIssues} issues, attempting auto-repair...`); // ลองซ่อมแซมด้วยการสร้าง manifest ใหม่ try { await generateManifests(pluginsDir); repairResults.push('Generated missing manifest files'); } catch (error) { console.warn(' Auto-repair failed:', error.message); } // ลองรีโหลดปลั๊กอิน try { await validationGateway.initializePlugins(); repairResults.push('Reloaded plugin registry'); } catch (error) { console.warn(' Plugin reload failed:', error.message); } } const message = analysis.totalIssues === 0 ? 'ไม่พบปัญหาในระบบ ทุกอย่างทำงานปกติ' : `พบปัญหา ${analysis.totalIssues} รายการ - ระบบได้ทำการซ่อมแซมแล้ว`; console.log(' System check completed successfully'); return { success: true, message: message, fixed: repairResults.length > 0, repairActions: repairResults, analysis: analysis }; } catch (error) { console.error(` System check failed: ${error.message}`); return { success: false, error: error.message }; } }); // IPC Handler: Parameterized System Check ipcMain.handle('run-parameterized-system-check', async (event, params) => { try { console.log(' [IPC] Running parameterized system check...', params); const { scope, plugins } = params; // คำนวณ Path ของโฟลเดอร์ plugins let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); } let analysisResult; let repairResults = []; let recommendations = []; switch (scope) { case 'all': // วิเคราะห์ทั้งระบบ (เหมือนเดิม) const projectInspector = require('./utils/project-inspector'); analysisResult = await projectInspector.analyzeProject(pluginsDir); if (analysisResult.totalIssues > 0) { // ซ่อมแซมอัตโนมัติ try { await generateManifests(pluginsDir); repairResults.push('Generated missing manifest files'); } catch (error) { console.warn(' Auto-repair failed:', error.message); } } break; case 'plugins': // วิเคราะห์เฉพาะปลั๊กอิน const projectInspector2 = require('./utils/project-inspector'); analysisResult = await projectInspector2.analyzeProject(pluginsDir); // เน้นที่ข้อมูล type analysis if (analysisResult.typeAnalysis) { recommendations.push(...analysisResult.typeAnalysis.recommendations); } break; case 'core': // วิเคราะห์เฉพาะระบบหลัก analysisResult = { totalIssues: 0, message: 'ตรวจสอบระบบหลักเสร็จสิ้น - ไม่พบปัญหา' }; break; case 'dependencies': // วิเคราะห์ dependencies analysisResult = await analyzeDependencies(pluginsDir); break; case 'specific': // วิเคราะห์ปลั๊กอินที่เลือก if (plugins && plugins.length > 0) { analysisResult = await analyzeSpecificPlugins(plugins); } else { return { success: false, error: 'กรุณาเลือกปลั๊กอินที่ต้องการตรวจสอบ' }; } break; default: return { success: false, error: 'ประเภทการวินิจฉัยไม่ถูกต้อง' }; } const message = analysisResult.totalIssues === 0 ? `ไม่พบปัญหาใน${getScopeText(scope)}` : `พบปัญหา ${analysisResult.totalIssues} รายการใน${getScopeText(scope)}`; console.log(' Parameterized system check completed successfully'); return { success: true, message: message, fixed: repairResults.length > 0, repairActions: repairResults, recommendations: recommendations, analysis: analysisResult, scope: scope }; } catch (error) { console.error(` Parameterized system check failed: ${error.message}`); return { success: false, error: error.message }; } }); // Helper functions for parameterized diagnostics function getScopeText(scope) { const texts = { 'all': 'ทั้งระบบ', 'plugins': 'ปลั๊กอิน', 'core': 'ระบบหลัก', 'dependencies': 'Dependencies', 'specific': 'ปลั๊กอินที่เลือก' }; return texts[scope] || 'ส่วนที่ระบุ'; } async function analyzeDependencies(pluginsDir) { // ตรวจสอบ dependencies ของปลั๊กอินต่างๆ const issues = []; try { const plugins = fs.readdirSync(pluginsDir); for (const plugin of plugins) { const pluginPath = path.join(pluginsDir, plugin); const stat = fs.statSync(pluginPath); if (stat.isDirectory()) { // ตรวจสอบ package.json const packageJsonPath = path.join(pluginPath, 'package.json'); if (fs.existsSync(packageJsonPath)) { try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); if (!packageJson.dependencies && !packageJson.devDependencies) { issues.push(`ปลั๊กอิน ${plugin} ไม่มี dependencies`); } } catch (error) { issues.push(`ปลั๊กอิน ${plugin} มี package.json ที่ไม่ถูกต้อง`); } } } } } catch (error) { issues.push(`ไม่สามารถตรวจสอบ dependencies ได้: ${error.message}`); } return { totalIssues: issues.length, issues: issues, message: issues.length === 0 ? 'Dependencies ทั้งหมดปกติ' : `พบปัญหา dependencies ${issues.length} รายการ` }; } async function analyzeSpecificPlugins(pluginPaths) { const projectInspector = require('./utils/project-inspector'); let totalIssues = 0; const results = []; for (const pluginPath of pluginPaths) { try { const analysis = await projectInspector.analyzeProject(pluginPath); totalIssues += analysis.totalIssues; results.push({ path: pluginPath, analysis: analysis }); } catch (error) { totalIssues++; results.push({ path: pluginPath, error: error.message }); } } return { totalIssues: totalIssues, results: results, message: `ตรวจสอบปลั๊กอิน ${pluginPaths.length} รายการเสร็จสิ้น` }; } // Removed duplicate 'get-available-plugins' handler - using ValidationGateway version instead // IPC Handler: Open Plugins Folder (NEW - สำหรับเปิดโฟลเดอร์ plugins) - FIX: ใช้ app.isPackaged ipcMain.handle('open-plugins-folder', () => { // FIX: ใช้ app.isPackaged เพื่อจัดการ plugins directory path let pluginsDir; if (app.isPackaged) { pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { pluginsDir = path.join(app.getPath('userData'), 'plugins'); } // สร้างโฟลเดอร์ถ้ายังไม่มี if (!fs.existsSync(pluginsDir)) { try { fs.mkdirSync(pluginsDir, { recursive: true }); console.log(` Created plugins directory at: ${pluginsDir}`); } catch (error) { console.error(` Failed to create plugins directory:`, error); return { success: false, error: error.message }; } } // เปิดโฟลเดอร์ใน File Explorer shell.openPath(pluginsDir); console.log(` Opened plugins folder: ${pluginsDir}`); return { success: true, path: pluginsDir }; }); // IPC Handler: Get All Available Plugins (via ValidationGateway) ipcMain.handle('get-available-plugins', async () => { try { // ValidationGateway's PluginManager will handle this const result = await validationGateway.processCommand({ action: 'list-plugins' }); console.log(` Returning available plugins via Gateway`); return result; } catch (error) { console.error(' Failed to get plugins:', error.message); return { success: false, error: error.message }; } }); // Plugin-specific IPC handlers removed - all commands now go through execute-command -> ValidationGateway // Plugin command handling functions removed - now handled by ValidationGateway // IPC Handler: Run NPM Project Commands (for HTML plugins) ipcMain.handle('run-npm-project', async (event, payload) => { console.log(' [IPC] NPM Project command received:', payload); try { // Check if this comes from an HTML plugin window const senderWebContentsId = event.sender.id; const htmlPluginInfo = global.htmlPluginWindows?.get(senderWebContentsId); if (!htmlPluginInfo || !htmlPluginInfo.isProjectManager) { throw new Error('This command can only be executed from HTML project management plugins'); } console.log(` [IPC] Running command from ${htmlPluginInfo.pluginName}`); // Security validation const context = { pipelineId: 'html_plugin_' + Date.now(), type: 'html_plugin_request', request: payload, htmlPlugin: htmlPluginInfo.pluginName }; const securityResult = await validationGateway.validate(payload, context); if (!securityResult.valid) { console.log(' [IPC] Security validation failed for HTML plugin:', securityResult.message); return { success: false, error: securityResult.message || 'Security validation failed' }; } // Execute based on action type switch (payload.action) { case 'scan-projects': return await handleScanProjects(); case 'scan-project': return await handleScanProject(payload.project, payload.path); default: // Regular command execution const NodeStrategy = require('./strategies/NodeStrategy'); const nodeStrategy = new NodeStrategy(); let projectPath = payload.path || payload.cwd; if (!projectPath) { projectPath = path.join(__dirname, 'plugins', 'Chahuadev_Studio_V.10.0.0'); } const commandContext = { command: payload.command || payload.action, projectPath: projectPath, options: { timeout: 60000, env: {} } }; const result = await nodeStrategy.execute(commandContext); return { success: result.success, data: result.success ? { success: true, output: result.output, message: `Command executed successfully`, command: commandContext.command, exitCode: result.exitCode, duration: result.duration } : null, error: result.success ? null : result.error, timestamp: new Date().toISOString(), source: 'html_plugin_npm' }; } } catch (error) { console.error(' [IPC] HTML Plugin NPM command error:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; } }); // Project analysis functions removed - now handled by ValidationGateway's SystemDetector // Handler: Scan Projects (NEW!) async function handleScanProjects() { console.log(' [Scan] Starting project scan...'); try { // ใช้ SystemDetector ในการสแกน const SystemDetector = require('./modules/system-detector'); const systemDetector = new SystemDetector(); // เรียกใช้ scanProjects ที่ SystemDetector const result = await systemDetector.scanProjects(); console.log(` [Scan] Scan complete: ${result.count} projects found`); return { success: true, data: result, timestamp: new Date().toISOString() }; } catch (error) { console.error(' [Scan] Error during project scan:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; } } // Handler: Scan Single Project (NEW!) async function handleScanProject(projectName, projectPath) { console.log(` [Scan] Scanning single project: ${projectName} at ${projectPath}`); try { // ใช้ SystemDetector ในการสแกน const SystemDetector = require('./modules/system-detector'); const systemDetector = new SystemDetector(); // เรียกใช้ detect สำหรับโปรเจกต์เดียว const result = await systemDetector.detect(projectPath); console.log(` [Scan] Single project scan complete: ${result.type} (${result.confidence}%)`); return { success: true, data: result, timestamp: new Date().toISOString() }; } catch (error) { console.error(' [Scan] Error during single project scan:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; } } // IPC Handler: Execute Quick Commands (NEW!) - with Fort-Knox Security ipcMain.handle('execute-quick-command', async (event, command) => { console.log(' [IPC] Quick command received:', command); try { // SECURITY: ตรวจสอบและทำความสะอาดคำสั่งก่อนรัน let sanitizedResult; try { sanitizedResult = ipcSecurity.sanitizeCommand(command); } catch (securityError) { console.error(' [Security] Command blocked:', securityError.message); return { success: false, error: `Security violation: ${securityError.message}`, securityAlert: true }; } // Parse --cwd= parameter if present let workingDir = null; let cleanCommand = sanitizedResult.sanitized; if (cleanCommand.includes('--cwd=')) { const cwdMatch = cleanCommand.match(/--cwd=([^\s]+)/); if (cwdMatch) { workingDir = cwdMatch[1]; cleanCommand = cleanCommand.replace(/--cwd=[^\s]+\s*/, '').trim(); console.log(` [IPC] Working directory: ${workingDir}`); // ตรวจสอบ working directory path if (workingDir.includes('../') || workingDir.includes('..\\')) { throw new Error('Path traversal detected in working directory'); } } } // Execute using NodeStrategy const NodeStrategy = require('./strategies/NodeStrategy'); const nodeStrategy = new NodeStrategy(); const commandContext = { command: cleanCommand, projectPath: workingDir || getUnpackedPath('plugins/Chahuadev_Studio_V.10.0.0'), options: { timeout: 60000, env: {} } }; const result = await nodeStrategy.execute(commandContext); return { success: result.success, data: result.success ? { output: result.output, message: `Quick command executed: ${cleanCommand}`, exitCode: result.exitCode, securityInfo: `Command sanitized and executed safely (${sanitizedResult.baseCommand})` } : null, error: result.success ? null : result.error }; } catch (error) { console.error(' [IPC] Quick command error:', error.message); return { success: false, error: error.message }; } }); // IPC Handler: Execute Plugin Commands (NEW - to bridge UI buttons) ipcMain.handle('execute-plugin-command', async (event, pluginName, command, data) => { console.log(` [IPC] Received command: [${command}] on [${pluginName}]`); if (!validationGateway) { return { success: false, error: 'Validation Gateway not initialized' }; } try { // หา Path ของโปรเจกต์ (ปลั๊กอิน) ก่อน const projectPath = await validationGateway.getPluginPath(pluginName); // สร้าง request object ที่สมบูรณ์เพื่อส่งให้ Gateway const request = { action: command, // action คือคำสั่งที่ได้จากปุ่มโดยตรง เช่น 'launch-exe' pluginName: pluginName, projectPath: projectPath, // ส่ง Path ที่ถูกต้องไปด้วย data: data || {} }; console.log(`Forwarding to Gateway processCommand:`, request); // ส่งให้ processCommand ใน Gateway จัดการ ซึ่งมี switch-case รองรับทุก action const result = await validationGateway.processCommand(request); return result; } catch (error) { console.error(` [IPC] Error processing command "${command}" for "${pluginName}":`, error); return { success: false, error: error.message }; } }); // MAIN IPC HANDLER: Execute Commands via ValidationGateway ipcMain.handle('execute-command', async (event, payload) => { console.log(' [IPC] Received command, forwarding to Validation Gateway:', payload); try { // ส่งต่อไปให้ Gateway จัดการทั้งหมด return await validationGateway.processCommand(payload); } catch (error) { console.error(' [IPC] Error forwarding to ValidationGateway:', error.message); return { success: false, error: error.message, timestamp: new Date().toISOString() }; } }); // IPC Handler: Get Run Mode (Development vs Production) ipcMain.handle('get-run-mode', () => { console.log(` [IPC] Checking run mode - isDevMode: ${isDevMode}`); return { isDevMode: isDevMode }; }); // IPC Handler: Build App Process (NEW!) ipcMain.handle('start-build', async (event) => { console.log(' [IPC] Starting build process...'); // ใช้ child_process เพื่อรันคำสั่ง electron-builder const { exec } = require('child_process'); // คำสั่ง build สำหรับ Windows const command = 'npx electron-builder --win --x64'; // ได้ project root จากฟังก์ชันที่มีอยู่แล้ว const projectRoot = getAppBasePath(); console.log(` Starting build with command: ${command}`); console.log(` Project root: ${projectRoot}`); try { // รันคำสั่ง build const buildProcess = exec(command, { cwd: projectRoot }); // ส่ง Log กลับไปที่ UI แบบ Real-time buildProcess.stdout.on('data', (data) => { console.log(` [STDOUT] ${data}`); // ส่ง Log กลับไปที่หน้าต่างหลักผ่านช่องทาง 'build-log' if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', data.toString()); } }); // ส่ง Error Log กลับไป buildProcess.stderr.on('data', (data) => { console.log(` [STDERR] ${data}`); if (mainWindow && !mainWindow.isDestroyed()) { // ส่ง Error Log กลับไปในรูปแบบที่แตกต่าง mainWindow.webContents.send('build-log', `[ERROR] ${data.toString()}`); } }); // เมื่อกระบวนการ Build สิ้นสุดลง buildProcess.on('close', (code) => { const message = code === 0 ? ' กระบวนการ Build เสร็จสมบูรณ์!' : ` กระบวนการ Build ล้มเหลว (Exit Code: ${code})`; console.log(` Build process finished with code: ${code}`); if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', `\n ${message}`); if (code === 0) { // ส่งข้อมูลเพิ่มเติมเมื่อ Build สำเร็จ mainWindow.webContents.send('build-log', ' ไฟล์ Build สำเร็จแล้ว สามารถดูได้ในโฟลเดอร์ dist/'); mainWindow.webContents.send('build-log', ' ไฟล์ที่สร้าง: *.exe, *.msi, *.zip'); mainWindow.webContents.send('build-log', ' สามารถนำไปติดตั้งบนเครื่องอื่นได้แล้ว!'); } } }); // เมื่อมี error ในการ start process buildProcess.on('error', (error) => { console.error(` Build process error:`, error); if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send('build-log', `[ERROR] ไม่สามารถเริ่ม Build ได้: ${error.message}`); } }); return { success: true }; } catch (error) { console.error(` Build command failed to start:`, error); return { success: false, error: error.message }; } }); // System Information API Handlers - สำหรับ debugger.js ipcMain.handle('system:get-info', async () => { try { const info = { platform: os.platform(), arch: os.arch(), version: os.version(), uptime: os.uptime(), totalmem: os.totalmem(), freemem: os.freemem(), cpus: os.cpus().length, networkInterfaces: Object.keys(os.networkInterfaces()).length }; return info; } catch (error) { console.error(' [System] Get info error:', error); throw error; } }); ipcMain.handle('system:get-cwd', async () => { try { return process.cwd(); } catch (error) { console.error(' [System] Get CWD error:', error); throw error; } }); ipcMain.handle('system:get-version', async () => { try { return app.getVersion(); } catch (error) { console.error(' [System] Get version error:', error); throw error; } }); ipcMain.handle('system:get-memory-usage', async () => { try { return process.memoryUsage(); } catch (error) { console.error(' [System] Get memory usage error:', error); throw error; } }); ipcMain.handle('system:get-cpu-usage', async () => { try { return os.cpus(); } catch (error) { console.error(' [System] Get CPU usage error:', error); throw error; } }); ipcMain.handle('system:get-platform', async () => { try { return { platform: process.platform, arch: process.arch, version: process.version }; } catch (error) { console.error(' [System] Get platform error:', error); throw error; } }); ipcMain.handle('system:get-plugins-path', async () => { try { let pluginsDir; if (app.isPackaged) { // โหมดใช้งานจริง: อยู่ข้างไฟล์ .exe pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); } else { // โหมดพัฒนา: อยู่ใน AppData pluginsDir = path.join(app.getPath('userData'), 'plugins'); } return pluginsDir; } catch (error) { console.error(' [System] Get plugins path error:', error); throw error; } }); // ========== FORT-KNOX SECURITY IPC HANDLERS ========== ipcMain.handle('process-command', async (event, request) => { try { console.log(' [Main] Processing command:', request.command || request.action); const result = await validationGateway.processCommand(request); return result; } catch (error) { console.error(' [Main] Process command error:', error); return { success: false, error: error.message }; } }); // ========== FORT-KNOX SECURITY IPC HANDLERS ========== // IPC Handler: ตรวจสอบโหมด Developer Mode ipcMain.handle('security:get-dev-mode', async () => { try { return { success: true, data: { isDevMode: antiDebugging.isDevMode, detectionMethod: antiDebugging.detectDeveloperMode ? 'enhanced' : 'legacy', timestamp: Date.now() } }; } catch (error) { console.error(' Error getting dev mode status:', error); return { success: false, error: error.message, data: { isDevMode: false } // Default to production mode on error }; } }); // IPC Handler: ตรวจสอบสถานะความปลอดภัย ipcMain.handle('security:get-status', async () => { try { return { success: true, data: { antiDebugging: { enabled: !antiDebugging.isDevMode, mode: antiDebugging.isDevMode ? 'development' : 'production', suspiciousActivityCount: antiDebugging.suspiciousActivityCount, maxSuspiciousActivity: antiDebugging.maxSuspiciousActivity }, ipcSecurity: { enabled: true, allowedCommands: ipcSecurity.getAllowedCommands(), commandCount: ipcSecurity.getAllowedCommands().length }, buildMode: app.isPackaged ? 'production' : 'development', version: app.getVersion(), securityLevel: 'Fort-Knox' } }; } catch (error) { return { success: false, error: error.message }; } }); // IPC Handler: ทดสอบการทำงานของระบบความปลอดภัย ipcMain.handle('security:test-command-sanitization', async (event, testCommand) => { try { const result = ipcSecurity.sanitizeCommand(testCommand); return { success: true, data: { original: result.original, sanitized: result.sanitized, baseCommand: result.baseCommand, isAllowed: result.isAllowed, testResult: 'Command passed security validation' } }; } catch (error) { return { success: false, error: error.message, data: { original: testCommand, testResult: 'Command blocked by security system', reason: error.message } }; } }); module.exports = { mainWindow };