Learn Electron · 7/12

Ironclad Security Best Practices

9 min read

Building an Electron application means you are creating a powerful desktop software using the web technologies you already know and love. However, with great power comes a terrifyingly large attack surface.

In a standard web browser, your code lives inside a heavily restricted sandbox. If someone exploits a vulnerability on a website, they can mostly just mess with the site itself. In Electron, your application has the potential to read the file system, execute system commands, and install software. If you do not secure your application, a simple Cross-Site Scripting (XSS) attack could allow a hacker to seamlessly delete a user's hard drive or silently install a crypto-miner because someone clicked a picture of a cute cat.

Let's make sure that never happens. We will systematically lock down your Electron application using industry-standard security practices.


1. Why nodeIntegration: false is Absolute Law 🛑

The Problem

If a malicious user manages to inject a malicious script into your frontend application (for example, through an unsanitized chat message), that script runs in the browser environment. In a normal browser, this is bad, but contained. However, if your frontend has direct access to Node.js, that injected script can instantly require the child_process module and execute operating system-level commands.

Imagine you are managing an airport security checkpoint. You have passengers (frontend code) walking through. If you give every passenger unrestricted access to the runway and the control tower (Node.js APIs) just because it makes boarding faster, a single bad actor could cause a catastrophe. You need passengers to stay in the terminal and only let authorized personnel handle the planes.

The Definition

nodeIntegration is a configuration property in Electron's webPreferences object. It determines whether the renderer process (the frontend web page) has native access to Node.js environments and modules like fs (file system), path, and child_process.

The Solution

Always set nodeIntegration to false. When this is disabled, the frontend web page cannot use require() or access Node.js globals directly. Any attempt to call require('fs') from your React, Vue, or Vanilla JS frontend will throw an error.

While nodeIntegration: false has been the default behavior in Electron since version 5, it is a strict industry standard to explicitly declare it in your configuration. This prevents accidental overrides by junior developers and provides immediate clarity during security audits.

javascript
// main.js
const { app, BrowserWindow } = require('electron');
const path = require('path');

app.whenReady().then(() => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // THE ABSOLUTE LAW: No direct Node access in the frontend
      nodeIntegration: false, 
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');
});

Interesting Fact: In the early days of Electron (pre-v5), nodeIntegration was true by default. Developers loved how easy it was to read a local file directly from a button click in HTML. Then, the security community realized that any XSS vulnerability immediately equated to Remote Code Execution (RCE), which led to widespread panics and a rapid shift in defaults.


2. Enforcing Context Isolation Properly 🧱

The Problem

You have disabled nodeIntegration. Great! But you still need your frontend to communicate with your operating system, so you use a preload.js script to bridge the gap.

If both the preload script (which has some Node access) and the frontend code share the exact same global window object, a clever attacker can use a technique called "Prototype Pollution." They can override or mutate fundamental JavaScript methods (like Promise or Array.prototype.push) that your preload script relies on. When your privileged preload script runs, it inadvertently executes the attacker's manipulated code.

The Definition

Context Isolation is an Electron feature that ensures that your preload scripts and Electron's internal logic run in a dedicated, entirely separate V8 JavaScript execution context from the website loaded in the webContents.

The Solution

Enable contextIsolation: true. When enabled, the window object in your frontend and the window object in your preload script are technically two completely isolated universes.

To safely send data between these two universes, Electron provides the contextBridge API.

Think of a high-security prison (the system) and a visitor (the frontend). Context isolation is the thick, bulletproof glass between them. The contextBridge is the tiny, heavily monitored telephone line they use to speak. The visitor cannot physically touch the prisoner or pass them a knife; they can only send predetermined, safe voice messages.

javascript
// main.js - Creating the window
const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false,
    contextIsolation: true, // MUST BE TRUE
    preload: path.join(__dirname, 'preload.js')
  }
});
javascript
// preload.js - The bridge between Main and Renderer
const { contextBridge, ipcRenderer } = require('electron');

