|
|
| const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron'); |
| const path = require('path'); |
| const fs = require('fs'); |
| const os = require('os'); |
| const crypto = require('crypto'); |
| const https = require('https'); |
| const { spawn, exec } = require('child_process'); |
|
|
| |
| if (app.isPackaged) { |
| process.argv = process.argv.filter(arg => arg !== '--dev-mode' && arg !== '--dev'); |
| } |
|
|
| |
| |
| |
|
|
| |
| 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'})`); |
|
|
| |
| |
| |
| |
|
|
| |
| const ApiTraceDebugger = { |
| start: () => console.log('[API TRACE] (Disabled - using Offline Auth)'), |
| stop: () => console.log('[API TRACE] (Disabled)') |
| }; |
|
|
| |
| |
| |
| |
|
|
| |
| const ValidationGateway = require('./validation_gateway'); |
| |
|
|
| |
| const TamperDetector = require('./modules/tamper-detector'); |
|
|
| |
| |
| |
| |
| 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'); |
| } |
|
|
| |
| |
| |
| ensureStorageDirectory() { |
| const dir = path.dirname(this.storagePath); |
| if (!fs.existsSync(dir)) { |
| fs.mkdirSync(dir, { recursive: true }); |
| } |
| } |
|
|
| |
| |
| |
| async startDeviceFlow() { |
| console.log(' [OFFLINE AUTH] Device Flow simulation started'); |
| |
| |
| 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; |
| } |
|
|
| |
| |
| |
| async authenticateOffline(username, password) { |
| console.log(` [OFFLINE AUTH] Attempting login: ${username}`); |
|
|
| |
| const user = this.demoUsers[username]; |
| if (!user || user.password !== password) { |
| console.error(' [OFFLINE AUTH] Invalid credentials'); |
| return { |
| success: false, |
| error: 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง' |
| }; |
| } |
|
|
| |
| const mockTokens = { |
| accessToken: 'mock_access_' + crypto.randomBytes(32).toString('hex'), |
| refreshToken: 'mock_refresh_' + crypto.randomBytes(32).toString('hex'), |
| expiresIn: 86400, |
| 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() |
| }; |
|
|
| |
| await this.saveTokens(mockTokens); |
|
|
| console.log(' [OFFLINE AUTH] Login successful:', user.username); |
| return { |
| success: true, |
| status: 'approved', |
| data: mockTokens |
| }; |
| } |
|
|
| |
| |
| |
| async pollDeviceStatus(deviceCode) { |
| console.log(' [OFFLINE AUTH] Polling device status (offline mode)'); |
| |
| |
| return { |
| success: true, |
| status: 'pending', |
| message: 'รอการใส่ชื่อผู้ใช้และรหัสผ่าน' |
| }; |
| } |
|
|
| |
| |
| |
| 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 }; |
| } |
| } |
|
|
| |
| |
| |
| 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')); |
|
|
| |
| 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 }; |
| } |
| } |
|
|
| |
| |
| |
| 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 }; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| class AntiDebuggingSystem { |
| constructor() { |
| this.checkInterval = null; |
| |
| 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'); |
| } |
|
|
| |
| |
| |
| |
| detectDeveloperMode() { |
| const indicators = { |
| |
| hasDevArgs: process.argv.includes('--dev-mode') || process.argv.includes('--dev'), |
|
|
| |
| isUnpackaged: !app.isPackaged, |
|
|
| |
| hasDevEnv: process.env.NODE_ENV === 'development' || process.env.CHAHUA_DEV === 'true', |
|
|
| |
| hasDevPort: process.env.PORT && (process.env.PORT === '3000' || process.env.PORT === '8080'), |
|
|
| |
| hasDebugFlag: process.execArgv.some(arg => arg.includes('--inspect') || arg.includes('--debug')), |
|
|
| |
| hasDevDeps: false |
| }; |
|
|
| |
| console.log(' Developer Mode Detection Results:', indicators); |
|
|
| |
| 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(); |
|
|
| |
| this.checkInterval = setInterval(() => { |
| this.performSecurityChecks(); |
| }, 2000); |
|
|
| |
| if (mainWindow && mainWindow.webContents) { |
| mainWindow.webContents.on('devtools-opened', () => { |
| this.handleSuspiciousActivity('DevTools opened'); |
| }); |
|
|
| mainWindow.webContents.on('devtools-focused', () => { |
| this.handleSuspiciousActivity('DevTools focused'); |
| }); |
| } |
| } |
|
|
| |
| |
| |
| performSecurityChecks() { |
| try { |
| |
| if (this.mainWindow && this.mainWindow.webContents && this.mainWindow.webContents.isDevToolsOpened()) { |
| this.handleSuspiciousActivity('DevTools detected as open'); |
| return; |
| } |
|
|
| |
| if (process.platform === 'win32') { |
| this.checkForDebuggingProcesses(); |
| } |
|
|
| |
| this.checkPerformanceAnomalies(); |
|
|
| } catch (error) { |
| console.warn(' Anti-Debugging check error:', error.message); |
| } |
| } |
|
|
| |
| |
| |
| checkForDebuggingProcesses() { |
| const suspiciousProcesses = [ |
| 'cheatengine', 'x64dbg', 'x32dbg', 'ollydbg', 'windbg', |
| 'processhacker', 'pestudio', 'ida64', 'ida32', 'ghidra' |
| ]; |
|
|
| |
| 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; |
| } |
| } |
| }); |
| } |
|
|
| |
| |
| |
| checkPerformanceAnomalies() { |
| const start = Date.now(); |
|
|
| |
| let sum = 0; |
| for (let i = 0; i < 10000; i++) { |
| sum += Math.random(); |
| } |
|
|
| const duration = Date.now() - start; |
|
|
| |
| if (duration > 100) { |
| 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...'); |
|
|
| |
| 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(); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| class IPCSecuritySystem { |
| constructor() { |
| |
| this.allowedCommands = new Set([ |
| 'node', 'npm', 'git', 'where', 'which', 'echo', 'dir', 'ls', |
| 'cd', 'pwd', 'whoami', 'hostname', 'ipconfig', 'ping', |
| 'powershell', |
| 'explorer' |
| ]); |
|
|
| |
| this.dangerousPatterns = [ |
| /rm\s+-rf/i, |
| /del\s+\/[sq]/i, |
| /format\s+[cd]:/i, |
| /shutdown/i, |
| /reboot/i, |
| />\s*nul/i, |
| /`[^`]*`/, |
| /\$\([^)]*\)/, |
| /eval\s*\(/i, |
| /exec\s*\(/i |
| ]; |
|
|
| 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(); |
|
|
| |
| 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 |
| }; |
| } |
|
|
| |
| 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(); |
|
|
| |
| if (!this.allowedCommands.has(baseCommand)) { |
| throw new Error(`Command not allowed: ${baseCommand}`); |
| } |
|
|
| |
| 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); |
| } |
| } |
|
|
| |
| const antiDebugging = new AntiDebuggingSystem(); |
| const ipcSecurity = new IPCSecuritySystem(); |
|
|
| |
| const { generateManifests } = require('./generate-manifests.js'); |
|
|
| |
| function checkAppIntegrity() { |
| console.log(' Verifying application integrity & signature...'); |
|
|
| |
| if (!app.isPackaged || process.argv.includes('--dev-mode')) { |
| console.log(' Development mode detected - skipping checksum verification'); |
| return true; |
| } |
|
|
| try { |
| |
| |
| let checksumsPath, signaturePath, publicKeyPath; |
|
|
| if (app.isPackaged) { |
| |
| 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 { |
| |
| 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'); |
| } |
|
|
| |
| if (!fs.existsSync(checksumsPath) || !fs.existsSync(signaturePath) || !fs.existsSync(publicKeyPath)) { |
| console.log(' Security files not found - skipping integrity check (Development mode?)'); |
| return true; |
| } |
|
|
| const storedChecksumsJson = fs.readFileSync(checksumsPath, 'utf8'); |
| const signature = fs.readFileSync(signaturePath, 'utf8'); |
| const publicKey = fs.readFileSync(publicKeyPath, 'utf8'); |
|
|
| |
| const verifier = crypto.createVerify('sha256'); |
| verifier.update(storedChecksumsJson); |
| verifier.end(); |
|
|
| if (!verifier.verify(publicKey, signature, 'hex')) { |
| |
| dialog.showErrorBox('Security Alert', 'Checksum file signature is invalid. The application has been tampered with.'); |
| return false; |
| } |
| console.log(' Signature verification passed.'); |
|
|
| |
| 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; |
| } |
|
|
| const fileContent = fs.readFileSync(fullPath); |
| const currentHash = crypto.createHash('sha256').update(fileContent).digest('hex'); |
|
|
| if (currentHash !== storedChecksums[filePath]) { |
| |
| 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; |
|
|
| |
| const isDev = isDevMode; |
|
|
| |
|
|
| |
| function getBundledNpmPaths() { |
| if (isPackaged) { |
| |
| 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 { |
| |
| return { |
| nodePath: 'node', |
| npmCliPath: 'npm' |
| }; |
| } |
| } |
|
|
| let mainWindow; |
| |
| let splashWindow; |
| let debugWindow; |
|
|
| |
| const cmdLogger = { |
| info: (message, ...args) => { |
| |
| 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) => { |
| |
| 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); |
| } |
| } |
| }; |
|
|
| |
| const validationGateway = new ValidationGateway(); |
|
|
| |
| function getAppBasePath() { |
| if (app.isPackaged) { |
| |
| return path.dirname(app.getPath('exe')); |
| } else { |
| |
| return __dirname; |
| } |
| } |
|
|
| function getUnpackedPath(relativePath) { |
| if (app.isPackaged) { |
| |
| const appPath = app.getAppPath(); |
| return path.join(path.dirname(appPath), 'app.asar.unpacked', relativePath); |
| } else { |
| |
| return path.join(__dirname, relativePath); |
| } |
| } |
|
|
| function getResourcePath(relativePath) { |
| if (app.isPackaged) { |
| |
| return path.join(app.getAppPath(), relativePath); |
| } else { |
| |
| return path.join(__dirname, relativePath); |
| } |
| } |
|
|
| |
| function createSplashWindow() { |
| |
| const iconPath = isPackaged ? |
| path.join(getAppBasePath(), 'icon.png') : |
| getResourcePath('icon.png'); |
|
|
| |
| 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}`); |
|
|
| |
| setTimeout(() => { |
| createMainWindow(); |
| if (splashWindow && !splashWindow.isDestroyed()) { |
| splashWindow.close(); |
| splashWindow = null; |
| console.log(' Splash closed, main window created'); |
| } |
| }, 4000); |
|
|
| return splashWindow; |
| } |
|
|
| function createMainWindow() { |
| |
| 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 |
| }); |
|
|
| |
| mainWindow.loadFile('app.html'); |
|
|
| console.log(` Main window icon path: ${iconPath}`); |
|
|
| |
| mainWindow.once('ready-to-show', () => { |
| mainWindow.show(); |
| console.log(' Chahuadev Framework Desktop App ready!'); |
|
|
|
|
| |
| antiDebugging.start(mainWindow); |
| }); |
|
|
| |
| mainWindow.on('closed', () => { |
| mainWindow = null; |
| |
| antiDebugging.stop(); |
| |
| cleanupAllPlugins(); |
| }); |
|
|
| |
| if (process.env.NODE_ENV === 'development') { |
| mainWindow.webContents.openDevTools(); |
| } |
| } |
|
|
| |
|
|
| |
| 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'); |
| } |
|
|
| |
| async function cleanupAllPlugins() { |
| console.log(' Cleaning up all plugins...'); |
| try { |
| |
| console.log(' Plugin cleanup delegated to ValidationGateway'); |
| } catch (error) { |
| console.error(' Plugin cleanup failed:', error.message); |
| } |
| } |
|
|
| |
| 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); |
| } |
|
|
| 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(); |
| } |
|
|
| |
| function enableMemoryProtection() { |
| |
| if (!app.isPackaged || process.argv.includes('--dev-mode')) { |
| return; |
| } |
|
|
| console.log(' Enabling memory protection...'); |
|
|
| |
| 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 { |
| |
| 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); |
| } |
|
|
| |
| 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')); |
|
|
| |
| 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; |
| } |
|
|
| |
| if (await checkKnownVulnerabilities(dep, installedVersion)) { |
| console.error(` Known vulnerability detected in ${dep}@${installedVersion}`); |
| return false; |
| } |
| } |
| } |
|
|
| |
| 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 { |
| |
| 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; |
| } |
| } |
|
|
| |
| async function checkKnownVulnerabilities(packageName, version) { |
| |
| const knownVulnerablePackages = { |
| 'electron': { |
| '<28.0.0': 'CVE-2023-xxxxx' |
| }, |
| 'express': { |
| '<4.18.0': 'CVE-2022-xxxxx' |
| } |
| |
| }; |
|
|
| const vulnInfo = knownVulnerablePackages[packageName]; |
| if (!vulnInfo) return false; |
|
|
| |
| 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; |
| } |
|
|
| |
| 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.whenReady().then(async () => { |
| console.log(' Electron app ready, performing security checks...'); |
|
|
| |
| const integrityOk = checkAppIntegrity(); |
| if (!integrityOk) { |
| console.log(' App integrity check failed. Shutting down.'); |
| app.quit(); |
| return; |
| } |
|
|
| |
| 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; |
| } |
|
|
| |
| startRuntimeIntegrityChecks(); |
|
|
| |
| enableMemoryProtection(); |
|
|
| |
| 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 ถูกปิดชั่วคราว (กำลังแก้ไขปัญหา)'); |
| } |
|
|
| |
| try { |
| await validationGateway.initializePlugins(); |
| console.log(' Plugins initialized via Gateway'); |
| } catch (error) { |
| console.warn(' Plugin initialization skipped:', error.message); |
| } |
|
|
| |
| try { |
| await handleScanProjects(); |
| console.log(' Auto project scan completed'); |
| } catch (error) { |
| console.warn(' Auto project scan failed:', error.message); |
| } |
|
|
| |
| createSplashWindow(); |
|
|
| |
| if (isDevMode) { |
| createDeveloperMenu(); |
| } else { |
| |
| 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(); |
| }); |
|
|
| |
| ipcMain.handle('get-app-version', () => { |
| return app.getVersion(); |
| }); |
|
|
| |
|
|
| |
| let offlineAuthClient = null; |
|
|
| |
| |
| |
| function getOfflineAuthClient() { |
| if (!offlineAuthClient) { |
| offlineAuthClient = new OfflineAuthClient(); |
| } |
| return offlineAuthClient; |
| } |
|
|
| |
| |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| 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'); |
|
|
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
| |
| |
| |
| async function injectTokensToWebview(tokens) { |
| console.log(' [Webview] Injecting tokens to active webviews'); |
|
|
| try { |
| if (!mainWindow || !mainWindow.webContents) { |
| throw new Error('Main window not available'); |
| } |
|
|
| |
| 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; |
| } |
| } |
|
|
| |
|
|
| 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 }; |
| } |
| }); |
|
|
| |
| 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) { |
| |
| 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'; |
|
|
| |
| 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() |
| }; |
| }); |
|
|
| |
| 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}`); |
|
|
| |
| const { execSync } = require('child_process'); |
|
|
| console.log(`[Framework Install] Running: npm install -g @chahuadev/framework`); |
|
|
| |
| 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`); |
|
|
| |
| 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); |
|
|
| |
| if (mainWindow && mainWindow.webContents) { |
| mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดในการติดตั้ง Framework: ${error.message}`); |
| } |
|
|
| return { success: false, error: error.message }; |
| } |
| } |
|
|
| return { success: false, error: 'Unknown action' }; |
| }); |
|
|
| |
| ipcMain.handle('execute-npm-command', async (event, command) => { |
| try { |
| console.log(`[Main] NPM Command Request: ${command}`); |
|
|
| |
| const result = await validationGateway.processCommand({ |
| action: 'execute-npm-command', |
| command: command, |
| userAgent: 'Electron-App', |
| timestamp: new Date().toISOString() |
| }); |
|
|
| |
| if (mainWindow && mainWindow.webContents) { |
| if (result.success) { |
| |
| 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); |
|
|
| |
| if (mainWindow && mainWindow.webContents) { |
| mainWindow.webContents.send('show-notification', ` เกิดข้อผิดพลาดภายใน: ${error.message}`); |
| } |
|
|
| return { |
| success: false, |
| error: error.message, |
| command: command, |
| securityLevel: 'SYSTEM_ERROR' |
| }; |
| } |
| }); |
|
|
| |
| ipcMain.handle('run-manifest-generator', async () => { |
| try { |
| console.log(' [IPC] Running manifest generator function directly...'); |
|
|
| |
| 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}`); |
|
|
| |
| await generateManifests(pluginsDir); |
|
|
| |
| try { |
| await validationGateway.initializePlugins(); |
| 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 }; |
| } |
| }); |
|
|
| |
| ipcMain.handle('run-system-check', async () => { |
| try { |
| console.log(' [IPC] Running system check and auto-repair...'); |
|
|
| |
| let pluginsDir; |
| if (app.isPackaged) { |
| pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| pluginsDir = path.join(app.getPath('userData'), 'plugins'); |
| } |
|
|
| |
| 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...`); |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
| ipcMain.handle('run-parameterized-system-check', async (event, params) => { |
| try { |
| console.log(' [IPC] Running parameterized system check...', params); |
|
|
| const { scope, plugins } = params; |
|
|
| |
| 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); |
|
|
| |
| if (analysisResult.typeAnalysis) { |
| recommendations.push(...analysisResult.typeAnalysis.recommendations); |
| } |
| break; |
|
|
| case 'core': |
| |
| analysisResult = { |
| totalIssues: 0, |
| message: 'ตรวจสอบระบบหลักเสร็จสิ้น - ไม่พบปัญหา' |
| }; |
| break; |
|
|
| case '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 }; |
| } |
| }); |
|
|
| |
| function getScopeText(scope) { |
| const texts = { |
| 'all': 'ทั้งระบบ', |
| 'plugins': 'ปลั๊กอิน', |
| 'core': 'ระบบหลัก', |
| 'dependencies': 'Dependencies', |
| 'specific': 'ปลั๊กอินที่เลือก' |
| }; |
| return texts[scope] || 'ส่วนที่ระบุ'; |
| } |
|
|
| async function analyzeDependencies(pluginsDir) { |
| |
| 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()) { |
| |
| 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} รายการเสร็จสิ้น` |
| }; |
| } |
|
|
| |
|
|
| |
| ipcMain.handle('open-plugins-folder', () => { |
| |
| 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 }; |
| } |
| } |
|
|
| |
| shell.openPath(pluginsDir); |
| console.log(` Opened plugins folder: ${pluginsDir}`); |
|
|
| return { success: true, path: pluginsDir }; |
| }); |
|
|
| |
| ipcMain.handle('get-available-plugins', async () => { |
| try { |
| |
| 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 |
| }; |
| } |
| }); |
|
|
| |
|
|
| |
|
|
| |
| ipcMain.handle('run-npm-project', async (event, payload) => { |
| console.log(' [IPC] NPM Project command received:', payload); |
|
|
| try { |
| |
| 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}`); |
|
|
| |
| 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' |
| }; |
| } |
|
|
| |
| switch (payload.action) { |
| case 'scan-projects': |
| return await handleScanProjects(); |
|
|
| case 'scan-project': |
| return await handleScanProject(payload.project, payload.path); |
|
|
| default: |
| |
| 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() |
| }; |
| } |
| }); |
|
|
| |
|
|
| |
| async function handleScanProjects() { |
| console.log(' [Scan] Starting project scan...'); |
|
|
| try { |
| |
| const SystemDetector = require('./modules/system-detector'); |
| const systemDetector = new 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() |
| }; |
| } |
| } |
|
|
| |
| async function handleScanProject(projectName, projectPath) { |
| console.log(` [Scan] Scanning single project: ${projectName} at ${projectPath}`); |
|
|
| try { |
| |
| const SystemDetector = require('./modules/system-detector'); |
| const systemDetector = new SystemDetector(); |
|
|
| |
| 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() |
| }; |
| } |
| } |
|
|
| |
| ipcMain.handle('execute-quick-command', async (event, command) => { |
| console.log(' [IPC] Quick command received:', command); |
|
|
| try { |
| |
| 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 |
| }; |
| } |
|
|
| |
| 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}`); |
|
|
| |
| if (workingDir.includes('../') || workingDir.includes('..\\')) { |
| throw new Error('Path traversal detected in working directory'); |
| } |
| } |
| } |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
| 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 { |
| |
| const projectPath = await validationGateway.getPluginPath(pluginName); |
|
|
| |
| const request = { |
| action: command, |
| pluginName: pluginName, |
| projectPath: projectPath, |
| data: data || {} |
| }; |
|
|
| console.log(`Forwarding to Gateway processCommand:`, request); |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
| ipcMain.handle('execute-command', async (event, payload) => { |
| console.log(' [IPC] Received command, forwarding to Validation Gateway:', payload); |
| try { |
| |
| 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() |
| }; |
| } |
| }); |
|
|
| |
| ipcMain.handle('get-run-mode', () => { |
| console.log(` [IPC] Checking run mode - isDevMode: ${isDevMode}`); |
| return { isDevMode: isDevMode }; |
| }); |
|
|
| |
| ipcMain.handle('start-build', async (event) => { |
| console.log(' [IPC] Starting build process...'); |
|
|
| |
| const { exec } = require('child_process'); |
|
|
| |
| const command = 'npx electron-builder --win --x64'; |
|
|
| |
| const projectRoot = getAppBasePath(); |
|
|
| console.log(` Starting build with command: ${command}`); |
| console.log(` Project root: ${projectRoot}`); |
|
|
| try { |
| |
| const buildProcess = exec(command, { cwd: projectRoot }); |
|
|
| |
| buildProcess.stdout.on('data', (data) => { |
| console.log(` [STDOUT] ${data}`); |
| |
| if (mainWindow && !mainWindow.isDestroyed()) { |
| mainWindow.webContents.send('build-log', data.toString()); |
| } |
| }); |
|
|
| |
| buildProcess.stderr.on('data', (data) => { |
| console.log(` [STDERR] ${data}`); |
| if (mainWindow && !mainWindow.isDestroyed()) { |
| |
| mainWindow.webContents.send('build-log', `[ERROR] ${data.toString()}`); |
| } |
| }); |
|
|
| |
| 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) { |
| |
| mainWindow.webContents.send('build-log', ' ไฟล์ Build สำเร็จแล้ว สามารถดูได้ในโฟลเดอร์ dist/'); |
| mainWindow.webContents.send('build-log', ' ไฟล์ที่สร้าง: *.exe, *.msi, *.zip'); |
| mainWindow.webContents.send('build-log', ' สามารถนำไปติดตั้งบนเครื่องอื่นได้แล้ว!'); |
| } |
| } |
| }); |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
| 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) { |
| |
| pluginsDir = path.join(path.dirname(app.getPath('exe')), 'plugins'); |
| } else { |
| |
| pluginsDir = path.join(app.getPath('userData'), 'plugins'); |
| } |
| return pluginsDir; |
| } catch (error) { |
| console.error(' [System] Get plugins path error:', error); |
| throw error; |
| } |
| }); |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
|
|
| |
| 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 } |
| }; |
| } |
| }); |
|
|
| |
| 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 }; |
| } |
| }); |
|
|
| |
| 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 }; |