Electron Security
Electron combines Node.js with the browser environment, which makes desktop apps very powerful but also brings certain security risks.
Proper security strategies can reduce the risks of XSS, remote code execution (RCE), and data leakage.
Security checklist and common pitfalls
Security checklist
- Enabling Context isolation (
contextIsolation) - Use Preload scripts (
preload.js) to expose secure APIs - Do not use Node.js modules directly in the renderer process
- Enabling Sandbox mode (
sandbox: true) - Configure Content Security Policy (CSP)
- Use IPC securely, verifying source and input
- Restrict the app's access to system permissions, following the principle of least privilege
- Avoid loading untrusted remote content
Common security pitfalls
- Remote content injection: loading unknown URLs or HTML files may execute malicious JS
- Insecure IPC calls: the renderer process can call arbitrary main-process methods
- Arbitrary Node.js execution: enabling in the renderer process
nodeIntegrationcan be exploited to execute system commands - XSS attacks: user input rendered directly to the page
- Dependency vulnerabilities: using outdated third-party libraries
Context Isolation
contextIsolation explained
Context isolation allows the renderer process and main process to run in different JS environments.
Web page JS in the renderer process cannot directly access Node.js APIs; instead, interfaces are exposed through secure preload scripts.
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: true, // 启用上下文隔离
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false // 禁止在渲染进程使用 Node.js
}
})
Why context isolation is needed
- Prevent loaded web pages or third-party scripts from directly accessing Node.js
- Prevent attackers from gaining system privileges through XSS
- Keep the renderer process handling only UI and the main process handling system operations
Migrating to an isolated context
- Use
contextBridge.exposeInMainWorldExpose secure APIs - Put all system operations in the main process and call them via IPC
Example:
// preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
getData: () => ipcRenderer.invoke('get-data')
})
The renderer process only calls window.api.getData(), and cannot directly operate the system.
Sandbox mode
Enable the sandbox
Sandbox mode makes the renderer process run like an ordinary browser web page, fully isolating the Node.js environment.
const mainWindow = new BrowserWindow({
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
Sandbox limitations and responses
- Limitation: the renderer process cannot directly access Node.js modules
- Response: call secure methods provided by the main process via IPC
- Advantage: enhance security and prevent malicious scripts from damaging the system
Content Security Policy (CSP)
CSP can prevent XSS and data injection attacks by restricting the sources from which a web page can load resources.
CSP configuration example
Explanation:
default-src 'self': only allow same-origin resources by defaultscript-src 'self': only allow local scriptsstyle-src 'self' 'unsafe-inline': allow inline stylesconnect-src: restrict AJAX / WebSocket request domains
Prevent XSS attacks
- Never use directly in the renderer process
innerHTMLto display user input - Escape user input or render it with framework templates
Secure IPC communication
Verify message source
The main process should distinguish the renderer process source to avoid arbitrary execution.
Example:
ipcMain.handle('do-action', (event, data) => {
if (event.senderFrame.url.startsWith('file://')) {
// Safe source, execute operation
} else {
console.warn('不安全的 IPC 请求被阻止')
}
})
Input validation
- All data passed via IPC should have its type and range validated
- Avoid injection of malicious commands or file paths
function validateInput(data) {
if (typeof data !== 'string' || data.length > 100) throw new Error('非法输入')
return data
}
Principle of least privilege
- Expose only necessary functions to the renderer process
- Do not expose all Node.js APIs or system permissions
- Use preload scripts to control the scope of interface access
Summary
The core of Electron security best practices is Isolation + Validation + Least Privilege:
- Isolation: enable context isolation and sandbox mode
- Validation: CSP, XSS prevention, IPC input validation
- Least privilege: minimize renderer process permissions and provide only necessary APIs
Following these principles can greatly reduce the risk of desktop apps being attacked or leaking data.