Preload and IPC

Validate IPC input

Check the sender and every note field in the main process before writing renderer data to disk.

12 minute lesson

~~~

A TypeScript type or renderer form check cannot protect the main process at runtime. Renderer values are untrusted when they cross IPC.

Add a small validator:

function validateNotes(value) {
  if (!Array.isArray(value)) throw new Error('Notes must be an array')
  if (value.length > 1000) throw new Error('Too many notes')

  return value.map(note => {
    if (!note || typeof note !== 'object') throw new Error('Invalid note')
    if (typeof note.id !== 'string' || note.id.length > 100) {
      throw new Error('Invalid note id')
    }
    if (typeof note.title !== 'string' || note.title.length > 200) {
      throw new Error('Invalid note title')
    }
    if (typeof note.body !== 'string' || note.body.length > 100000) {
      throw new Error('Invalid note body')
    }

    return { id: note.id, title: note.title, body: note.body }
  })
}

The validator returns a new object with only allowed properties. That drops prototype tricks and unexpected fields instead of passing the renderer object into storage.

Validate the sender separately. For one known main window:

function assertTrustedSender(frame) {
  if (!mainWindow || frame !== mainWindow.webContents.mainFrame) {
    throw new Error('Untrusted IPC sender')
  }
}

Checking only a URL string is easy to get wrong. Comparing the actual main frame is a strong fit when this app has one trusted local window. If the app later adds several windows, define an explicit allowlist of trusted frames and capabilities.

Return plain data. Electron serializes IPC values with the structured clone algorithm, so DOM elements and Electron objects cannot cross the boundary.

Test the validator directly with valid notes, an object instead of an array, 1,001 notes, oversized strings, extra properties, and an object with a custom prototype. Then send a valid value from an iframe and confirm the sender check rejects it.

Validation limits shape and volume. It does not decide which user may save which notes. Add authorization too when data belongs to multiple users.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →