Can I prevent node_modules bundled with webpack from using window.postMessage?

Viewed 202

For security reasons, I need to disallow 3rd party modules which are included in my bundle by webpack from using window.postMessage to communicate with other processes in my Electron app.

Is that possible?

1 Answers

A standard trick could help here: simply move the method to another variable on window, like this maybe:

window._postMessage = window.postMessage;
window.postMessage = () => {};

Run this first on your render script or with a <script> tag on your html and plugins that would use that can't send events anymore (in fact, they don't crash but never get a response).

Edit

If you want to make sure that only authorized user can use it, something like this could work:

function createSecurePostMessage() {
  const _postMessage = window.postMessage;

  return {
    get() {return function(...args) {
      if (isAuthorized(...args) {
         _postMessage(...args);
      }
    }
  }
}
window.postMessage = createSecurePostMessage().get();

Now the original postMessage is inside the function and inaccessible and you can implement a method, for example, that checks if a certain message can be sent. If someone calls create again, then the secured postMethod will just be 'secured' again.

Related