GitHub – jbreckmckye/electron-auth0-login: Helper widget for Auth0 authentication in Electron desktop apps

. Не испольхуйте enableBlinkFeatures​

Blink is the name of the rendering engine behind Chromium. As with experimentalFeatures, the enableBlinkFeatures property allows developers to enable features that have been disabled by default.

. Verify WebView options before creation​

A WebView created in a renderer process that does not have Node.js integration enabled will not be able to enable integration itself. However, a WebView will always create an independent renderer process with its own webPreferences.

It is a good idea to control the creation of new <webview> tags from the main process and to verify that their webPreferences do not disable security features.

. Disable or limit navigation​

If your app has no need to navigate or only needs to navigate to known pages, it is a good idea to limit navigation outright to that known scope, disallowing any other kinds of navigation.

. Do not use shell.openExternal with untrusted content​

The shell module’s openExternal API allows opening a given protocol URI with the desktop’s native utilities. On macOS, for instance, this function is similar to the open terminal command utility and will open the specific application based on the URI and filetype association.

Enable Context Isolation​

Context isolation is an Electron feature that allows developers to run code in preload scripts and in Electron APIs in a dedicated JavaScript context. In practice, that means that global objects like Array.prototype.push or JSON.parse cannot be modified by scripts running in the renderer process.

Electron uses the same technology as Chromium’s Content Scripts to enable this behavior.

Even when nodeIntegration: false is used, to truly enforce strong isolation and prevent the use of Node primitives contextIsolationmust also be used.

Похожее:  Ajax авторизация и регистрация на PHP

Enable process sandboxing​

Sandboxing is a Chromium feature that uses the operating system to significantly limit what renderer processes have access to. You should enable the sandbox in all renderers. Loading, reading or processing any untrusted content in an unsandboxed process, including the main process, is not advised.

Не выключайте webSecurity​

You may have already guessed that disabling the webSecurity property on a renderer process (BrowserWindow, BrowserView, or &lt;webview&gt;) disables crucial security features.

Do not disable webSecurity in production applications.

Define a Content Security Policy​

A Content Security Policy (CSP) is an additional layer of protection against cross-site-scripting attacks and data injection attacks. We recommend that they be enabled by any website you load inside Electron.

Bonus: add functionality to your web contents

At this point, you might be wondering how to add more functionality to your application.

For any interactions with your web contents, you want to add scripts to your
renderer process. Because the renderer runs in a normal web environment, you can add a
<script> tag right before your index.html file’s closing </body> tag to include
any arbitrary scripts you want:

Build an electron app

Now you’re ready to build an Electron application. First, open a new folder using your favorite IDE. In the console, type npm init and complete the setup presented to you. Accepting all the defaults is fine. Once you are done with the setup, install the following dependencies:

Next, add a start script to your package.json file.

Create a new file called main.js and add the following code to it. Make sure to replace {yourOktaDomain} and {yourClientId} with the settings from the OIDC app you created earlier.

const{app,BrowserWindow}=require("electron");constpath=require("path");constOktaAuth=require("@okta/okta-auth-js").OktaAuth;const{ipcMain}=require("electron");letmainWindow;letuser;varconfig={// Required configissuer:"https://{yourOktaDomain}/oauth2/default",clientId:"{yourClientId}",};varauthClient=newOktaAuth(config);ipcMain.on("user:login",(event,data)=>{authClient.signInWithCredentials(data).then(function(res){console.log(res);if(res.data.status!="SUCCESS"){event.reply("login-failed",err.errorSummary);return;}user=res.user;openHome();}).catch(function(err){console.log(err);event.reply("login-failed",err.errorSummary);});});ipcMain.handle("user:get",(event)=>{returnuser;});ipcMain.on("user:logout",(event)=>{user=null;openIndex();});functioncreateWindow(){mainWindow=newBrowserWindow({width:800,height:600,webPreferences:{preload:path.join(__dirname,"preload.js"),},});}functionopenIndex(){mainWindow.loadFile("index.html");// Open the DevTools.mainWindow.webContents.openDevTools();}functionopenHome(){mainWindow.loadFile("home.html");}// This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(()=>{createWindow();openIndex();app.on("activate",function(){// On macOS it's common to re-create a window in the app when the// dock icon is clicked and there are no other windows open.if(BrowserWindow.getAllWindows().length===0)createWindow();});});// Quit when all windows are closed, except on macOS. There, it's common// for applications and their menu bar to stay active until the user quits// explicitly with Cmd   Q.app.on("window-all-closed",function(){if(process.platform!=="darwin")app.quit();});

This file serves a few different functions. First, it is the main entry point for the application. Because of this, it also handles creating the window as well as the close function.

Manage your window’s lifecycle

Although you can now open a browser window, you’ll need some additional boilerplate code
to make it feel more native to each platform. Application windows behave differently on
each OS, and Electron puts the responsibility on developers to implement these
conventions in their app.

In general, you can use the process global’s platform attribute
to run code specifically for certain operating systems.

New version!

💥 Version 2 now out! New features include:

  • easier setup with no need for peer dependencies
  • support for non-Keytar refresh token libraries
  • support for future extensibility

Package and distribute your application

The fastest way to distribute your newly created app is using
Electron Forge.

  1. Add Electron Forge as a development dependency of your app, and use its import command to set up
    Forge’s scaffolding:

  2. Create a distributable using Forge’s make command:

    Electron Forge creates the out folder where your package will be located:

Preface​

As web developers, we usually enjoy the strong security net of the browser — the risks associated with the code we write are relatively small. Наши веб-сайты имеют ограниченные полномочия в песочнице, и мы верим, что пользователи довольны браузером, созданным большой командой инженеров, которая может быстро реагировать на последние обнаруженные угрозы безопасности.

Когда вы работаете в среде Электрон, важно понимать, что это не веб браузер. Электрон позволяет создавать функционально развитые приложения для настольных компьютеров с помощью веб технологий, но ваш код обладает большими возможностями. JavaScript имеет доступ к файловой системе, пользовательским скриптам и т. д.

Учтите что показ произвольного содержимого от недоверенных источников влечет за собой риски безопасности, которые Электрон не предназначен купировать. In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc) display primarily local content (or trusted, secure remote content without Node integration) — if your application executes code from an online source, it is your responsibility to ensure that the code is not malicious.

