Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท IPC and Preload Scripts

IPC Validation, Security and Advanced Patterns

Secure Electron IPC by checking senders, validating arguments, allow-listing paths, rate limiting, and use MessageChannel ports for window-to-window and streaming messages. Runnable examples.

Every IPC handler is a door into your privileged main process. The page in front of it can be compromised in many ways: a cross-site scripting bug, a malicious dependency, an iframe from another site, a link that loaded something you did not expect. If your handlers trust their input, an attacker who controls the page controls the computer.

This lesson turns the principle "treat IPC input as untrusted" into practical code: verify who is calling, validate what they send, restrict what they can reach, and slow down abuse. At the end we look at MessageChannel ports, a more advanced tool for streaming and renderer-to-renderer communication.

Step 1: verify the sender

A handler should only serve your own pages. event.senderFrame.url (or event.senderFrame.origin) tells you which frame sent the message. Reject everything else:

JavaScript
const { ipcMain } = require('electron')

function isTrustedSender(event) {
  const frame = event.senderFrame
  if (!frame) return false
  if (frame !== event.sender.mainFrame) return false          // reject iframes
  const url = new URL(frame.url)
  return url.protocol === 'app:' || (url.protocol === 'file:' && url.pathname.endsWith('/index.html'))
}

ipcMain.handle('notes:save', async (event, note) => {
  if (!isTrustedSender(event)) throw new Error('Untrusted sender')
  // ...
})

Wrap the check in a helper that every handler calls, or write a secureHandle(channel, fn) function that does it for you (shown below).

Step 2: validate the arguments

IPC arguments can be anything a structured clone can carry: null, huge strings, arrays instead of objects, objects with extra keys. Define the shape you accept and reject the rest. You can use a validation library (zod, valibot, ajv) in the main process, or hand-written checks for small cases. Check:

  • Type (typeof x === 'string', Array.isArray).
  • Size (maximum string length, array length, number range).
  • Allowed values (an enum like 'light' | 'dark').
  • Unknown keys (ignore or reject them; never spread untrusted objects into options).

Step 3: restrict what the action can reach

If a handler reads a file, never take a free path from the page. Prefer an identifier: the page passes "notes/todo" and you map it to a folder you control. If you must accept paths (for example from a file dialog you opened), remember that the main process chose that path; do not accept a path that came from the page unvalidated. Resolve the path and verify it stays inside an allowed folder.

A secure handler wrapper

Here is the entire approach as a runnable stand-in: a secureHandle helper that wraps each handler with a sender check, schema validation and a safe error. Read the output to see which calls pass and why the others fail.

Node.js Stand-in: secureHandle with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the layers: even if the pattern check had a hole, the startsWith(NOTES_ROOT) check would still contain the damage. That is defence in depth.

Step 4: limit the damage of abuse

A compromised page can call a handler thousands of times a second. Add a simple per-window rate limit to expensive operations (disk writes, network calls, dialogs). A token bucket is a few lines:

Node.js Stand-in: token-bucket rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first five calls pass, the next three are denied, and after one second two tokens have come back.

One-way messages: send and on

ipcRenderer.send with ipcMain.on is fire-and-forget. The same security rules apply to ipcMain.on listeners: validate the sender and the arguments. Do not use event.returnValue with sendSync unless you have no other choice, because it blocks.

JavaScript
ipcMain.on('window:set-title', (event, title) => {
  if (!isTrustedSender(event) || typeof title !== 'string') return
  BrowserWindow.fromWebContents(event.sender)?.setTitle(title.slice(0, 120))
})

MessageChannel and MessagePort

Standard web MessageChannel objects work in Electron. Two ports are linked: a message posted on one arrives on the other. In Electron you can transfer a port from a renderer to the main process (or to another renderer through main) with ipcRenderer.postMessage, creating a direct pipe that bypasses further round trips through ipcMain. This is useful for:

  • Streaming a lot of data (frames, log lines, progress) without one IPC call per message.
  • Connecting two windows (or a window and a utility process) so they talk directly.
  • Keeping a long-lived, stateful conversation.
JavaScript
// renderer A creates a channel and sends one port to the main process
const { port1, port2 } = new MessageChannel()
ipcRenderer.postMessage('connect-to-worker', null, [port1])   // transfer port1
port2.onmessage = (e) => console.log('from worker', e.data)
port2.postMessage({ job: 'compress' })
JavaScript
// main: forwards the port to a utility process or another window
ipcMain.on('connect-to-worker', (event) => {
  const [port] = event.ports
  worker.postMessage({ type: 'port' }, [port])   // child is utilityProcess.fork(...)
})

Node.js has the same MessageChannel class, so you can see the mechanism:

Node.js MessageChannel: a direct pipe between two sides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Ports carry structured-cloneable data just like IPC, and you can transfer ArrayBuffers to avoid copying them.

A security checklist for IPC

  1. One narrow channel per capability; no generic "run" or "invoke any channel" API.
  2. Validate the sender frame on every handler.
  3. Validate type, size and allowed values of all arguments.
  4. Never build file paths, shell commands or URLs directly from page input.
  5. Return minimal, safe error messages; log details in the main process.
  6. Rate-limit expensive actions.
  7. Remove channels and handlers you no longer need.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why check event.senderFrame in handlers?

    Handlers should only serve trusted frames; a remote or embedded page must not be able to call privileged functions.
  2. 2. A handler receives a file name from the page. What is the safest design?

    Pattern checks plus a final containment check give defence in depth against path traversal.
  3. 3. What does a token-bucket limiter do for an IPC handler?

    A bucket holds a limited number of tokens that refill over time, so a burst is allowed but sustained flooding is denied.
  4. 4. When is a MessagePort a better choice than repeated invoke calls?

    A transferred port is a direct, long-lived pipe, which suits streams and renderer-to-renderer or utility-process communication.

Summary

  • Verify the sender frame, validate every argument, and restrict what the action can reach.
  • Wrap handlers in a helper (secureHandle) so the checks cannot be forgotten.
  • Return safe errors and rate-limit expensive operations.
  • Use MessageChannel ports for streaming and direct process-to-process links.
  • Keep a short checklist and review every channel against it.

Next: Window Management: Multiple, Child and Modal Windows