Packaging a Local Inference Web Management UI with Electron
This guide explains how to wrap a locally hosted inference service in an Electron desktop application. It covers process and IPC boundaries, service lifecycle management, dynamic port allocation, health checks, child-process cleanup, renderer security, custom protocols, CSP, IPC validation, and Electron fuse configuration. The examples assume a service that exposes an HTTP health endpoint and can run independently of the desktop application.
1. Prerequisites and Version Requirements
- Node.js 20 LTS or later for running build scripts.
- Use the Electron version locked in
package.json. The APIs used in this guide—includingprotocol.handle,net.fetch, andcontextBridge—must be verified against your specific Electron version. After upgrading Electron, rerun all checks described here. The inference service must be able to run independently, accept a host and port, and expose a health-check endpoint. For example:
infer-server serve --host 127.0.0.1 --port 8080
Replace this with the command used by your framework.
- The health endpoint, referred to as
/healthbelow, should preferably require no authentication and return only service status. It should not expose configuration details or model paths. - macOS code signing requires an Apple Developer account. Windows code signing requires a code-signing certificate.
This guide does not cover command-line-only tools, services without an HTTP interface, or detailed Linux packaging.
2. Processes, IPC, and Port Health Checks
2.1 Four Application Layers
A desktop application can be divided into four layers. Each layer requires different failure handling.
| Layer | Responsibility | Key APIs | Failure handling |
|---|---|---|---|
| Renderer | Loads the frontend and displays service status | window.desktop |
Show an error page and provide a retry button |
| Main process | Manages windows and the application lifecycle | app, BrowserWindow |
Stop the service before exiting |
| Service manager | Creates, monitors, and cleans up the inference process | spawn, health checks |
Clean up failed processes and retry port conflicts up to three times |
| IPC layer | Passes messages between the renderer and main process | invoke, on |
Validate the sender and reject unexpected arguments |
2.2 Service States and Transitions
The service uses six states: idle, starting, ready, failed, stopping, and stopped.
| Current state | Event | Next state |
|---|---|---|
idle |
start is called |
starting |
starting |
Health check succeeds | ready |
starting |
Timeout, exhausted port retries, or early process exit | failed |
starting |
The user calls stop |
stopping |
ready |
stop is called or the application exits |
stopping |
ready |
The child process exits unexpectedly | stopped |
stopping |
The child process exits and cleanup completes | stopped |
failed |
The user clicks retry | starting |
stopped |
start is called |
starting |
Both start and stop should be idempotent. If start is called while startup is already in progress, it should return the same Promise. If the service is already ready, it should immediately return the current service information. If stop is called when no child process is alive, it should return immediately. This prevents repeated button clicks from starting multiple services.
2.3 The Preload Script
Expose only the methods the renderer needs. Do not expose ipcRenderer itself.
// preload.jsconst { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('desktop', {getServiceStatus: () => ipcRenderer.invoke('service:status'),startService: () => ipcRenderer.invoke('service:start'),stopService: () => ipcRenderer.invoke('service:stop'),onStatusChange: (callback) => {const listener = (_event, payload) => callback(payload);ipcRenderer.on('service:status-changed', listener);return () => ipcRenderer.removeListener('service:status-changed', listener);},});
The renderer can call only these four methods. If ipcRenderer is exposed directly, any script running in the page could send arbitrary messages to the main process. Startup arguments and paths must be controlled by the main process; the renderer must not be allowed to provide commands or paths.
2.4 Selecting a Port
A fixed port can conflict with another application. A safer approach is to let the operating system allocate an available port and bind the service only to 127.0.0.1.
// service-manager.js (excerpt)const net = require('net');function getFreePort() {return new Promise((resolve, reject) => {const server = net.createServer();server.once('error', reject);server.listen(0, '127.0.0.1', () => {const { port } = server.address();server.close(() => resolve(port));});});}
This approach has a race window: another process may claim the port between the check and the child process binding to it. If the child process writes address already in use or EADDRINUSE to standard error, select another port and restart it.
Binding to 0.0.0.0 would allow other machines on the local network to access the service. None of the examples in this guide use that address.
2.5 Environment Variable Allowlisting and Child-Process Startup
The child process should not inherit the host application’s complete environment. process.env may contain API keys, proxy credentials, and other sensitive values. Passing everything to the child process unnecessarily increases the risk of disclosure.
Pass only an allowlist of variables and inject a token for the current process:
const { spawn } = require('child_process');const { randomBytes } = require('crypto');const isWin = process.platform === 'win32';const ENV_ALLOWLIST = isWin? ['PATH', 'SYSTEMROOT', 'USERPROFILE', 'TEMP', 'TMP']: ['PATH', 'HOME', 'TMPDIR'];function buildEnv(token) {const env = {};for (const key of ENV_ALLOWLIST) {if (process.env[key]) env[key] = process.env[key];}env.INFER_API_TOKEN = token;return env;}function launchService(binPath, port, token) {const child = spawn(binPath,['serve', '--host', '127.0.0.1', '--port', String(port)],{env: buildEnv(token),windowsHide: true,detached: !isWin, // On Unix, create a new process group for group cleanupstdio: ['ignore', 'pipe', 'pipe'],});child.stderrTail = '';child.stdout.resume(); // Drain stdout or a full pipe can block the childchild.stderr.on('data', (chunk) => {child.stderrTail = (child.stderrTail + chunk.toString()).slice(-4096);});return child;}
Important considerations:
binPathmust come from the application’s own resource directory. It must never come from user input.- Pass arguments as an array rather than concatenating a shell command. This prevents spaces and special characters in paths from being interpreted incorrectly.
- Generate a new token for every startup. Use 32 bytes of random data. Pass it through an environment variable instead of a command-line argument, because other users may be able to view process command lines.
- Redact the token before writing logs. A service may echo the token in an error message:
function redact(text, token) {return token ? text.split(token).join('[REDACTED]') : text;}
2.6 Health Checks
A successful startup requires both a successful HTTP response and a child process that has not exited early. Use exponential backoff, increasing the interval from 300 milliseconds to 2 seconds, to avoid generating excessive requests and logs while the model is loading.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));async function waitForReady(child,port,token,{ timeoutMs, initialMs = 300, maxMs = 2000 }) {let exited = null;child.once('exit', (code, signal) => {exited = { code, signal };});const deadline = Date.now() + timeoutMs;let delay = initialMs;while (Date.now() < deadline) {if (exited) {throw new Error(`SERVICE_EXITED:${exited.code ?? exited.signal}`);}try {const res = await fetch(`http://127.0.0.1:${port}/health`, {headers: { Authorization: `Bearer ${token}` },// Remove the header if the health endpoint does not require authenticationsignal: AbortSignal.timeout(2000),});if (res.ok) return;} catch {// The service may not be listening yet}await sleep(delay);delay = Math.min(delay * 2, maxMs);}throw new Error('HEALTH_TIMEOUT');}
Set timeoutMs based on measurements rather than copying a default value. Start the service with the real model on target machines and record the time from process creation until /health first returns successfully. Run the test several times, use the maximum result, and add a 50% margin. Cold and warm model startup times can differ significantly, so measure both.
If /health requires authentication, keep the Authorization header. If it does not, remove the header. Do not place the token in a URL query parameter for convenience.
2.7 ServiceManager: Startup, Retries, and Shutdown
The following class combines state transitions, port retries, and process cleanup. stop has priority over start, so a user can stop the service even while startup is in progress.
const { execFile } = require('child_process');const { promisify } = require('util');const execFileAsync = promisify(execFile);const waitExit = (child) =>child.exitCode !== null || child.signalCode !== null? Promise.resolve(): new Promise((resolve) => child.once('exit', resolve));function signalGroup(pid, signal) {try {process.kill(-pid, signal); // A negative PID targets the process group} catch (err) {if (err.code !== 'ESRCH') throw err;}}class ServiceManager {constructor(binPath,{ healthTimeoutMs, stopGraceMs = 5000, onChange = () => {} }) {Object.assign(this, {binPath,healthTimeoutMs,stopGraceMs,onChange,});this.state = 'idle';this.url = null;this.error = null;this.child = null;this.pending = null;this.stopPending = null;}info() {return {state: this.state,url: this.url,error: this.error,};}setState(state, { url = null, error = null } = {}) {this.state = state;this.url = url;this.error = error;this.onChange(this.info());}start() {if (this.pending) return this.pending;if (this.state === 'ready') return Promise.resolve(this.info());this.pending = this._start().finally(() => {this.pending = null;});return this.pending;}async _start() {this.setState('starting');let lastError = null;for (let attempt = 1; attempt <= 3; attempt++) {const port = await getFreePort();const token = randomBytes(32).toString('hex');const child = launchService(this.binPath, port, token);this.child = child;child.once('exit', () => {if (this.child === child && this.state === 'ready') {this.setState('stopped');}});try {await waitForReady(child, port, token, {timeoutMs: this.healthTimeoutMs,});this.setState('ready', {url: `http://127.0.0.1:${port}`,});return this.info();} catch (err) {lastError = err;await this.killTree(child);if (this.state === 'stopping') {return this.info();}if (!/address already in use|EADDRINUSE/.test(child.stderrTail)) {break;}// Port conflict: request another port on the next attempt}}this.setState('failed', {error: lastError.message,});throw lastError;}stop() {if (this.stopPending) return this.stopPending;const child = this.child;if (!child ||child.exitCode !== null ||child.signalCode !== null) {return Promise.resolve(this.info());}this.stopPending = (async () => {this.setState('stopping', { url: this.url });await this.killTree(child);this.child = null;this.setState('stopped');return this.info();})().finally(() => {this.stopPending = null;});return this.stopPending;}async killTree(child) {const exited = waitExit(child);if (isWin) {// /T terminates the process tree and /F forces terminationawait execFileAsync('taskkill',['/pid', String(child.pid), '/T', '/F']).catch(() => {});await exited;return;}signalGroup(child.pid, 'SIGTERM');await Promise.race([exited, sleep(this.stopGraceMs)]);signalGroup(child.pid, 'SIGKILL');await exited;}}
Process cleanup differs by platform:
- Unix, including macOS and Linux: With
detached: true, the child becomes the leader of a new process group.process.kill(-pid, 'SIGTERM')notifies every process in that group. AfterstopGraceMs, which defaults to five seconds, sendSIGKILLto anything that remains. If the process group has already disappeared, the system returnsESRCH, which the code ignores. - Windows:
child.kill()terminates only the direct child. Worker processes created by the service may remain alive.taskkill /T /Fterminates the complete process tree. Console applications generally do not provide a reliable equivalent toSIGTERM, so this example uses forced termination. If the service provides an HTTP shutdown endpoint, call it first, wait several seconds, and then runtaskkillif necessary. - Final state handling: Set the state to
stoppedonly after the child emits itsexitevent. Otherwise, the interface may display “stopped” while the process is still running.
The application must stop the service before exiting. Intercept before-quit, wait for cleanup, and then exit:
const manager = new ServiceManager(resolveBinPath(), {healthTimeoutMs: 90000, // Adjust based on measurements from Section 2.6onChange: (info) => {for (const win of BrowserWindow.getAllWindows()) {win.webContents.send('service:status-changed', info);}},});let quitting = false;app.on('before-quit', (event) => {if (quitting) return;quitting = true;event.preventDefault();manager.stop().finally(() => app.quit());});
This mechanism cannot handle every termination scenario. If the main process is forcibly terminated—for example, through a task manager—or the system crashes, before-quit does not run. On Unix, the child process may continue running; on Windows, it may also remain alive.
Two possible mitigations are:
- After starting the service, write its PID and startup time to a PID file in the user data directory. On the next launch, read the file and terminate the process only after confirming that its name and start time match. Do not terminate a process based only on its PID, because the PID may have been reused.
- On Windows, place the child process in a Job Object configured to terminate the job when the main process closes its handle. This requires a native module or helper program and is more complex than the PID-file approach.
3. Security Hardening
The following measures reduce risk but do not make the application completely secure. Other programs running under the same user account may be able to read environment variables or access the local port. The objective is to reduce the attack surface, not eliminate every possible attack.
3.1 Window Configuration
const { BrowserWindow } = require('electron');function createWindow() {const win = new BrowserWindow({width: 1200,height: 800,webPreferences: {preload: path.join(__dirname, 'preload.js'),contextIsolation: true,nodeIntegration: false,sandbox: true,},});win.webContents.setWindowOpenHandler(() => ({action: 'deny',}));win.webContents.on('will-navigate', (event, url) => {const { protocol, origin } = new URL(url);const local = manager.url ? new URL(manager.url).origin : null;if (protocol !== 'app:' && origin !== local) {event.preventDefault();}});win.loadURL('app://bundle/index.html');return win;}
contextIsolation: truekeeps the preload context separate from the page context.nodeIntegration: falseprevents the page from accessing Node.js APIs directly.sandbox: trueruns the renderer in the system sandbox.setWindowOpenHandlerblocks new windows.will-navigateallows navigation only to the application itself or the local service.
3.2 Content Security Policy
Add the following CSP to the HTML shell. It restricts the page to local resources and permits connections only to the local service.
<meta http-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'; style-src 'self';connect-src 'self' http://127.0.0.1:*; img-src 'self' data:;object-src 'none'; base-uri 'none'">
If the shell embeds the management interface in an iframe, add:
frame-src http://127.0.0.1:*
If the management interface is served by the inference service, the service should send the CSP through its Content-Security-Policy response header. The main process can supplement that header with session.defaultSession.webRequest.onHeadersReceived.
After changing the CSP, check the developer console for Refused to ... errors. Framework-generated inline styles and scripts often require separate handling.
3.3 Custom Protocol and Path Validation
Load the shell through a custom app:// protocol. The following code maps requests to files in the packaged renderer directory and blocks paths that escape that directory.
const { app, net, protocol } = require('electron');const { pathToFileURL } = require('url');protocol.registerSchemesAsPrivileged([{scheme: 'app',privileges: {standard: true,secure: true,},},]);const rendererRoot = path.join(__dirname, 'renderer');app.whenReady().then(() => {protocol.handle('app', (request) => {const pathname = decodeURIComponent(new URL(request.url).pathname);const target = path.normalize(path.join(rendererRoot,pathname === '/' ? 'index.html' : pathname));if (!target.startsWith(rendererRoot + path.sep)) {return new Response('forbidden', { status: 403 });}return net.fetch(pathToFileURL(target).toString());});createWindow();});
registerSchemesAsPrivileged must run before app.ready, so it belongs at module scope. Perform the path check after path.normalize; this prevents .. segments from bypassing the validation.
3.4 IPC Validation
Main-process handlers must verify the request source and reject unexpected arguments.
const { ipcMain } = require('electron');function assertTrustedSender(event) {const frameUrl = event.senderFrame?.url ?? '';if (!frameUrl.startsWith('app://')) {throw new Error('UNTRUSTED_SENDER');}}function assertNoArgs(args) {if (args.length > 0) {throw new Error('INVALID_ARGS');}}ipcMain.handle('service:status', (event) => {assertTrustedSender(event);return manager.info();});ipcMain.handle('service:start', (event, ...args) => {assertTrustedSender(event);assertNoArgs(args);return manager.start();});ipcMain.handle('service:stop', (event, ...args) => {assertTrustedSender(event);assertNoArgs(args);return manager.stop();});
The current interfaces require no arguments. If parameters are added later, validate every field’s type and allowed range, and reject fields that are not explicitly allowlisted. The main process must always use its own configuration and must not trust paths or commands supplied by the renderer.
3.5 Disable Dangerous Features During Packaging
Use @electron/fuses after packaging to modify Electron’s binary fuse settings. The following configuration disables Node.js execution for the executable, prevents Node options from being injected through environment variables, disables CLI inspector arguments, and allows application code to load only from the ASAR archive.
const {flipFuses,FuseVersion,FuseV1Options,} = require('@electron/fuses');await flipFuses(electronBinaryPath, {version: FuseVersion.V1,[FuseV1Options.RunAsNode]: false,[FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,[FuseV1Options.EnableNodeCliInspectArguments]: false,[FuseV1Options.OnlyLoadAppFromAsar]: true,});
The order is:
- Package the application.
- Modify the fuse settings.
- Sign the binary.
Changing the fuse settings modifies the binary, so signing must happen afterward.
3.6 Additional Checks
- Bind the service only to
127.0.0.1. Verify this in startup arguments, configuration files, and firewall rules. - Do not expose the service on
0.0.0.0. - Keep executable paths under the application’s resource directory.
- Do not pass the host application’s complete environment to the child process.
- Redact authentication tokens from logs.
- Ensure shutdown waits for the child process to exit.
- Recheck Electron API availability after every Electron upgrade.
