Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions electron/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,13 @@ const {
nativeImage,
shell,
session,
dialog,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Unused import - dialog is imported but never used in the codebase. Either remove this import or implement dialog functionality.

Notification,
} = require("electron");
const path = require("path");
const { spawn } = require("child_process");
const fs = require("fs");
const { autoUpdater } = require("electron-updater");

// ── Single Instance Lock ───────────────────────────────────
const gotTheLock = app.requestSingleInstanceLock();
Expand Down Expand Up @@ -62,6 +65,11 @@ let serverPort = 20128;

const getServerUrl = () => `http://localhost:${serverPort}`;

// ── Auto-Updater Configuration ──────────────────────────────
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;
autoUpdater.logger = console;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Using console as the logger could expose sensitive information in production. Consider using a proper logger or setting up environment-specific logging levels.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While using console for logging is acceptable during development, electron-updater strongly recommends using electron-log in production. It provides out-of-the-box file logging, which is invaluable for diagnosing update-related issues on user machines. You'll need to add electron-log to your dependencies in package.json.

Suggested change
autoUpdater.logger = console;
autoUpdater.logger = require("electron-log");


// ── Helper: Send IPC event to renderer (#5) ────────────────
function sendToRenderer(channel, data) {
if (mainWindow && !mainWindow.isDestroyed()) {
Expand Down Expand Up @@ -103,6 +111,85 @@ async function waitForServerExit(proc, timeoutMs = 5000) {
]);
}

// ── Auto-Updater Event Handlers ─────────────────────────────
function setupAutoUpdater() {
autoUpdater.on("checking-for-update", () => {
sendToRenderer("update-status", { status: "checking" });
console.log("[Electron] Checking for updates...");
});

autoUpdater.on("update-available", (info) => {
sendToRenderer("update-status", { status: "available", version: info.version });
console.log("[Electron] Update available:", info.version);
});

autoUpdater.on("update-not-available", (info) => {
sendToRenderer("update-status", { status: "not-available", version: info.version });
console.log("[Electron] No update available");
});

autoUpdater.on("download-progress", (progress) => {
sendToRenderer("update-status", {
status: "downloading",
percent: Math.round(progress.percent),
transferred: progress.transferred,
total: progress.total,
});
});

autoUpdater.on("update-downloaded", (info) => {
sendToRenderer("update-status", { status: "downloaded", version: info.version });
console.log("[Electron] Update downloaded:", info.version);

if (Notification.isSupported()) {
const notification = new Notification({
title: "OmniRoute Update Ready",
body: `Version ${info.version} is ready to install. Click to restart.`,
});
notification.on("click", () => {
autoUpdater.quitAndInstall();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: quitAndInstall() is called without any cleanup of the Next.js server or saving application state. This could lead to data loss or incomplete operations. Consider graceful shutdown before installing updates.

});
notification.show();
}
});

autoUpdater.on("error", (error) => {
sendToRenderer("update-status", { status: "error", message: error.message });
console.error("[Electron] Update error:", error);
});
}

