pokusew / nfc-pcsc

Easy reading and writing NFC tags and cards in Node.js
MIT License
535 stars 132 forks source link

Context Aware Native Module, Electron Context Isolation and Node Integration Support #148

Open danielduan opened 1 year ago

danielduan commented 1 year ago

@pokusew I saw that you're making some changes in both the pcsclite module and here so I hope this helps.

Since Electron 14, there's been enhanced security around how native modules in node can interact with Electron renderer and main processes. Basically, to reduce the risk of external content loaded remotely from directly interacting with native and operating system level programs, the renderer process cannot access native modules and hardware by default, including the pcsclite module.

There's also been a change introduced to node that requires native modules to be context aware. Looks like the change was introduced here https://github.com/pokusew/node-pcsclite/commit/3cbfdc391fa63e8acecf162aac0e7cbdc50c130b but not published yet.

The native module pcsclite needs to be used inside the main process, and communicate with the renderer via the new IPC channels. But because IPC cannot reasonably stringify all bytecodes and errors, it makes it hard for us to work with nfc-pcsc or pcsclite.

The workaround and hack is to disable these new security mechanisms.

In the main.ts file, when the BrowserWindow object is created, we must enable nodeIntegration and disable contextIsolation so that native modules like pcsclite can be used in the same JS context.

mainWindow = new BrowserWindow({
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

In addition, most new Electron boilerplates and example projects require two different package.json files, one for the native modules specifically, and the other for everything else because the native modules need to be compiled and rebuilt separately per platform (Windows, Mac, Linux).

In the case of Electron React Boilerplate that I'm using, I've only gotten it to work in this very specific way.

It also seems like the the original package your @pokesew/pcsclite was forked from has also been updated with some of your changes. I wonder if it makes sense to combine the two because it seems like the compiled native modules are more or less interchangeable. https://github.com/santigimeno/node-pcsclite