11
votes

I'm looking to deploy an auto-update feature to an Electron installation that I have, however I am finding it difficult to find any resources on the web.

I've built a self contained application using Adobe Air before and it seemed to be a lot easier writing update code that effectively checked a url and automatically downloaded and installed the update across Windows and MAC OSX.

I am currently using the electron-boilerplate for ease of build.

I have a few questions:

  • How do I debug the auto update feature? Do I setup a local connection and test through that using a local Node server or can I use any web server?
  • In terms of signing the application I am only looking to run apps on MAC OSX and particularly Windows. Do I have to sign the applications in order to run auto-updates? (I managed to do this with Adobe Air using a local certificate.
  • Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.
5

5 Answers

4
votes

I am also new to Electron but I think there is no simple auto-update from electron-boilerplate (which I also use). Electron's auto-updater uses Squirrel.Windows installer which you also need to implement into your solution in order to use it.

I am currently trying to use this:

And more info can be found here:

EDIT: I just opened the project to try it for a while and it looks it works. Its pretty straightforward. These are pieces from my gulpfile.

In current configuration, I use electron-packager to create a package.

var packager = require('electron-packager')
var createPackage = function () {
    var deferred = Q.defer();


    packager({
        //OPTIONS
    }, function done(err, appPath) {
        if (err) {
            gulpUtil.log(err);
        }

        deferred.resolve();
    });

    return deferred.promise;
};

Then I create an installer with electron-installer-squirrel-windows.

var squirrelBuilder = require('electron-installer-squirrel-windows');
var createInstaller = function () {
    var deferred = Q.defer();

squirrelBuilder({
// OPTIONS
}, function (err) {
        if (err)
            gulpUtil.log(err);

        deferred.resolve();
    });

    return deferred.promise;
}

Also you need to add some code for the Squirrel to your electron background/main code. I used a template electron-squirrel-startup.

if(require('electron-squirrel-startup')) return;

The whole thing is described on the electron-installer-squirrel-windows npm documentation mentioned above. Looks like the bit of documentation is enough to make it start. Now I am working on with electron branding through Squirrel and with creating appropriate gulp scripts for automation.

0
votes

You could also use standard Electron's autoUpdater module on OS X and my simple port of it for Windows: https://www.npmjs.com/package/electron-windows-updater

0
votes

I followed this tutorial and got it working with my electron app although it needs to be signed to work so you would need:

 certificateFile: './path/to/cert.pfx'

In the task config.

and:

"build": {
  "win": {
    "certificateFile": "./path/to/cert.pfx",
    "certificatePassword": "password"
  }
},

In the package.json

0
votes

Are there any good resources that detail how to implement the auto-update feature? As I'm having difficulty finding some good documentation on how to do this.

You don't have to implement it by yourself. You can use the provided autoUpdater by Electron and just set a feedUrl. You need a server that provides the update information compliant to the Squirrel protocol.

There are a couple of self-hosted ones (https://electronjs.org/docs/tutorial/updates#deploying-an-update-server) or a hosted service like https://www.update.rocks

0
votes

Question 1:

I use Postman to validate that my auto-update server URLs return the response I am expecting. When I know that the URLs provide the expected results, I know I can use those URLs within the Electron's Auto Updater of my Application.

Example of testing Mac endpoint with Postman:

Request: https://my-server.com/api/macupdates/checkforupdate.php?appversion=1.0.5&cpuarchitecture=x64

JSON Response when there is an update available:

{
    "url": "https:/my-server.com/updates/darwin/x64/my-electron=app-x64-1.1.0.zip",
    "name": "1.1.0",
    "pub_date": "2021-07-03T15:17:12+00:00"
}

Question 2:

Yes, your Electron App must be code signed to use the auto-update feature on Mac. On Windows I'm not sure because my Windows Electron app is code signed and I did not try without it. Though it is recommended that you sign your app even if the auto-update could work without it (not only for security reasons but mainly because otherwise your users will get scary danger warnings from Windows when they install your app for the first time and they might just delete it right away).


Question 3:

For good documentation, you should start with the official Electron Auto Updater documentation, as of 2021-07-07 it is really good.

The hard part, is figuring out how to make things work for Mac. For Windows it's a matter of minutes and you are done. In fact...

For Windows auto-update, it is easy to setup - you just have to put the RELEASES and nupkg files on a server and then use that URL as the FeedURL within your Electron App's autoUpdater. So if your app's update files are located at https://my-server.com/updates/win32/x64/ - you would point the Electron Auto Updater to that URL, that's it.

For Mac auto-update, you need to manually specify the absolute URL of the latest Electron App .zip file to the Electron autoUpdater. So, in order to make the Mac autoUpdater work, you will need to have a way to get a JSON response in a very specific format. Sadly, you can't just put your Electron App's files on your server and expect it to work with Mac just like that. Instead, the autoUpdater needs a URL that will return the aforementioned JSON response. So to do that, you need to pass Electron's Auto Updater feedURL the URL that will be able to return this expected kind of JSON response. The way you achieve this can be anything but I use PHP just because that's the server I already paid for.

So in summary, with Mac, even if your files are located at https://my-server.com/updates/darwin/x64/ - you will not provide that URL to Electron's Auto Updater FeedURL. Instead will provide another URL which returns the expected JSON response.

Here's an example of my main.js file for the Electron main process of my App:

// main.js (Electron main process)
function registerAutoUpdater() {
    const appVersion = app.getVersion();
    const os = require('os');
    const cpuArchitecture = os.arch();

    const domain = 'https://my-server.com';

    const windowsURL = `${domain}/updates/win32/x64`;
    const macURL = `${domain}/api/macupdates/checkforupdate.php?appversion=${appVersion}&cpuarchitecture=${cpuArchitecture}`;

    //init the autoUpdater with proper update feed URL
    const autoUpdateURL = `${isMac ? macURL : windowsURL}`;
    autoUpdater.setFeedURL({url: autoUpdateURL});
    log.info('Registered autoUpdateURL = ' + (isMac ? 'macURL' : 'windowsURL'));

    //initial checkForUpdates
    autoUpdater.checkForUpdates();

    //Automatic 2-hours interval loop checkForUpdates
    setInterval(() => {
        autoUpdater.checkForUpdates();
    }, 7200000);
}

And here's an example of the checkforupdate.php file that returns the expected JSON response back to the Electron Auto Updater:

<?php
//FD Electron App Mac auto update API endpoint.
// The way Squirrel.Mac works is by checking a given API endpoint to see if there is a new version.
// If there is no new version, the endpoint should return HTTP 204. If there is a new version,
// however, it will expect a HTTP 200 JSON-formatted response, containing a url to a .zip file:
// https://github.com/Squirrel/Squirrel.Mac#server-support

$clientAppVersion = $_GET["appversion"] ?? null;
if (!isValidVersionString($clientAppVersion)) {
    http_response_code(204);
    exit();
}
$clientCpuArchitecture = $_GET["cpuarchitecture"] ?? null;

$latestVersionInfo = getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture);
if (!isset($latestVersionInfo["versionNumber"])) {
    http_response_code(204);
    exit();
}

// Real logic starts here when basics did not fail
$isUpdateVailable = isUpdateAvailable($clientAppVersion, $latestVersionInfo["versionNumber"]);
if ($isUpdateVailable) {
    http_response_code(200);
    header('Content-Type: application/json;charset=utf-8');
    $jsonResponse = array(
        "url" => $latestVersionInfo["directZipFileURL"],
        "name" => $latestVersionInfo["versionNumber"],
        "pub_date" => date('c', $latestVersionInfo["createdAtUnixTimeStamp"]),
    );
    echo json_encode($jsonResponse);
} else {
    //no update: must respond with a status code of 204 No Content.
    http_response_code(204);
}
exit();
// End of execution.
// Everything bellow here are function declarations.


function getLatestVersionInfo($clientAppVersion, $clientCpuArchitecture): array {

    // override path if client requests an arm64 build
    if ($clientCpuArchitecture === 'arm64') {
        $directory = "../../updates/darwin/arm64/";
        $baseUrl = "https://my-server.com/updates/darwin/arm64/";
    } else if (!$clientCpuArchitecture || $clientCpuArchitecture === 'x64') {
        $directory = "../../updates/darwin/";
        $baseUrl = "https://my-server.com/updates/darwin/";
    }

    // default name with version 0.0.0 avoids failing
    $latestVersionFileName = "Finance D - Tenue de livres-darwin-x64-0.0.0.zip"; 

    $arrayOfFiles = scandir($directory);
    foreach ($arrayOfFiles as $file) {
        if (is_file($directory . $file)) {
            $serverFileVersion = getVersionNumberFromFileName($file);
            if (isVersionNumberGreater($serverFileVersion, $clientAppVersion)) {
                $latestVersionFileName = $file;
            }
        }
    }

    return array(
        "versionNumber" => getVersionNumberFromFileName($latestVersionFileName),
        "directZipFileURL" => $baseUrl . rawurlencode($latestVersionFileName),
        "createdAtUnixTimeStamp" => filemtime(realpath($directory . $latestVersionFileName))
    );
}

function isUpdateAvailable($clientVersion, $serverVersion): bool {
    return
        isValidVersionString($clientVersion) &&
        isValidVersionString($serverVersion) &&
        isVersionNumberGreater($serverVersion, $clientVersion);
}

function getVersionNumberFromFileName($fileName) {
    // extract the version number with regEx replacement
    return preg_replace("/Finance D - Tenue de livres-darwin-(x64|arm64)-|\.zip/", "", $fileName);
}

function removeAllNonDigits($semanticVersionString) {
    // use regex replacement to keep only numeric values in the semantic version string
    return preg_replace("/\D+/", "", $semanticVersionString);
}

function isVersionNumberGreater($serverFileVersion, $clientFileVersion): bool {
    // receives two semantic versions (1.0.4) and compares their numeric value (104)
    // true when server version is greater than client version (105 > 104)
    return removeAllNonDigits($serverFileVersion) > removeAllNonDigits($clientFileVersion);
}

function isValidVersionString($versionString) {
    // true when matches semantic version numbering: 0.0.0
    return preg_match("/\d\.\d\.\d/", $versionString);
}