Authenticating Node-RED web sockets

While developing extension nodes for Node-RED is sometimes useful to re-use the built-in Web Sockets channel (/comms) to provide two ways communication between the extension and Node-RED.

Everything works fine until the moment we put everything in production and we secure the Node-RED server, the web socket connection remains pending. That's because the Web Socket connection is initiated through the http:// protocol (which requires authentication) and then upgraded to ws://.

I've found the solution after digging a little in the Node-RED code (since the lack of documentation on this topic)

import Sockette from 'sockette';
const ws = new Sockette(
  'http://localhost:1880/comms', // the Node-RED server  
  {
    // ...
    onopen: () => {
      const raw = localStorage.getItem('auth-tokens');
      let json;
      try {
        json = JSON.parse(raw)
      } catch(e) {
        // do nothing
      }
      if (json != null && !_.isEmpty(json.access_token)) {
        ws.send(`{"auth":"${json.access_token}"}`);
      }
    }
  }
);

Basically the trick is to use the same Node-RED authentication token to authenticate the web socket connection.