Electron + MySQL throws security warning

Viewed 214

I've installed Electron and MySql and got them working well together.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>Hello world</h1>
</body>


<script>
  var mysql = require('mysql');
  var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'blog'
  });

  connection.connect();

  connection.query('SELECT * FROM posts', function (error, results, fields) {
    if (error) throw error;
    console.log(results);
  });

  connection.end();
</script>

</html>

Then in the window I get a security error.

index.html:16 Uncaught ReferenceError: require is not defined

I noticed that I could override it like below.

win = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true
    }
  });

I've read it's dangerous and not recommended? I also get a warning when doing so.

Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security Policy set or a policy with "unsafe-eval" enabled. This exposes users of this app to unnecessary security risks.

How can I get around it?

2 Answers

What you're experiencing here is Electron's out-of-the-box sandboxing. This prevents your renderer process, where your user interface HTML and JavaScript are executed, from being able to access NodeJS APIs so no malicious code can actually do harm to the user's computer. As you said, you can disable this automatic sandboxing by setting nodeIntegration: true, which yields this security warning, but this is not considered a good practice by the Electron developers.

However, if you cannot use some of the workarounds (e.g. by using a preload script; refer to the Electron documentation, specifically this tutorial on context isolation), to get rid of the warning (which really does not do any harm because it won't be displayed when the app is packaged), you may set an environment variable in your main process like so (preferably on the very first line):

process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true;
// Other main process code...

Although this will remove the warning, I'd leave it where it is so that it can remind you of your security duties and to maybe revisit your code once the app has reached a production-ready state to make it comply with Electron's security guidelines.

Use a preload script instead, and put your MySQL connection code in there. Preload scripts have access to require / the node integration and also have access to the content window at the same time. You can make the preload script add to the global window object to expose functions to connect and perform sql queries.

Related