// We expose ONLY what is strictly necessary.
// We do NOT expose the entire ipcRenderer object.
contextBridge.exposeInMainWorld('secureAPI', {
  // Safe way to send a message
  saveFile: (data) => ipcRenderer.send('save-file-channel', data),
  
  // Safe way to receive a message
  onFileSaved: (callback) => {
    // We strip the `event` object because it contains sender information
    // that the frontend does not need and could potentially abuse.
    ipcRenderer.on('file-saved-success', (_event, value) => callback(value));
  }
});
javascript
// frontend.js (Your React/Vue/Vanilla UI)
// You interact with the bridge, not Electron itself.
window.secureAPI.saveFile({ content: "Hello secure world!" });

window.secureAPI.onFileSaved((message) => {
  console.log(message);
});

If a hacker tries to modify window.secureAPI.saveFile, they only modify the frontend's copy. The actual underlying Node logic remains completely untouched in its isolated V8 context.


3. Implementing Content Security Policies (CSP) 📜

The Problem

Even if you have perfectly isolated your contexts and completely disabled Node integration, your application is still vulnerable to traditional web attacks. If an attacker manages to inject <script src="https://evil-hacker-domain.com/steal-data.js"></script> into your app's DOM, the application will blindly download and execute it. Your app might also execute inline scripts (<script>alert('hacked')</script>) unexpectedly.

The Definition

A Content Security Policy (CSP) is an HTTP header (or an HTML <meta> tag) that allows site administrators to declare approved sources of content that the browser is permitted to load and execute.

The Solution

You must establish a strict CSP. This acts as an "allowlist" for your application. If a script, image, or stylesheet attempts to load from a source not explicitly defined in the CSP, the browser engine instantly blocks it.

In industry practice, the most robust way to enforce a CSP in Electron is by intercepting network requests at the session level using onHeadersReceived. This ensures the policy applies globally, even if a developer forgets to add a <meta> tag in an HTML file.

javascript
// main.js
const { app, session } = require('electron');

app.whenReady().then(() => {
  // Define strict rules
  const csp = [
    "default-src 'self'", // Only allow resources from the app's own origin
    "script-src 'self'",  // Do NOT use 'unsafe-inline' or 'unsafe-eval'
    "style-src 'self' 'unsafe-inline'", // 'unsafe-inline' often needed for UI frameworks
    "img-src 'self' data:", // Allow local images and base64 encoded images
    "connect-src 'self' https://api.mytrustedbackend.com" // Only allow API calls here
  ].join('; ');

  // Apply the CSP to all requests
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [csp]
      }
    });
  });

  // ... create your BrowserWindow here
});

If an attacker tries to inject an external script, Electron's console will politely (or rather, via a giant red error) inform them that the request was blocked by the Content Security Policy. This is one of the most effective ways to completely neutralize XSS attacks.


4. Safely Handling External Links and Web Navigation ⚓

The Problem

