/** * Chahuadev Framework - Preload Script (IPC Bridge) * ================================================= * * SECURE BRIDGE POLICY: * ------------------------ * This preload script acts as a secure bridge between renderer (UI) and main process. * ALL communication must be validated and routed through ValidationGateway. * * REQUEST ROUTING ARCHITECTURE: * ------------------------------- * Renderer (Widget/UI) window.electronAPI.* ipcRenderer.invoke() main.js handlers ValidationGateway * * EXPOSED APIs: * --------------- * window.electronAPI: * - executeCommand() 'execute-command' IPC validationGateway.processCommand() * - loadWorkflow() 'load-workflow' IPC validationGateway.processCommand() * - saveWorkflow() 'save-workflow' IPC validationGateway.processCommand() * * SECURITY MANDATE: * ------------------- * Every single IPC call must route through ValidationGateway in main.js * NO direct access to backend modules is permitted * * FORBIDDEN: Direct require() of plugins or backend modules * REQUIRED: All operations through secure IPC ValidationGateway flow */ const { contextBridge, ipcRenderer } = require('electron'); // Expose protected methods that allow the renderer process to use // the ipcRenderer without exposing the entire object contextBridge.exposeInMainWorld('electronAPI', { getAppVersion: async () => { try { const version = await ipcRenderer.invoke('get-app-version'); console.log(' App version retrieved:', version); return version; } catch (error) { console.warn(' Failed to get app version:', error); return '1.0.0'; // fallback version } }, showMessageBox: (options) => ipcRenderer.invoke('show-message-box', options), // Platform detection platform: process.platform, // Framework API helpers (Updated to production URL) frameworkAPI: { baseUrl: 'https://chahuadev.com/api' }, // IPC Command Execution - ไม่ต้อง HTTP อีกต่อไป! executeCommand: (payload) => ipcRenderer.invoke('execute-command', payload), // Quick Command Execution (NEW!) executeQuickCommand: (command) => ipcRenderer.invoke('execute-quick-command', command), // Plugin Command Execution (NEW!) executePluginCommand: (pluginName, command, data) => ipcRenderer.invoke('execute-plugin-command', pluginName, command, data), // เพิ่มบรรทัดนี้เข้าไป processCommand: (request) => ipcRenderer.invoke('process-command', request), // NPM Project Management Commands (for HTML plugins) runNpmProject: (payload) => ipcRenderer.invoke('run-npm-project', payload), // Manifest Generator (for plugin scanning) runManifestGenerator: () => ipcRenderer.invoke('run-manifest-generator'), // System Check for In-App Diagnostics runSystemCheck: () => ipcRenderer.invoke('run-system-check'), runParameterizedSystemCheck: (params) => ipcRenderer.invoke('run-parameterized-system-check', params), getAvailablePlugins: () => ipcRenderer.invoke('get-available-plugins'), // Open Plugins Folder (NEW - เปิดโฟลเดอร์ plugins ใน userData) openPluginsFolder: () => ipcRenderer.invoke('open-plugins-folder'), // Build Process API (NEW - สำหรับ Build App เป็น MSI/EXE) startBuild: () => ipcRenderer.invoke('start-build'), // รับ Log จาก Build Process แบบ Real-time onBuildLog: (callback) => ipcRenderer.on('build-log', (_event, value) => callback(value)), removeBuildLogListeners: () => ipcRenderer.removeAllListeners('build-log'), // ตรวจสอบโหมดการทำงาน (Development vs Production) getRunMode: () => ipcRenderer.invoke('get-run-mode'), // ตรวจสอบสถานะ Developer Mode แบบปรับปรุงใหม่ getDevModeStatus: () => ipcRenderer.invoke('security:get-dev-mode'), // [เพิ่มใหม่] ฟังก์ชันสำหรับเรียก Path จาก main.js getPreloadPath: () => ipcRenderer.invoke('get-preload-path'), // SECURE NPM COMMAND EXECUTION (NEW!) - สำหรับการติดตั้ง Framework ใน Electron executeNpmCommand: (command) => ipcRenderer.invoke('execute-npm-command', command), // ตรวจสอบสถานะ Electron Environment isElectronApp: true, // เปิด URL ภายนอกอย่างปลอดภัยผ่าน main process openExternal: (url) => ipcRenderer.invoke('open-external', url), // Splash Screen Control splashScreenFinished: () => ipcRenderer.invoke('splash:finished'), // Real Terminal/CMD Execution (NEW!) terminal: { execute: (command, options = {}) => ipcRenderer.invoke('terminal:execute', command, options), executeStream: (command, callback) => { const channel = `terminal-output-${Date.now()}`; ipcRenderer.on(channel, (_event, data) => callback(data)); return ipcRenderer.invoke('terminal:execute-stream', command, channel); }, // Secure Command Execution with Firewall Protection executeCommand: (command) => ipcRenderer.invoke('terminal:execute-command', command), getSystemInfo: () => ipcRenderer.invoke('terminal:get-system-info'), kill: (processId) => ipcRenderer.invoke('terminal:kill', processId), getHistory: () => ipcRenderer.invoke('terminal:get-history'), clearHistory: () => ipcRenderer.invoke('terminal:clear-history'), // Event listeners for terminal events onMessage: (callback) => ipcRenderer.on('terminal:message', callback), onCommandResult: (callback) => ipcRenderer.on('terminal:command-result', callback), onCommandExecuted: (callback) => ipcRenderer.on('terminal:command-executed', callback), onClear: (callback) => ipcRenderer.on('terminal:clear', callback), onWelcome: (callback) => ipcRenderer.on('terminal:welcome', callback), onNewLog: (callback) => ipcRenderer.on('terminal:new-log', callback), // Remove listeners removeAllListeners: () => { ipcRenderer.removeAllListeners('terminal:message'); ipcRenderer.removeAllListeners('terminal:command-result'); ipcRenderer.removeAllListeners('terminal:command-executed'); ipcRenderer.removeAllListeners('terminal:clear'); ipcRenderer.removeAllListeners('terminal:welcome'); ipcRenderer.removeAllListeners('terminal:new-log'); } }, // UI State Management (NEW!) ui: { saveState: (key, value) => ipcRenderer.invoke('ui:save-state', key, value), loadState: (key, defaultValue) => ipcRenderer.invoke('ui:load-state', key, defaultValue), clearState: (key) => ipcRenderer.invoke('ui:clear-state', key) }, // Get Webview Preload Path - สำหรับ webview initialization getPreloadWebviewPath: () => ipcRenderer.invoke('get-preload-webview-path'), // Project API - สำหรับ debugger.js project: { analyze: (projectPath) => ipcRenderer.invoke('project:analyze', projectPath), getStats: (analysis) => ipcRenderer.invoke('project:get-stats', analysis), setRules: (rules) => ipcRenderer.invoke('project:set-rules', rules), // เพิ่ม: สร้างช่องทางสำหรับรับ status update onStatusUpdate: (callback) => ipcRenderer.on('inspector:status-update', (_event, value) => callback(value)) }, // Plugin Management Functions plugins: { // Get all available plugins getAll: () => ipcRenderer.invoke('get-available-plugins'), // Get specific plugin information getInfo: (pluginName) => ipcRenderer.invoke('get-plugin-info', pluginName), // Execute plugin with data (Enhanced for multiple types) execute: (pluginName, data) => ipcRenderer.invoke('execute-command', { plugin: pluginName, data: data }), // Open HTML Plugin in new window openHTML: (pluginName) => ipcRenderer.invoke('execute-command', { plugin: pluginName, data: { action: 'open_html' } }), // View Project Information viewProject: (pluginName) => ipcRenderer.invoke('execute-command', { plugin: pluginName, data: { action: 'view_project' } }) }, // System Info getSystemInfo: () => ipcRenderer.invoke('get-system-info'), // ========== OFFLINE DEMO AUTHENTICATION ========== /** * Authentication API สำหรับโหมดออฟไลน์ (Offline Demo Mode) */ auth: { // เริ่มต้น Offline Auth Dashboard startDeviceFlow: () => ipcRenderer.invoke('auth:start-device-flow'), // ล็อคอินแบบออฟไลน์ (ใช้ username/password) offlineLogin: (username, password) => ipcRenderer.invoke('auth:offline-login', { username, password }), // Polling สำหรับรอ user approve (legacy) pollDeviceAuth: (deviceCode) => ipcRenderer.invoke('auth:poll-device', deviceCode), // ดึงข้อมูล User ปัจจุบัน getCurrentUser: () => ipcRenderer.invoke('auth:get-current-user'), // ตรวจสอบสถานะ Authentication checkStatus: () => ipcRenderer.invoke('auth:check-status'), // Logout logout: () => ipcRenderer.invoke('auth:logout') }, // Message listener for IPC communication onMessage: (channel, callback) => { ipcRenderer.on(channel, (event, ...args) => callback(...args)); }, // Desktop app indicators isDesktopApp: true, isElectron: true }); // --- WebView Communication Bridge --- window.addEventListener('message', (event) => { // SECURITY: ตรวจสอบว่าข้อความมาจากเว็บของเราจริงๆ เท่านั้น! if (event.origin !== 'https://chahuadev.com') { console.warn(`[Preload] Blocked message from untrusted origin: ${event.origin}`); return; } const message = event.data; console.log('[Preload] Message received from WebView:', message); // เพิ่มการจัดการ action อื่นๆ ได้ที่นี่ }); // Console log to confirm preload loaded console.log(' Chahuadev Framework preload script loaded with Plugin Management System'); // Add desktop app styling window.addEventListener('DOMContentLoaded', () => { document.body.classList.add('electron-app'); });