File size: 10,931 Bytes
857cdcf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | /**
* 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');
}); |