Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

electron-asar-updater

npm version License: MIT

Asar hot-update bootstrap & build tools for Electron apps.

Electron only — This module relies on Electron's asar archive support and original-fs module. It is not compatible with plain Node.js applications.

Replace your entire business code (core.asar) without a full app reinstall — just download, verify, and restart.

No asarUnpack support — Projects using electron-builder's asarUnpack will fail at build time. Remove asarUnpack from your config — native .node modules work fine inside asar (Electron auto-extracts them to a temp directory at runtime). asarUnpack is only needed for child_process executables or modules requiring companion files at real filesystem paths.

How It Works

Build (afterPack)

Step Action
1 electron-builder packs app.asar normally (everything)
2 Rename app.asar → core.asar
3 Sign core.asar with RSA-SHA256 (signature embedded in tail)
4 Create new minimal app.asar (bootstrap.js + this module)
5 Patch Electron's built-in asar integrity hash (if present — see Compatibility)

Runtime (bootstrap)

Step Action
1 Swap — core.asar.new → core.asar (if exists)
2 Verify — RSA-SHA256 signature check
3 Compare — Pick newer version (bundled vs downloaded)
4 Load — require(core.asar/<main from package.json>)
5 Fallback — Try next version → error dialog → quit

Dual-asar architecture

resources/
  app.asar        ← Tiny (~KB). Contains only bootstrap.js + this module.
  core.asar       ← Full app. electron-builder's original app.asar, renamed.

<userData>/updates/asar/
  core.asar       ← Downloaded hot-update version (signature embedded in tail)
  core.asar.new   ← Pending update (swapped on next launch)

Quick Start

1. Install

npm install electron-asar-updater --save-dev

Install as a devDependency. The afterPack hook automatically bundles the runtime code into a minimal app.asar — no need for it in production dependencies (which would bloat core.asar).

2. Initialize

npx electron-asar-updater init

This single command does everything:

  • Generates RSA key pair → keys/public_key.pem + keys/private_key.pem
  • Creates bootstrap.js with the public key already embedded
  • Adds keys/ to .gitignore

Prefer manual setup? See Manual Setup below.

3. Add build hook (afterpack.js)

const { buildCoreAsar } = require('electron-asar-updater/build');

exports.default = async function (context) {
  await buildCoreAsar(context, {
    entryFile: './bootstrap.js',
    privateKeyPath: process.env.ASAR_PRIVATE_KEY_PATH || './keys/private_key.pem',
  });
};

4. Build and run

npm run build

The afterPack hook will: rename app.asar → core.asar → sign → create minimal app.asar → optional zip archive.

Integrating into an existing Electron project requires zero restructuring — your project structure, webpack/vite config, and build pipeline stay exactly the same. To remove: delete bootstrap.js, afterpack.js, and the afterPack config line. No other traces.

Manual Setup

If you prefer to set up each step manually (or need to customize the bootstrap file):

Click to expand manual setup steps

Generate signing keys

npx electron-asar-updater keygen --out ./keys

Creates keys/public_key.pem and keys/private_key.pem, and adds keys/ to .gitignore.

Create bootstrap.js

Create a bootstrap file at project root. This file is only used in production builds — in development, Electron loads your app entry directly.

const path = require('path');
const { app } = require('electron');
const { bootstrap } = require('electron-asar-updater');

bootstrap({
  publicKey: `-----BEGIN PUBLIC KEY-----
...paste contents of keys/public_key.pem here...
-----END PUBLIC KEY-----`,
  bundledAsarPath: path.join(process.resourcesPath, 'core.asar'),
  downloadDir: path.join(app.getPath('userData'), 'updates', 'asar'),
});

Note: asarEntryPoint is auto-detected from core.asar/package.json's main field. No need to specify it.

Configure electron-builder

Add afterPack to your package.json:

{
  "build": {
    "afterPack": "./afterpack.js"
  }
}

Examples

Quick Demo (hot-update in 30 seconds)

See the full hot-update flow — build, sign, serve, download, swap, restart:

# 1. Build an example (e.g. basic)
cd examples/basic
npm install
npx electron-asar-updater init
npm run build

# 2. Start the demo update server
cd ../demo && npm install
npm run demo:basic

# 3. Launch the built app and click "Check for Update"