Prerequisites

To use Electron, you need to install Node.js. We recommend that you
use the latest LTS version available.

Please install Node.js using pre-built installers for your platform.
You may encounter incompatibility issues with different development tools otherwise.

To check that Node.js was installed correctly, type the following commands in your
terminal client:

The commands should print the versions of Node.js and npm accordingly.

Note: Since Electron embeds Node.js into its binary, the version of Node.js running
your code is unrelated to the version running on your system.

Problems?

If you’re having problems with the latest v2 release, try npm install [email protected].

Docs for the old release are here.

Security is everyone’s responsibility​

Важно помнить, что безопасность вашего Electron приложения является результатом общей безопасности основы платформы (Chromium, Node.js), самого Electron, всех NPM-зависимостей и вашего кода. Поэтому вы обязаны следовать нескольким важным рекомендациям:

📜 general details

This library is made available under the MIT license: see LICENSE file.

🔑 what exactly does this do?

When asked for an auth token, this library will try the following:

  1. If you have a valid token in memory, and won’t expire in the next 60 seconds, we return it
  2. If you have a refresh token, we exchange it for a new token
  3. If you have no refresh token (or have refresh tokens disabled), we open a new window with the Auth0 login page and begin a PKCE flow.

Discover more features in the API docs.

🚀 quick start guide: getting auth tokens

Install using NPM or Yarn:

🚨 This library expects a peerDependency of Electron 7

Set up an application in the Auth0 console:

Create a file called auth.ts/auth.js:

🛠 issues / contributions

Feel free to open an issue or pull request. Try to make these as detailed as possible: the more info, the easier it is to help. Example code is always good.

Quit the app when all windows are closed (windows & linux)

On Windows and Linux, exiting all windows generally quits an application entirely.

Access node.js from the renderer with a preload script

Now, the last thing to do is print out the version numbers for Electron and its
dependencies onto your web page.

Accessing this information is trivial to do in the main process through Node’s
global process object. However, you can’t just edit the DOM from the main
process because it has no access to the renderer’s document context.
They’re in entirely different processes!

Note: If you need a more in-depth look at Electron processes, see the
Process Model document.

Checklist: security recommendations​

You should at least follow these steps to improve the security of your application:

  1. Загружайте только безопасный контент
  2. Выключите Node.js интеграцию во всех видах (renderers) показывающих удаленный контент
  3. Enable context isolation in all renderers
  4. Enable process sandboxing
  5. Используйте ses.setPermissionRequestHandler() в сессиях с загрузкой удаленного контента
  6. Не выключайте webSecurity
  7. Определите Content-Security-Policy и используйте ограничительные правила (i.e. script-src 'self')
  8. Do not enable allowRunningInsecureContent
  9. Не включайте экспериментальные функции
  10. Не испольхуйте enableBlinkFeatures
  11. Disable or limit navigation
  12. Disable or limit creation of new windows
  13. Do not use shell.openExternal with untrusted content
  14. Use a current version of Electron

To automate the detection of misconfigurations and insecure patterns, it is possible to use Electronegativity. For additional details on potential weaknesses and implementation bugs when developing applications using Electron, please refer to this guide for developers and auditors.

. Validate the sender of all IPC messages​

You should always validate incoming IPC messages sender property to ensure you aren’t performing actions or sending information to untrusted renderers.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *