Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Electron Security

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

Common security pitfalls


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

Migrating to an isolated context

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


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:

Prevent XSS attacks


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

function validateInput(data) {

  if (typeof data !== 'string' || data.length > 100) throw new Error('非法输入')

  return data

}

Principle of least privilege


Summary

The core of Electron security best practices is Isolation + Validation + Least Privilege:

Following these principles can greatly reduce the risk of desktop apps being attacked or leaking data.