Click "Check for Update" → "Restart Now" → watch the version change from v1.0.0 to v2.0.0.

Integration Examples

Implementing Your Own Updater

This module handles bootstrap + build + signing, but does not include download logic — every project has unique needs (authentication, CDN, rollback strategies, etc.). You implement the download part.

Update Flow Overview

Stage Build CI Server Client (App)
Build afterPack → core.asar + .zip
Upload Receive zip → CDN / API
Startup bootstrap() → swap → verify → load
Check ← GET /latest Check version
Respond → { version, url } Has update?
Download ← GET /*.zip Download zip
Install Extract core.asar.new
Restart app.relaunch() → next launch auto-swaps

Build side: buildCoreAsar() with archiveDir produces core.asar.<version>.zip containing core.asar.new (signed).

Server side: Host the zip on CDN and provide a version API (can be a static JSON file).

Client side: Check version → download zip → extract to downloadDir → restart → bootstrap() auto-swaps on next launch.

Server API Example

A simple static JSON file is enough:

{
  "version": "1.2.0",
  "downloadUrl": "https://cdn.example.com/updates/core.asar.1.2.0.zip"
}

Client Implementation

// updater.js — run in main process after app is ready
const { app } = require('electron');
const path = require('path');
const fs = require('fs');
const { compareVersions } = require('electron-asar-updater');

const DOWNLOAD_DIR = path.join(app.getPath('userData'), 'updates', 'asar');
const UPDATE_API = 'https://api.example.com/updates/latest';

async function checkAndUpdate(currentVersion) {
  // 1. Check for update
  const res = await fetch(UPDATE_API);
  const remote = await res.json(); // { version: "1.2.0", downloadUrl: "..." }

  if (compareVersions(remote, currentVersion) <= 0) {
    console.log('Already up to date');
    return false;
  }

  // 2. Download zip
  console.log(`Updating: ${currentVersion.version} → ${remote.version}`);
  if (!fs.existsSync(DOWNLOAD_DIR)) {
    fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
  }

  const zipPath = path.join(DOWNLOAD_DIR, 'update.zip');
  const response = await fetch(remote.downloadUrl);
  const buffer = Buffer.from(await response.arrayBuffer());
  fs.writeFileSync(zipPath, buffer);

  // 3. Extract — produces core.asar.new in downloadDir
  const AdmZip = require('adm-zip');
  const zip = new AdmZip(zipPath);
  zip.extractAllTo(DOWNLOAD_DIR, true);
  fs.unlinkSync(zipPath); // clean up zip

  // 4. Prompt user to restart (or restart silently)
  const { dialog } = require('electron');
  const { response: btn } = await dialog.showMessageBox({
    type: 'info',
    title: 'Update Available',
    message: `Version ${remote.version} has been downloaded. Restart now?`,
    buttons: ['Restart', 'Later'],
  });

  if (btn === 0) {
    app.relaunch();
    app.exit(0);
  }

  return true;
}

module.exports = { checkAndUpdate };

Using with bootstrap() Result

// In your main process entry (inside core.asar)
const path = require('path');
const { app } = require('electron');
const { readVersion } = require('electron-asar-updater');

const currentVersion = readVersion(
  path.join(process.resourcesPath, 'core.asar')
);

app.whenReady().then(() => {
  // ... create windows ...

  // Check for updates after app is ready (non-blocking)
  const { checkAndUpdate } = require('./updater');
  checkAndUpdate(currentVersion).catch(console.error);
});

TypeScript Interfaces

For structured implementations, use the provided interfaces:

import type { AsarUpdater, VersionInfo, UpdateCheckResult } from 'electron-asar-updater';
import { compareVersions } from 'electron-asar-updater';

class MyUpdater implements AsarUpdater {
  async checkForUpdate(currentVersion: VersionInfo): Promise<UpdateCheckResult> {
    const res = await fetch('https://api.example.com/updates/latest');
    const remote = await res.json();
    return {
      hasUpdate: compareVersions(remote, currentVersion) > 0,
      remoteVersion: remote,
      currentVersion,
    };
  }

  async downloadUpdate(remoteVersion, downloadDir, onProgress?) {
    const zipPath = path.join(downloadDir, 'update.zip');
    // ... download remoteVersion.downloadUrl to zipPath ...
    return zipPath;
  }

  async installUpdate(downloadedPath, downloadDir) {
    // Extract zip so that this file exists:
    //   <downloadDir>/core.asar.new  (signature embedded in file tail)
    // On next app launch, bootstrap() will swap it in.
    const AdmZip = require('adm-zip');
    const zip = new AdmZip(downloadedPath);
    zip.extractAllTo(downloadDir, true);
  }
}

Version Format

Version is read from package.json inside the asar — the same version field you already have in your project. Standard semver format (major.minor.patch), compared numerically segment by segment.

API Reference

Runtime — require('electron-asar-updater')

bootstrap(config): BootstrapResult

Config Type Required Default Description
publicKey string Yes — PEM public key for signature verification
bundledAsarPath string Yes — Path to bundled core.asar in resources/
downloadDir string Yes — Directory containing downloaded asar updates
asarFilename string No 'core.asar' Downloaded asar filename
updateFilename string No 'core.asar.new' Pending update filename
asarEntryPoint string No Auto from package.json main Entry file inside asar
versionFile string No 'package.json' Version file inside asar
verify Function No RSA-SHA256 Custom (filePath, pubKey) => boolean
compareVersions Function No Built-in Custom (a, b) => number
onLoadFailure Function No Show dialog Return false to suppress default error dialog
logger object No console { info, warn, error }
devMode boolean No !app.isPackaged Override dev mode detection
devEntryPoint string No — Dev mode require path (only if bootstrap.js is used in dev)
throwOnBundledFailure boolean No true Throw when bundled asar fails (vs. silent fallback)

Returns BootstrapResult:

{
  loaded: boolean;
  source: 'bundled' | 'downloaded' | 'dev' | null;
  loadedPath: string | null;
  loadedVersion: VersionInfo | null;     // { version }
  swapped: boolean;
  downloadValid: boolean;
}

compareVersions(ver1, ver2): number

Compare two { version } objects. Returns 1 if ver1 is newer, -1 if older, 0 if equal.

const { compareVersions } = require('electron-asar-updater');
compareVersions({ version: '1.2.1' }, { version: '1.2.0' });
// → 1

readVersion(asarPath, versionFile?): VersionInfo | null

Read version from inside an asar file. By default reads package.json and extracts the version field.

isValidVersion(info): boolean

Check if a version info object matches the expected format.

Build — require('electron-asar-updater/build')

generateKeyPair(options?): { publicKey, privateKey }

Generate an RSA-2048 PEM key pair for asar signing.

signAsar(options): string

Sign an asar file by appending RSA-SHA256 signature to the file tail. Format: [asar data][signature][sigLen uint32 LE][magic "ASGN"]. Returns base64 signature.

signAsar({
  asarPath: 'dist/core.asar',
  privateKey: fs.readFileSync('keys/private_key.pem', 'utf8'),
});

verifyAsar(options): { valid, error? }

Verify the embedded RSA-SHA256 signature of a signed asar file. Works in plain Node.js (no Electron required).

const result = verifyAsar({
  asarPath: 'dist/core.asar',
  publicKey: fs.readFileSync('keys/public_key.pem', 'utf8'),
});
// result: { valid: true } or { valid: false, error: 'reason' }

packAsar(options): Promise<void>

Pack a directory into an asar file (standalone utility).

await packAsar({
  sourceDir: 'dist/app',
  outputPath: 'dist/app.asar',
  cleanSource: true,
});

archiveUpdate(options): Promise<void>

Create a zip archive containing core.asar.new for hot-update distribution. The asar file already has the signature embedded in its tail.

await archiveUpdate({
  asarPath: 'dist/core.asar',
  outputPath: 'dist/update/core.asar.1.2.0.zip',
});

buildCoreAsar(context, options): Promise<void>

All-in-one integration for electron-builder afterPack. Renames app.asar → core.asar, signs it, creates minimal new app.asar.

await buildCoreAsar(context, {
  entryFile: './bootstrap.js',                // path to bootstrap file
  privateKeyPath: './keys/private_key.pem',
  archiveDir: './dist/update',            // optional: create zip archive
});

createAfterPackHook(options): Function

Convenience factory:

// afterpack.js
const { createAfterPackHook } = require('electron-asar-updater/build');
exports.default = createAfterPackHook({
  entryFile: './bootstrap.js',
  privateKeyPath: './keys/private_key.pem',
});

computeAsarHeaderHash(asarPath): string

Compute the SHA256 hash of an asar archive's raw header. Uses the same algorithm as Electron's built-in integrity check. Requires @electron/asar.

const hash = computeAsarHeaderHash('dist/resources/app.asar');
// → 'a3f2...hex string'

updateBuiltinAsarIntegrity(context, appAsarPath): Promise<void>

Detect whether Electron's built-in integrity hash is embedded in the app binary and, if so, recompute it for the provided app.asar. Called automatically by buildCoreAsar(). Exposed for advanced use cases (e.g. custom build pipelines that call the steps individually).

No-op if no hash is found. Set ASAR_SKIP_INTEGRITY_UPDATE=1 to skip explicitly. Windows requires resedit.

CLI

npx electron-asar-updater <command> [options]

init

One-command project setup. Generates keys, creates bootstrap.js with the public key embedded, detects your project type, and generates the appropriate afterpack.js.

npx electron-asar-updater init [--entry <path>]
Option Default Description
--entry <path> ./bootstrap.js Output path for the bootstrap entry file

What it does:

  1. Generates RSA-2048 key pair → keys/public_key.pem + keys/private_key.pem
  2. Reads the public key and injects it into the bootstrap template → writes to --entry path
  3. Adds keys/ to .gitignore
  4. Detects project type and generates afterpack.js at the appropriate path
  5. Prints type-specific next steps

Auto-detected project types:

Project Type Detection Signal afterpack.js Path Next Steps
electron-vite electron-vite in deps or electron.vite.config.* exists ./build/afterpack.js Add afterPack to electron-builder.yml
electron-builder electron-builder in deps or build key in package.json ./afterpack.js Add afterPack to package.json build config
electron-forge @electron-forge/* in deps or forge.config.* exists (not generated) Manual integration required
unknown None of the above ./afterpack.js Generic instructions

Skips any step that's already done (existing keys, existing entry file, existing afterpack.js).

keygen

Generate an RSA-2048 key pair for asar signing (without creating bootstrap.js).

npx electron-asar-updater keygen [--out <dir>]
Option Default Description
--out <dir> ./keys Output directory for key files

sign

Sign an asar file by embedding an RSA-SHA256 signature in the file tail. Useful for CI/CD pipelines or manual signing.

npx electron-asar-updater sign <asar-path> [--key <private-key-path>]
Option Default Description
--key <path> ./keys/private_key.pem Path to PEM private key

Private key resolution priority: ASAR_PRIVATE_KEY env (key content) > ASAR_PRIVATE_KEY_PATH env > --key flag > default path.

verify

Verify the embedded signature of a signed asar file. Exit code 0 = valid, 1 = invalid.

npx electron-asar-updater verify <asar-path> [--key <public-key-path>]
Option Default Description
--key <path> ./keys/public_key.pem Path to PEM public key

archive

Create a zip archive from a signed asar file for hot-update distribution.

npx electron-asar-updater archive <asar-path> [--out <zip-path>]
Option Default Description
--out <path> ./<basename>.zip Output zip path

The zip contains a single file core.asar.new (the signed asar).

check

Validate that your project setup is complete — keys exist, bootstrap.js is in place, and afterPack is properly configured. Exit code 0 = all good, 1 = errors found.

npx electron-asar-updater check

Checks performed:

  • Keys exist (keys/public_key.pem, keys/private_key.pem)
  • keys/ is in .gitignore
  • bootstrap.js exists and references electron-asar-updater
  • afterPack is configured in build config and the hook calls buildCoreAsar()

Run this after init to verify everything is wired up correctly.

Compatibility

Electron built-in asar integrity

Electron supports an optional built-in asar integrity check (EnableEmbeddedAsarIntegrityValidation fuse, available on macOS since Electron 16, Windows since Electron 30). When enabled, the app binary contains a SHA256 hash of the app.asar header; a mismatch at startup terminates the app immediately.

buildCoreAsar() replaces app.asar with a new bootstrap file during afterPack. electron-builder computes and embeds the integrity hash before afterPack runs, so without correction the embedded hash would point to the original (now-renamed) file.

This is handled automatically. After creating the new app.asar, buildCoreAsar() detects whether a hash was embedded and recomputes it. The fix is a no-op if the feature is not in use (older electron-builder, fuse disabled).

Windows requirement

On Windows, updating the PE resource inside the .exe requires the resedit package:

npm install --save-dev resedit

resedit is already used by @electron/fuses — if you flip fuses in your build, it is likely already in your node_modules. If resedit is missing and the integrity resource is present in the binary, the build will fail with an actionable error message.

Opting out

Set ASAR_SKIP_INTEGRITY_UPDATE=1 to skip the patch step entirely. Only safe when EnableEmbeddedAsarIntegrityValidation is confirmed to be off.

ASAR_SKIP_INTEGRITY_UPDATE=1 npm run build

Interaction with OnlyLoadAppFromAsar fuse

The OnlyLoadAppFromAsar fuse prevents loading code from outside an asar. It does not affect core.asar — that file is loaded via require() from inside app.asar, which is already inside the asar boundary. No additional configuration is needed.


Security

  • Public key is embedded in app.asar — safe to distribute, used for runtime verification
  • Private key must never be in app.asar or committed to git
    • Pass via ASAR_PRIVATE_KEY_PATH env var (recommended for CI/CD)
    • Or pass key content directly via ASAR_PRIVATE_KEY env var
    • Or local file path ./keys/private_key.pem (for local builds)
  • keygen command automatically adds keys/ to .gitignore
  • All downloaded asars are verified against the public key before loading
  • Verification failure → fall back to bundled version → never load untrusted code

FAQ

Q: Can I use this in a plain Node.js project?

No. This module is designed exclusively for Electron. It depends on Electron's asar archive support (patched fs for reading inside .asar files) and original-fs (unpatched fs for physical file operations). In a plain Node.js environment, .asar files are just opaque binaries — there is no way to require() modules from inside them.

Q: What is original-fs?

Electron patches Node's fs module to transparently read inside .asar archives. original-fs is the unpatched version that does real filesystem I/O. This module uses original-fs for physical file operations (swap, verify) and fs for reading inside asar archives (package.json).

Q: Why does bootstrap() need to be synchronous?

The entry point must require() the business code before the Electron event loop starts. An async bootstrap would cause the app to show a blank window while loading.

Q: Can I use this without electron-builder?

Yes. bootstrap() and the utility functions (signAsar, packAsar) work independently. buildCoreAsar() is the only function tied to electron-builder's afterPack context.

Q: What happens if the downloaded asar is corrupted?

Signature verification will fail → the bundled version loads instead → on total failure, the app shows an error dialog and deletes the problematic files on exit, so the next launch uses the bundled version.

Q: Should I commit the generated bootstrap.js?

Yes. bootstrap.js is your project's production entry point (with the public key embedded). Commit it to version control. The private key (keys/) is automatically gitignored.

Q: Should I exclude bootstrap.js and afterpack.js from core.asar?

Optional. These files are only used during the build process. They'll work fine inside core.asar (just unused bytes), but you can exclude them to keep core.asar slightly smaller:

{
  "build": {
    "files": ["!afterpack.js", "!bootstrap.js", "!keys${/*}"],
    "afterPack": "./afterpack.js"
  }
}

Q: Is Electron's built-in asar integrity (EnableEmbeddedAsarIntegrityValidation fuse) compatible?

Yes. buildCoreAsar() automatically detects and patches the integrity hash after replacing app.asar. On Windows, install resedit as a dev dependency if you use this fuse. See Compatibility for details.

Q: Does this support asarUnpack (native modules)?

No. If your electron-builder config uses asarUnpack, the build will fail with an error — hot-update zips only contain core.asar, so the unpacked directory would become stale after a swap. The fix is simple: remove asarUnpack from your config. Native .node modules work fine inside asar — Electron automatically extracts them to a temp directory at runtime via process.dlopen. asarUnpack is only truly needed for child_process.spawn() executables or modules that require companion files (.dll/.so) at real filesystem paths.

Q: How do I distribute hot-updates?

  1. Build with archiveDir option — produces core.asar.<version>.zip
  2. Upload the zip to your CDN/server, update your version API
  3. Client checks version → downloads zip → extracts core.asar.new to downloadDir
  4. On next app restart, bootstrap() auto-swaps and loads the new version

See Implementing Your Own Updater for a complete example.

License

MIT

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages