Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(linux): register the sign-in link handler for AppImage and tar.gz (#2312)

Joshua05dcbf8a8cca
diff --git a/main.js b/main.js
index c843205e3..4f92ee7d6 100644
--- a/main.js
+++ b/main.js
@@ -151,6 +151,8 @@ function getOAuthProtocol() {
const OAUTH_PROTOCOL = getOAuthProtocol();
+const { registerLinuxUrlSchemeHandler } = require("./src/helpers/linuxUrlSchemeHandler");
+
function shouldRegisterProtocolWithAppArg() {
return Boolean(process.defaultApp) || isElectronBinaryExec();
}
@@ -186,9 +188,10 @@ function restoreHtmlHandlerIfChanged(original) {
// True source of truth for whether openwhispr:// resolves on Linux — the same
// MIME database xdg-open consults. Returns true for deb/rpm/flatpak/AUR installs
-// (scheme registered via the packaged .desktop MimeType) and false for AppImage/
-// tar.gz runs where it genuinely isn't registered, so we never enable a dead-end
-// OAuth flow. Used to recover from setAsDefaultProtocolClient's KDE false negative.
+// (scheme registered via the packaged .desktop MimeType; registerLinuxUrlSchemeHandler
+// first takes it back from an AppImage/tar.gz entry) and false for AppImage/tar.gz
+// runs whose own registration failed, so we never enable a dead-end OAuth flow.
+// Used to recover from setAsDefaultProtocolClient's KDE false negative.
function isOAuthSchemeRegistered() {
if (process.platform !== "linux") return false;
try {
@@ -204,17 +207,22 @@ function isOAuthSchemeRegistered() {
}
}
-// Register custom protocol for OAuth callbacks.
// In development, always include the app path argument so macOS/Windows/Linux
// can launch the project app instead of opening bare Electron.
+function getProtocolAppArgs() {
+ if (!shouldRegisterProtocolWithAppArg()) return [];
+ return [process.argv[1] ? path.resolve(process.argv[1]) : path.resolve(".")];
+}
+
+// Register custom protocol for OAuth callbacks.
function registerOpenWhisprProtocol() {
const protocol = OAUTH_PROTOCOL;
const htmlHandler = process.platform === "linux" ? getDefaultHtmlHandler() : null;
+ const appArgs = getProtocolAppArgs();
let result;
- if (shouldRegisterProtocolWithAppArg()) {
- const appArg = process.argv[1] ? path.resolve(process.argv[1]) : path.resolve(".");
- result = app.setAsDefaultProtocolClient(protocol, process.execPath, [appArg]);
+ if (appArgs.length > 0) {
+ result = app.setAsDefaultProtocolClient(protocol, process.execPath, appArgs);
} else {
result = app.setAsDefaultProtocolClient(protocol);
}
@@ -226,11 +234,18 @@ function registerOpenWhisprProtocol() {
return result;
}
-// setAsDefaultProtocolClient returns a false negative on KDE/Wayland, so on Linux
-// fall back to probing the system MIME database for an actual handler. This keeps
-// OAuth enabled where the callback can resolve (deb/rpm/flatpak/AUR) and correctly
-// gated where it can't (AppImage/tar.gz with no scheme registration).
-const protocolRegistered = registerOpenWhisprProtocol() || isOAuthSchemeRegistered();
+// On Linux, setAsDefaultProtocolClient can only name open-whispr.desktop, which
+// AppImage and tar.gz installs don't have, so those (and development) register
+// their own handler entry first and skip it. Otherwise it runs as before, and
+// since it returns a false negative on KDE/Wayland, fall back to probing the
+// system MIME database for an actual handler. This keeps OAuth enabled where the
+// callback can resolve and correctly gated where it can't.
+const linuxSchemeHandler =
+ process.platform === "linux"
+ ? registerLinuxUrlSchemeHandler(OAUTH_PROTOCOL, getProtocolAppArgs())
+ : null;
+const protocolRegistered =
+ linuxSchemeHandler?.registered || registerOpenWhisprProtocol() || isOAuthSchemeRegistered();
if (!protocolRegistered) {
console.warn(`[Auth] Failed to register ${OAUTH_PROTOCOL}:// protocol handler`);
}
@@ -425,6 +440,14 @@ function initializeCoreManagers() {
debugLogger = require("./src/helpers/debugLogger");
debugLogger.ensureFileLogging();
+ // Registration runs before app ready, when the logger cannot write its file yet.
+ if (linuxSchemeHandler?.reason) {
+ debugLogger.warn("Could not register the Linux URL scheme handler entry", {
+ protocol: OAUTH_PROTOCOL,
+ reason: linuxSchemeHandler.reason,
+ protocolRegistered,
+ });
+ }
environmentManager = new EnvironmentManager();
const uiLanguage = environmentManager.getUiLanguage(app.getLocale());
diff --git a/src/helpers/linuxAutostart.js b/src/helpers/linuxAutostart.js
index 93a084f22..5173d3dc8 100644
--- a/src/helpers/linuxAutostart.js
+++ b/src/helpers/linuxAutostart.js
@@ -209,6 +209,7 @@ function syncAutostartEntry() {
module.exports = {
getDesktopFilePath,
resolveExecutablePath,
+ quoteExecPath,
buildDesktopFileContents,
isAutostartEnabled,
setAutostartEnabled,
diff --git a/src/helpers/linuxUrlSchemeHandler.js b/src/helpers/linuxUrlSchemeHandler.js
new file mode 100644
index 000000000..70ed21e01
--- /dev/null
+++ b/src/helpers/linuxUrlSchemeHandler.js
@@ -0,0 +1,107 @@
+const fs = require("fs");
+const path = require("path");
+const os = require("os");
+const { execFileSync } = require("child_process");
+const { quoteExecPath, resolveExecutablePath } = require("./linuxAutostart");
+
+const XDG_TOOL_TIMEOUT_MS = 3000;
+const PACKAGED_DESKTOP_FILE = "open-whispr.desktop";
+
+// Characters the Desktop Entry spec says must be quoted in an Exec argument.
+const EXEC_RESERVED_CHARACTERS = /[\s"'\\><~|&;$*?#()`]/;
+
+// Quotes only when the spec requires it: xdg-mime default reads the program as
+// the first space-separated word of Exec, quotes included, and newer releases
+// refuse an entry whose program is not executable (xdg-utils #253).
+function formatExecArg(arg) {
+ const escaped = arg.replace(/%/g, "%%");
+ return EXEC_RESERVED_CHARACTERS.test(escaped) ? quoteExecPath(escaped) : escaped;
+}
+
+// NoDisplay keeps it out of app menus, where a deb/rpm or the AppImage's own
+// entry already appears; it exists only to receive the sign-in callback.
+function buildHandlerEntry(protocol, launchCommand) {
+ return [
+ "[Desktop Entry]",
+ "Type=Application",
+ "Name=OpenWhispr",
+ `Exec=${[...launchCommand.map(formatExecArg), "%U"].join(" ")}`,
+ "Terminal=false",
+ "NoDisplay=true",
+ `MimeType=x-scheme-handler/${protocol};`,
+ "",
+ ].join("\n");
+}
+
+function runXdgTool(command, args) {
+ return execFileSync(command, args, { encoding: "utf8", timeout: XDG_TOOL_TIMEOUT_MS }).trim();
+}
+
+// update-desktop-database only refreshes the "can open" cache that some desktops
+// read; the default set below does not depend on it, so it is optional.
+function refreshDesktopDatabase(applicationsDir) {
+ try {
+ runXdgTool("update-desktop-database", [applicationsDir]);
+ } catch {
+ // Not installed; nothing to refresh.
+ }
+}
+
+// A deb/rpm entry declares the scheme itself, but an AppImage or tar.gz run on
+// the same machine may have made its own entry the default. Point it back here
+// with xdg-mime: in xdg-utils' generic mode, xdg-settings reverts to the previous
+// default when the app is not also the text/html browser.
+function reclaimFromOwnHandler(fileName, mimeType) {
+ try {
+ if (runXdgTool("xdg-mime", ["query", "default", mimeType]) === fileName) {
+ runXdgTool("xdg-mime", ["default", PACKAGED_DESKTOP_FILE, mimeType]);
+ }
+ } catch {
+ // xdg-mime unavailable; registerOpenWhisprProtocol reports the outcome.
+ }
+}
+
+// Only AppImage and unpacked runs (tar.gz, development) lack a desktop entry for
+// the scheme, so only they write one. Flatpak and Nix install their own entry
+// from a sandbox or read-only store. Named after the scheme, not
+// open-whispr.desktop: a user entry with the packaged name would shadow a
+// deb/rpm install's entry, and staging/dev keep their own.
+function registerLinuxUrlSchemeHandler(protocol, appArgs) {
+ const fileName = `${protocol}-url-handler.desktop`;
+ const mimeType = `x-scheme-handler/${protocol}`;
+ if (process.env.FLATPAK_ID || process.execPath.startsWith("/nix/store/")) {
+ return { registered: false };
+ }
+ // electron-builder's package-type marker: the official v1.10.2 deb carries it,
+ // its AppImage and tar.gz do not. electron-updater reads it the same way.
+ if (process.resourcesPath && fs.existsSync(path.join(process.resourcesPath, "package-type"))) {
+ reclaimFromOwnHandler(fileName, mimeType);
+ return { registered: false };
+ }
+
+ try {
+ const dataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share");
+ const applicationsDir = path.join(dataHome, "applications");
+ const filePath = path.join(applicationsDir, fileName);
+ // Rewriting on any change also re-points the entry after the AppImage moves.
+ const contents = buildHandlerEntry(protocol, [resolveExecutablePath(), ...appArgs]);
+ const current = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : null;
+ if (current !== contents) {
+ fs.mkdirSync(applicationsDir, { recursive: true });
+ fs.writeFileSync(filePath, contents, { mode: 0o644 });
+ refreshDesktopDatabase(applicationsDir);
+ }
+
+ if (runXdgTool("xdg-mime", ["query", "default", mimeType]) === fileName) {
+ return { registered: true };
+ }
+ runXdgTool("xdg-mime", ["default", fileName, mimeType]);
+ const handler = runXdgTool("xdg-mime", ["query", "default", mimeType]);
+ if (handler === fileName) return { registered: true };
+ return { registered: false, reason: `default stayed ${handler || "unset"}` };
+ } catch (error) {
+ return { registered: false, reason: error.message };
+ }
+}
+
+module.exports = { registerLinuxUrlSchemeHandler };
diff --git a/test/helpers/linuxUrlSchemeHandler.test.js b/test/helpers/linuxUrlSchemeHandler.test.js
new file mode 100644
index 000000000..d7bbd8cad
--- /dev/null
+++ b/test/helpers/linuxUrlSchemeHandler.test.js
@@ -0,0 +1,309 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const helperPath = require.resolve("../../src/helpers/linuxUrlSchemeHandler");
+const originalLoad = Module._load;
+
+const MANAGED_ENV = ["XDG_DATA_HOME", "APPIMAGE", "FLATPAK_ID"];
+const HANDLER_FILE = "openwhispr-url-handler.desktop";
+
+// Assigning undefined to process.env coerces to the string "undefined".
+function setEnv(name, value) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+}
+
+function setProcessPath(name, value) {
+ Object.defineProperty(process, name, { value, configurable: true, writable: true });
+}
+
+// Every test gets a private XDG data home, a packaged-looking execPath and a
+// resources dir with no deb/rpm marker, so each case states only what differs.
+function withInstall(fn) {
+ return async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-url-handler-test-"));
+ const saved = Object.fromEntries(MANAGED_ENV.map((name) => [name, process.env[name]]));
+ const savedExecPath = process.execPath;
+ const savedResourcesPath = process.resourcesPath;
+ MANAGED_ENV.forEach((name) => setEnv(name, undefined));
+ process.env.XDG_DATA_HOME = path.join(root, "data");
+ const resourcesPath = path.join(root, "install", "resources");
+ fs.mkdirSync(resourcesPath, { recursive: true });
+ setProcessPath("execPath", path.join(root, "install", "open-whispr-app"));
+ setProcessPath("resourcesPath", resourcesPath);
+ try {
+ await fn({ root, resourcesPath, applicationsDir: path.join(root, "data", "applications") });
+ } finally {
+ MANAGED_ENV.forEach((name) => setEnv(name, saved[name]));
+ setProcessPath("execPath", savedExecPath);
+ setProcessPath("resourcesPath", savedResourcesPath);
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ };
+}
+
+// Stands in for xdg-utils: it keeps the scheme's default handler, so a query
+// answers whatever the last `xdg-mime default` set.
+function createXdg({ defaultHandler = "", missing = [], ignoresDefault = false } = {}) {
+ const xdg = { defaultHandler };
+ xdg.execFileSync = (command, args) => {
+ if (missing.includes(command)) {
+ throw Object.assign(new Error(`spawn ${command} ENOENT`), { code: "ENOENT" });
+ }
+ if (command === "xdg-mime" && args[0] === "query") return `${xdg.defaultHandler}\n`;
+ if (command === "xdg-mime" && args[0] === "default" && !ignoresDefault) {
+ xdg.defaultHandler = args[1];
+ }
+ return "";
+ };
+ return xdg;
+}
+
+function loadHelper(xdg) {
+ delete require.cache[helperPath];
+ Module._load = function loadWithStubs(request, parent, isMain) {
+ if (request === "child_process") return { execFileSync: xdg.execFileSync };
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ try {
+ return require(helperPath);
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+const readHandler = (applicationsDir) =>
+ fs.readFileSync(path.join(applicationsDir, HANDLER_FILE), "utf8");
+
+const execLine = (applicationsDir) => readHandler(applicationsDir).match(/^Exec=(.*)$/m)[1];
+
+test(
+ "the handler entry is hidden and declares only the scheme",
+ withInstall(async ({ applicationsDir }) => {
+ const { registerLinuxUrlSchemeHandler } = loadHelper(createXdg());
+ process.env.APPIMAGE = "/home/user/Apps/OpenWhispr.AppImage";
+
+ registerLinuxUrlSchemeHandler("openwhispr", []);
+
+ assert.equal(
+ readHandler(applicationsDir),
+ [
+ "[Desktop Entry]",
+ "Type=Application",
+ "Name=OpenWhispr",
+ "Exec=/home/user/Apps/OpenWhispr.AppImage %U",
+ "Terminal=false",
+ "NoDisplay=true",
+ "MimeType=x-scheme-handler/openwhispr;",
+ "",
+ ].join("\n")
+ );
+ })
+);
+
+// Newer xdg-mime takes the first space-separated word of Exec as the program,
+// quotes included, and refuses the entry if it is not executable. So a plain
+// path stays bare and only a path the spec says must be quoted gets quotes.
+test(
+ "Exec quotes only arguments that need it and escapes percent signs",
+ withInstall(async ({ applicationsDir }) => {
+ const { registerLinuxUrlSchemeHandler } = loadHelper(createXdg());
+ const cases = [
+ ["/home/u/My Apps/OpenWhispr.AppImage", '"/home/u/My Apps/OpenWhispr.AppImage" %U'],
+ ["/home/u/100%/OpenWhispr", "/home/u/100%%/OpenWhispr %U"],
+ ['/home/u/"$HOME"/x', '"/home/u/\\"\\$HOME\\"/x" %U'],
+ ];
+
+ for (const [appImage, expected] of cases) {
+ process.env.APPIMAGE = appImage;
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+ assert.equal(execLine(applicationsDir), expected);
+ }
+ })
+);
+
+test(
+ "Flatpak and Nix installs are left to their own desktop entry",
+ withInstall(async ({ applicationsDir }) => {
+ const xdg = createXdg();
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+
+ process.env.FLATPAK_ID = "com.gizmolabs.openwhispr";
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: false });
+ setEnv("FLATPAK_ID", undefined);
+
+ // The Nix package wraps the AppImage, so APPIMAGE may be set too.
+ process.env.APPIMAGE = "/nix/store/abc-openwhispr/OpenWhispr.AppImage";
+ setProcessPath("execPath", "/nix/store/abc-openwhispr-extracted/open-whispr-app");
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: false });
+
+ assert.equal(xdg.defaultHandler, "");
+ assert.equal(fs.existsSync(applicationsDir), false);
+ })
+);
+
+test(
+ "an AppImage writes its handler at the stable AppImage path and makes it the default",
+ withInstall(async ({ applicationsDir }) => {
+ const xdg = createXdg({ defaultHandler: "open-whispr.desktop" });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ process.env.APPIMAGE = "/home/user/Applications/OpenWhispr.AppImage";
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+
+ assert.equal(execLine(applicationsDir), `${process.env.APPIMAGE} %U`);
+ assert.equal(xdg.defaultHandler, HANDLER_FILE);
+ })
+);
+
+test(
+ "a tar.gz points its handler at the launcher wrapper beside the binary",
+ withInstall(async ({ root, applicationsDir }) => {
+ const { registerLinuxUrlSchemeHandler } = loadHelper(createXdg());
+ fs.writeFileSync(path.join(root, "install", "open-whispr"), "#!/bin/bash\n");
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+
+ const wrapper = path.join(root, "install", "open-whispr");
+ assert.equal(execLine(applicationsDir), `${wrapper} %U`);
+ })
+);
+
+test(
+ "development and staging get their own handler for their own scheme",
+ withInstall(async ({ applicationsDir }) => {
+ const xdg = createXdg();
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ setProcessPath("execPath", "/repo/node_modules/electron/dist/electron");
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr-staging", ["/repo"]), {
+ registered: true,
+ });
+
+ const entry = fs.readFileSync(
+ path.join(applicationsDir, "openwhispr-staging-url-handler.desktop"),
+ "utf8"
+ );
+ assert.match(entry, /^Exec=\/repo\/node_modules\/electron\/dist\/electron \/repo %U$/m);
+ assert.match(entry, /^MimeType=x-scheme-handler\/openwhispr-staging;$/m);
+ assert.equal(xdg.defaultHandler, "openwhispr-staging-url-handler.desktop");
+ })
+);
+
+test(
+ "a second launch keeps the same entry and default",
+ withInstall(async ({ applicationsDir }) => {
+ const xdg = createXdg();
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ process.env.APPIMAGE = "/home/user/Applications/OpenWhispr.AppImage";
+ registerLinuxUrlSchemeHandler("openwhispr", []);
+ const firstEntry = readHandler(applicationsDir);
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+
+ assert.equal(readHandler(applicationsDir), firstEntry);
+ assert.equal(xdg.defaultHandler, HANDLER_FILE);
+ })
+);
+
+test(
+ "moving the AppImage re-points the handler",
+ withInstall(async ({ applicationsDir }) => {
+ const xdg = createXdg();
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ process.env.APPIMAGE = "/home/user/Downloads/OpenWhispr.AppImage";
+ registerLinuxUrlSchemeHandler("openwhispr", []);
+
+ process.env.APPIMAGE = "/home/user/Applications/OpenWhispr.AppImage";
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+
+ assert.equal(execLine(applicationsDir), `${process.env.APPIMAGE} %U`);
+ assert.equal(xdg.defaultHandler, HANDLER_FILE);
+ })
+);
+
+test(
+ "a deb or rpm install writes no entry and leaves another default alone",
+ withInstall(async ({ resourcesPath, applicationsDir }) => {
+ const xdg = createXdg({ defaultHandler: "other.desktop" });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ fs.writeFileSync(path.join(resourcesPath, "package-type"), "rpm");
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: false });
+
+ assert.equal(xdg.defaultHandler, "other.desktop");
+ assert.equal(fs.existsSync(applicationsDir), false);
+ })
+);
+
+// In xdg-utils' generic mode, xdg-settings would revert to the AppImage's entry,
+// which stops working once the AppImage is deleted.
+test(
+ "a deb or rpm install takes the default back from an AppImage's entry",
+ withInstall(async ({ resourcesPath }) => {
+ const xdg = createXdg({ defaultHandler: HANDLER_FILE });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ fs.writeFileSync(path.join(resourcesPath, "package-type"), "deb");
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: false });
+
+ assert.equal(xdg.defaultHandler, "open-whispr.desktop");
+ })
+);
+
+test(
+ "a missing update-desktop-database does not stop registration",
+ withInstall(async () => {
+ const xdg = createXdg({ missing: ["update-desktop-database"] });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), { registered: true });
+ assert.equal(xdg.defaultHandler, HANDLER_FILE);
+ })
+);
+
+test(
+ "without xdg-mime it reports not registered with the reason instead of throwing",
+ withInstall(async () => {
+ const xdg = createXdg({ missing: ["xdg-mime"] });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+
+ const result = registerLinuxUrlSchemeHandler("openwhispr", []);
+
+ assert.equal(result.registered, false);
+ assert.match(result.reason, /ENOENT/);
+ })
+);
+
+test(
+ "an unwritable data directory reports not registered with the reason instead of throwing",
+ withInstall(async ({ root }) => {
+ const xdg = createXdg();
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+ // A file where the directory should be fails the same way a read-only home does.
+ fs.writeFileSync(path.join(root, "data"), "");
+
+ const result = registerLinuxUrlSchemeHandler("openwhispr", []);
+
+ assert.equal(result.registered, false);
+ assert.ok(result.reason);
+ assert.equal(xdg.defaultHandler, "");
+ })
+);
+
+test(
+ "a default that will not stick is reported as not registered",
+ withInstall(async () => {
+ const xdg = createXdg({ defaultHandler: "other.desktop", ignoresDefault: true });
+ const { registerLinuxUrlSchemeHandler } = loadHelper(xdg);
+
+ assert.deepEqual(registerLinuxUrlSchemeHandler("openwhispr", []), {
+ registered: false,
+ reason: "default stayed other.desktop",
+ });
+ })
+);