Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Security Model

Validating IPC Messages and Handling Secrets

Treat every IPC message as untrusted input: verify the sender frame, validate arguments with schemas, confine file paths to a folder and keep secrets out of the renderer.

An IPC handler in the main process is an API endpoint, and the renderer is its client. In a web backend nobody trusts the browser: every parameter is validated, every action authorised. The same discipline applies here, and for the same reason. If an attacker gets script running in a renderer, the only thing standing between that script and the user's disk is how carefully your handlers behave.

Three questions to ask of each handler: who is calling (sender validation), what exactly did they send (argument validation) and what could the work touch (confinement). This lesson answers each with code you can run.

Who is calling?

Every handler receives an event that identifies the frame that sent the message. A window can contain iframes with other origins, and a navigated window may now show a different page than you started with. Check the sender frame's URL before doing anything sensitive.

JavaScript
import { ipcMain } from 'electron';

function isTrustedSender(frame) {
  if (!frame) return false;
  const url = new URL(frame.url);
  return url.protocol === 'file:' && url.pathname.endsWith('/app/dist/index.html');
}

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

Use event.senderFrame and check its url (and, for the strictest setups, compare frame.processId and frame.routingId with your own window's main frame). Do not use event.sender.getURL() alone: it reports the top frame, not necessarily the frame that sent the message.

What did they send?

Arguments over IPC are structured-cloned JSON-like data: anything the page wants. A handler that expects { title: string, tags: string[] } must not assume it got that.

A schema library such as Zod makes the check declarative:

JavaScript
import { z } from 'zod';

const SaveNote = z.object({
  id: z.string().regex(/^[a-z0-9-]{1,40}$/),
  title: z.string().min(1).max(120),
  body: z.string().max(200_000),
  tags: z.array(z.string().max(30)).max(10),
}).strict();

ipcMain.handle('notes:save', async (event, raw) => {
  const note = SaveNote.parse(raw);     // throws on any mismatch
  await store.save(note);
});

Without a library the same idea is a function. The next example validates the payload by hand, rejects unknown keys (they often hint at prototype pollution attempts), and shows the failure modes.

Node.js Validating an IPC payload

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.

Note two details. The accepted value is rebuilt from known fields, so nothing unexpected travels deeper into the app. And error messages describe the rule, not the internals.

What could the work touch?

Even a perfectly typed id can be dangerous if it ends up in a file path. Confine file access to a base folder and verify that the resolved path stays inside it.

Node.js Confining paths to a folder

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.

Two layers here: a strict pattern on the id, and a containment check on the resolved path. Keep both. The + sep suffix matters: without it a sibling folder called notes-data-backup would pass a plain startsWith.

Keep secrets out of the renderer

A rule of thumb: if the renderer does not need the value, it must never receive it. API keys, refresh tokens and database passwords stay in the main process. The renderer asks for the result of an operation.

JavaScript
// Bad: renderer gets the token and calls the API itself
ipcMain.handle('auth:token', () => store.token);

// Better: main process makes the call, the renderer gets data
ipcMain.handle('profile:load', async (event) => {
  assertTrusted(event);
  const res = await fetch('https://api.example.com/me', {
    headers: { Authorization: `Bearer ${store.token}` },
  });
  const { name, avatarUrl } = await res.json();
  return { name, avatarUrl };            // only what the UI needs
});

Also make sure secrets never reach logs, crash reports or error messages sent over IPC. Return stable error codes ('not_found', 'forbidden') rather than raw exceptions that may contain paths or tokens. How to store the token on disk is the subject of Safe Storage and Fuses.

A reusable guard

You will write the same three steps in every handler, so wrap them once. handle below checks the sender, validates the payload and converts exceptions into plain error objects.

Node.js A guarded handler wrapper

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 renderer sees { ok: false, error: 'failed' } for the last call, while the sensitive message stays in the main-process log.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object tells an IPC handler which frame sent the message?

    senderFrame carries the URL of the frame that actually sent the message. Check it before sensitive work, because a window can host other origins in iframes.
  2. 2. Why rebuild the accepted value from known fields after validation?

    Copying only the fields you checked prevents extra properties, such as admin flags, from reaching later code.
  3. 3. Why add path.sep when testing that a path starts with the base folder?

    'notes-data-backup/x' starts with 'notes-data' as text. Appending the separator makes the prefix test match only real children.
  4. 4. What should a handler return when an internal exception mentions a password?

    Errors cross the process boundary into untrusted code. Keep details in the main-process log and return a short code.

Summary

  • Treat IPC handlers as an API: verify the sender frame, validate every argument, confine every path.
  • Prefer schemas (Zod or hand-written) with unknown keys rejected and the accepted value rebuilt.
  • Resolve paths and check containment with path.sep; do not trust ids.
  • Keep secrets in the main process; return only the data the UI needs, with stable error codes.
  • Wrap the common checks in one guard so no handler forgets them.

Next: Safe Storage and Fuses