Applications frequently contain links to external resources (like a "Forgot Password" link or a user's social media profile). If a user clicks an <a href="https://malicious-site.com"> tag, Electron's default behavior might navigate the entire app window to that URL.

Suddenly, your user is looking at a perfect visual clone of your application hosted on a hacker's server, capturing their keystrokes. Furthermore, if the attacker triggers a programmatic navigation (window.location = ...), they can hijack your app's current window.

The Definition

Web navigation handling is the implementation of event listeners on the webContents object to monitor, intercept, and manage any attempts the application makes to load new URLs or open new windows.

The Solution

You need to explicitly deny your application window the ability to navigate anywhere except your local files (or trusted dev servers). Any valid external links should be caught and passed to the user's default web browser (like Chrome, Firefox, or Edge) so they open safely outside of your Electron application environment.

Imagine managing a corporate office building. An employee requests to go to a sketchy warehouse across town. Instead of driving the entire corporate headquarters building to the warehouse (navigating the Electron window), you call a taxi (the default OS browser) to take them there separately, keeping your headquarters perfectly safe.

javascript
// main.js
const { app, BrowserWindow, shell } = require('electron');

app.whenReady().then(() => {
  const mainWindow = new BrowserWindow({ /* ... preferences ... */ });

  // 1. Prevent the main window from navigating away from your app
  mainWindow.webContents.on('will-navigate', (event, navigationUrl) => {
    const parsedUrl = new URL(navigationUrl);
    
    // If the URL is not our local app file, stop the navigation dead in its tracks.
    if (parsedUrl.protocol !== 'file:') {
      console.warn(`Blocked navigation attempt to: ${navigationUrl}`);
      event.preventDefault(); 
    }
  });

  // 2. Safely handle external links meant to open in a new window/tab
  // (e.g., target="_blank" links)
  mainWindow.webContents.setWindowOpenHandler((details) => {
    const parsedUrl = new URL(details.url);

    // If it is a safe, valid HTTPS link, open it in the user's native web browser
    if (parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:') {
      // Hands the URL to the operating system
      shell.openExternal(details.url); 
    }

    // Always deny Electron from creating a new BrowserWindow internally
    return { action: 'deny' };
  });

  mainWindow.loadFile('index.html');
});

Funny exaggeration: If you do not handle navigation, an attacker navigating your app window to a 10-hour loop of the Nyan Cat video on YouTube is technically the best-case scenario. The worst-case is them loading a phishing page that prompts the user for their system administrator password.


Summary

Securing an Electron application is all about reducing trust. Trust nothing your frontend does, restrict its access to the bare minimum, and strictly enforce rules on what it is allowed to load and where it is allowed to go.

  1. nodeIntegration: false - Keep Node.js APIs out of the frontend.
  2. contextIsolation: true - Keep the V8 environments separate to prevent prototype pollution.
  3. CSP - Actively block unauthorized scripts and resources from loading.
  4. Navigation Handling - Lock the application to your intended views and delegate external links to the OS browser.

Further Reading & References 📚

Challenge

You are tasked with hardening a new Electron application's main process to mitigate common security vulnerabilities. Your goal is to configure the main BrowserWindow and implement application-wide security handlers based on the following requirements:

  1. Window Configuration: In the createWindow function, configure the BrowserWindow's webPreferences to strictly disable Node.js integration in the renderer process and ensure the preload script and renderer process run in separate JavaScript contexts.

  2. Content Security Policy (CSP): After the application is ready, implement a global Content Security Policy for all network requests. The policy must enforce the following rules:

    • Default sources should be restricted to 'self'.
    • Scripts, styles, and fonts must only be loaded from the application's own origin ('self').
    • Images can be loaded from the application's origin ('self') and any subdomain of secure-cdn.com.
    • Connections (like WebSockets or fetch) are only allowed to the application's origin.
  3. Navigation Control: Implement a handler for the main window that intercepts all new window creation requests. The handler should prevent the application from opening any external URLs within a new Electron window. Instead, any requested URL should be opened securely in the user's default system browser.

Expected result

Your final code should correctly implement all three security measures.

  1. The webPreferences object inside the BrowserWindow constructor must contain the properties nodeIntegration: false and contextIsolation: true.

  2. Within the app.whenReady().then() callback, you must correctly use session.defaultSession.webRequest.onHeadersReceived. The callback for this listener should modify the responseHeaders to include a Content-Security-Policy header. The value of this policy must be a string that correctly implements the specified rules, for example: "default-src 'self'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' https://*.secure-cdn.com; connect-src 'self'".

  3. A handler must be set on mainWindow.webContents using the setWindowOpenHandler method. The handler's implementation should call shell.openExternal with the requested URL and must return { action: 'deny' } to prevent Electron from opening the URL internally.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.