async function checkForUpdates(silent = false) {
if (isDev) {
console.log("[Electron] Dev mode — skipping auto-update");
if (!silent) {
sendToRenderer("update-status", { status: "error", message: "Updates disabled in dev mode" });
}
return;
}
try {
await autoUpdater.checkForUpdates();
} catch (error) {
console.error("[Electron] Check for updates failed:", error);
if (!silent) {
sendToRenderer("update-status", { status: "error", message: error.message });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This catch block currently handles the error by logging it and sending an IPC message, but it effectively swallows the error. This prevents the promise returned by ipcMain.handle from rejecting, which can be misleading for the renderer process. To ensure the renderer can properly handle failures (e.g., in a try/catch block around the invoke call), you should re-throw the error after logging it.

    console.error("[Electron] Check for updates failed:", error);
    if (!silent) {
      sendToRenderer("update-status", { status: "error", message: error.message });
    }
    throw error;

}
}

async function downloadUpdate() {
try {
await autoUpdater.downloadUpdate();
} catch (error) {
console.error("[Electron] Download update failed:", error);
sendToRenderer("update-status", { status: "error", message: error.message });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Similar to the checkForUpdates function, this catch block swallows the error. This prevents the corresponding ipcMain.handle from rejecting on failure. You should re-throw the error here as well to ensure the renderer process is aware of the failure and can handle it appropriately.

    console.error("[Electron] Download update failed:", error);
    sendToRenderer("update-status", { status: "error", message: error.message });
    throw error;

}
}

function installUpdate() {
autoUpdater.quitAndInstall();
}

// ── Content Security Policy (#15) ──────────────────────────
function setupContentSecurityPolicy() {
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
Expand Down Expand Up @@ -236,6 +323,11 @@ function createTray() {
],
},
{ type: "separator" },
{
label: "Check for Updates",
click: () => checkForUpdates(false),
},
{ type: "separator" },
{
label: "Quit",
click: () => {
Expand Down Expand Up @@ -391,6 +483,24 @@ function setupIpcHandlers() {
});

ipcMain.on("window-close", () => mainWindow?.close());

// Auto-update IPC handlers
ipcMain.handle("check-for-updates", async () => {
await checkForUpdates(false);
return { success: true };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: This IPC handler returns { success: true } regardless of whether the update check actually succeeded or failed. The renderer process cannot distinguish between success and failure. Consider returning error information when the update check fails.

});

ipcMain.handle("download-update", async () => {
await downloadUpdate();
return { success: true };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: This IPC handler returns { success: true } even if downloadUpdate() throws an error. The error is logged but not returned to the caller, making it impossible for the renderer to know if the download failed.

});

ipcMain.handle("install-update", () => {
installUpdate();
return { success: true };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: This IPC handler returns { success: true } even though installUpdate() (quitAndInstall) will quit the application immediately. The return value is meaningless in this context.

});

ipcMain.handle("get-app-version", () => app.getVersion());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL: The get-app-version handler doesn't return the version. It calls app.getVersion() but doesn't return the result, so callers will always receive undefined instead of the actual version string.

}

// ── App Lifecycle ──────────────────────────────────────────
Expand All @@ -407,6 +517,14 @@ app.whenReady().then(async () => {
createWindow();
createTray();
setupIpcHandlers();
setupAutoUpdater();

// Check for updates after a short delay (don't block startup)
if (!isDev) {
setTimeout(() => {
checkForUpdates(true);
}, 3000);
}

// macOS: recreate window when dock icon clicked
app.on("activate", () => {
Expand Down
9 changes: 8 additions & 1 deletion electron/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
"build:linux": "electron-builder --linux",
"pack": "electron-builder --dir"
},
"dependencies": {},
"dependencies": {
"electron-updater": "^6.8.3"
},
"devDependencies": {
"electron": "^40.6.1",
"electron-builder": "^25.1.8"
Expand All @@ -28,6 +30,11 @@
"output": "dist-electron",
"buildResources": "assets"
},
"publish": {
"provider": "github",
"owner": "diegosouzapw",
"repo": "OmniRoute"
},
Comment on lines +33 to +37

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Hardcoding the owner and repo here works, but it makes the configuration less portable. A more maintainable approach is to let electron-builder infer these values from a repository field in your package.json. You can remove the owner and repo keys and add a top-level repository field instead:

"repository": {
  "type": "git",
  "url": "https://github.com/diegosouzapw/OmniRoute.git"
}
    "publish": {
      "provider": "github"
    },

"files": [
"main.js",
"preload.js",
Expand Down
20 changes: 18 additions & 2 deletions electron/preload.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,18 @@ const { contextBridge, ipcRenderer } = require("electron");

// ── Channel Whitelist ──────────────────────────────────────
const VALID_CHANNELS = {
invoke: ["get-app-info", "open-external", "get-data-dir", "restart-server"],
invoke: [
"get-app-info",
"open-external",
"get-data-dir",
"restart-server",
"check-for-updates",
"download-update",
"install-update",
"get-app-version",
],
send: ["window-minimize", "window-maximize", "window-close"],
receive: ["server-status", "port-changed"],
receive: ["server-status", "port-changed", "update-status"],
};

// ── Fix #16: Generic IPC wrappers ──────────────────────────
Expand Down Expand Up @@ -48,6 +57,12 @@ contextBridge.exposeInMainWorld("electronAPI", {
openExternal: (url) => safeInvoke("open-external", url),
getDataDir: () => safeInvoke("get-data-dir"),
restartServer: () => safeInvoke("restart-server"),
getAppVersion: () => safeInvoke("get-app-version"),

// ── Auto-Update ──────────────────────────────────────────
checkForUpdates: () => safeInvoke("check-for-updates"),
downloadUpdate: () => safeInvoke("download-update"),
installUpdate: () => safeInvoke("install-update"),

// ── Send (fire-and-forget) ───────────────────────────────
minimizeWindow: () => safeSend("window-minimize"),
Expand All @@ -58,6 +73,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Fix #6: Returns a disposer function for precise cleanup
onServerStatus: (callback) => safeOn("server-status", callback),
onPortChanged: (callback) => safeOn("port-changed", callback),
onUpdateStatus: (callback) => safeOn("update-status", callback),

// ── Static Properties ────────────────────────────────────
isElectron: true,
Expand Down