A desktop coding agent with free access to frontier models.
TypeScript
fix(desktop): sign-in on Linux without a usable keyring
ogsamrat2dc1e4b2d81f
diff --git a/README.md b/README.mdindex bf274da9..551ee1cb 100644--- a/README.md+++ b/README.md@@ -31,6 +31,7 @@ Builds are not notarized (macOS) or code-signed (Windows) yet, so the operating| macOS keychain | When the app asks to use "omnirush.ai Safe Storage", enter your Mac login password and choose **Always Allow**. That item only holds the key that encrypts your omnirush.ai sign-in on this Mac; macOS asks again after the app binary changes. || Windows | On the SmartScreen dialog choose **More info > Run anyway**. If setup reports "Extract: error writing to file", the download is incomplete or blocked: download it again, compare its hash with `SHA256SUMS.txt`, free some disk space, and retry. || Linux | Prefer the `.deb` on Debian and Ubuntu. For the AppImage or tar.gz, install the runtime first: `sudo apt install libgtk-3-0 libnss3 libatk-bridge2.0-0 libasound2` (on Ubuntu 24.04 use `libasound2t64`), then `chmod +x` the AppImage or unpack the tar.gz. An error about `libatk-1.0.so.0` means those packages are missing. |+| Linux keyring | Optional. With a keyring the app encrypts your sign-in with it; without one (common on Hyprland, sway, i3 and other window managers) sign-in still works, and **Settings** notes that the sign-in is kept in a private file (owner-only permissions) in the app's data folder, unencrypted. To use a keyring, run a Secret Service provider in your session, such as gnome-keyring (`sudo pacman -S gnome-keyring libsecret` on Arch, then start it with your session or `gnome-keyring-daemon --start --components=secrets`) or KeePassXC with **Secret Service Integration** enabled, or KWallet on KDE. The app finds it on the next launch and moves the sign-in into it. To pick a store yourself, start the app with `--password-store=gnome-libsecret`, `kwallet5` or `kwallet6`. |## Sign indiff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex f782147b..ac3f5ed1 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -252,10 +252,17 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {: "omnirush.ai models are ready on this Mac.": account.gatewayConfigured? account.reauthorizationRequired- ? "Your session expired. Sign in again to continue."+ ? account.credentialStorage === "file"+ ? "Your system keyring is not available right now. Sign in again to continue."+ : "Your session expired. Sign in again to continue.": "Sign in in your browser, then return here.": "The omnirush.ai account service has not been configured for this build.")}</div>+ {account.connected && account.credentialStorage === "file" ? (+ <div className="mt-0.5 text-[11px] text-dls-secondary" data-testid="account-credential-storage">+ Signed in. Your system has no keyring, so the sign-in is kept in a private file on this computer.+ </div>+ ) : null}{account.connected && account.usage?.tokenLimit ? (<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-dls-hover" aria-label={`${account.usage.usedTokens} tokens used today`}><divdiff --git a/apps/desktop/electron/linux-password-store.mjs b/apps/desktop/electron/linux-password-store.mjsnew file mode 100644index 00000000..b8cc3091--- /dev/null+++ b/apps/desktop/electron/linux-password-store.mjs@@ -0,0 +1,130 @@+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import path from "node:path";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);++/** Upper bound on the startup D-Bus probe; it runs before `ready`. */+export const PASSWORD_STORE_PROBE_TIMEOUT_MS = 300;++const SECRET_SERVICE_NAME = "org.freedesktop.secrets";+const KWALLET6_NAME = "org.kde.kwalletd6";+const KWALLET5_NAME = "org.kde.kwalletd5";++// Desktops Chromium recognizes (base::nix::GetDesktopEnvironment), matched+// loosely so that any desktop Chromium might recognize keeps its own choice:+// those get gnome-libsecret or KWallet without help, and overriding them+// could strand secrets an existing install sealed with another backend.+const KNOWN_XDG_DESKTOPS = ["unity", "deepin", "gnome", "x-cinnamon", "cinnamon", "kde", "plasma", "pantheon", "xfce", "ukui", "lxqt", "mate"];+const KNOWN_DESKTOP_SESSIONS = ["deepin", "gnome", "mate", "kde", "plasma", "xfce", "xubuntu", "ukui", "cinnamon", "pantheon", "lxqt", "unity"];++/**+ * Whether Chromium picks the insecure basic_text store on its own: it does+ * so when it cannot name the desktop environment (Hyprland, sway, i3 and+ * other window managers), even when a keyring runs on the session bus.+ * @param {NodeJS.ProcessEnv} env+ */+export function chromiumPicksBasicText(env) {+ const current = (env.XDG_CURRENT_DESKTOP ?? "").split(":").map((value) => value.trim().toLowerCase()).filter(Boolean);+ if (current.some((value) => KNOWN_XDG_DESKTOPS.some((known) => value.includes(known)))) return false;+ const session = (env.DESKTOP_SESSION ?? "").trim().toLowerCase();+ if (session && KNOWN_DESKTOP_SESSIONS.some((known) => session.includes(known))) return false;+ return !env.GNOME_DESKTOP_SESSION_ID && !env.KDE_FULL_SESSION;+}++/**+ * Names on the session bus, or null when the bus or both probe tools are+ * unavailable. Never autolaunches a bus: without DBUS_SESSION_BUS_ADDRESS+ * only the systemd user bus socket is tried.+ * @param {{ env: NodeJS.ProcessEnv, timeoutMs: number, runCommand?: (file: string, args: string[], options: object) => Promise<{ stdout: string | Buffer }> }} options+ * @returns {Promise<Set<string> | null>}+ */+export async function listSessionBusNames({ env, timeoutMs, runCommand = execFileAsync }) {+ const runtimeBus = env.XDG_RUNTIME_DIR ? path.join(env.XDG_RUNTIME_DIR, "bus") : null;+ const address = env.DBUS_SESSION_BUS_ADDRESS?.trim()+ || (runtimeBus && existsSync(runtimeBus) ? `unix:path=${runtimeBus}` : "");+ if (!address) return null;+ const deadline = Date.now() + timeoutMs;+ /** @type {Array<[string, string[]]>} */+ const probes = [+ ["dbus-send", ["--session", "--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus.ListNames"]],+ ["busctl", ["--user", "call", "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames"]],+ ];+ for (const [file, args] of probes) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) break;+ try {+ const { stdout } = await runCommand(file, args, {+ env: { ...env, DBUS_SESSION_BUS_ADDRESS: address },+ timeout: remaining,+ killSignal: "SIGKILL",+ maxBuffer: 256 * 1024,+ });+ return new Set(String(stdout).split(/[\s"]+/).filter(Boolean));+ } catch {+ // Tool missing, bus unreachable or too slow: try the next one.+ }+ }+ return null;+}++/**+ * The --password-store value to start Chromium with on Linux, or null to+ * leave Chromium's own choice. Only overrides the case where Chromium would+ * fall back to basic_text while a Secret Service provider (gnome-keyring,+ * KeePassXC, ...) or KWallet is reachable on the session bus.+ * @param {{+ * platform?: NodeJS.Platform,+ * env?: NodeJS.ProcessEnv,+ * userChoseStore: boolean,+ * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<Set<string> | null>,+ * timeoutMs?: number,+ * }} options+ * @returns {Promise<{ store: "gnome-libsecret" | "kwallet6" | "kwallet5" | null, reason: string }>}+ */+export async function selectLinuxPasswordStore({+ platform = process.platform,+ env = process.env,+ userChoseStore,+ listBusNames = listSessionBusNames,+ timeoutMs = PASSWORD_STORE_PROBE_TIMEOUT_MS,+}) {+ if (platform !== "linux") return { store: null, reason: "not Linux" };+ if (userChoseStore) return { store: null, reason: "--password-store given" };+ if (!chromiumPicksBasicText(env)) return { store: null, reason: "Chromium default for this desktop" };+ const names = await listBusNames({ env, timeoutMs }).catch(() => null);+ if (names?.has(SECRET_SERVICE_NAME)) return { store: "gnome-libsecret", reason: `${SECRET_SERVICE_NAME} on the session bus` };+ if (names?.has(KWALLET6_NAME)) return { store: "kwallet6", reason: `${KWALLET6_NAME} on the session bus` };+ if (names?.has(KWALLET5_NAME)) return { store: "kwallet5", reason: `${KWALLET5_NAME} on the session bus` };+ return { store: null, reason: names ? "no keyring on the session bus" : "session bus not reachable" };+}++/**+ * Start Chromium with a real keyring when one is reachable. Must run before+ * `ready` and before anything touches safeStorage. Logs the outcome once.+ * @param {{+ * app: { commandLine: Pick<import("electron").CommandLine, "hasSwitch" | "appendSwitch"> },+ * platform?: NodeJS.Platform,+ * env?: NodeJS.ProcessEnv,+ * argv?: string[],+ * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<Set<string> | null>,+ * log?: (message: string) => void,+ * }} options+ */+export async function applyLinuxPasswordStore({+ app,+ platform = process.platform,+ env = process.env,+ argv = process.argv,+ listBusNames,+ log = (message) => console.log(message),+}) {+ if (platform !== "linux") return null;+ const userChoseStore = app.commandLine.hasSwitch("password-store")+ || argv.some((arg) => arg === "--password-store" || arg.startsWith("--password-store="));+ const { store, reason } = await selectLinuxPasswordStore({ platform, env, userChoseStore, listBusNames });+ if (store) app.commandLine.appendSwitch("password-store", store);+ log(`[omnirush] Linux password store: ${store ?? "unchanged"} (${reason})`);+ return store;+}diff --git a/apps/desktop/electron/linux-password-store.test.mjs b/apps/desktop/electron/linux-password-store.test.mjsnew file mode 100644index 00000000..d4542738--- /dev/null+++ b/apps/desktop/electron/linux-password-store.test.mjs@@ -0,0 +1,148 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ applyLinuxPasswordStore,+ chromiumPicksBasicText,+ listSessionBusNames,+ selectLinuxPasswordStore,+} from "./linux-password-store.mjs";++const HYPRLAND = { XDG_CURRENT_DESKTOP: "Hyprland", DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus" };++function fakeApp(argvSwitches = []) {+ const appended = [];+ return {+ appended,+ app: {+ commandLine: {+ hasSwitch: (name) => argvSwitches.includes(name),+ appendSwitch: (name, value) => { appended.push([name, value]); },+ },+ },+ };+}++function busWith(...names) {+ const calls = [];+ const listBusNames = async (options) => {+ calls.push(options);+ return new Set(["org.freedesktop.DBus", ":1.0", ...names]);+ };+ return { calls, listBusNames };+}++test("Chromium's basic_text choice is predicted only for desktops it cannot name", () => {+ for (const desktop of ["Hyprland", "sway", "i3", "niri", "river", ""]) {+ assert.equal(chromiumPicksBasicText({ XDG_CURRENT_DESKTOP: desktop }), true, desktop);+ }+ for (const env of [+ { XDG_CURRENT_DESKTOP: "GNOME" },+ { XDG_CURRENT_DESKTOP: "ubuntu:GNOME" },+ { XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" },+ { XDG_CURRENT_DESKTOP: "XFCE" },+ { XDG_CURRENT_DESKTOP: "X-Cinnamon" },+ { DESKTOP_SESSION: "plasma" },+ { DESKTOP_SESSION: "mate" },+ { KDE_FULL_SESSION: "true" },+ { GNOME_DESKTOP_SESSION_ID: "this-is-deprecated" },+ ]) {+ assert.equal(chromiumPicksBasicText(env), false, JSON.stringify(env));+ }+});++test("a Secret Service provider on the bus selects gnome-libsecret (gnome-keyring, KeePassXC)", async () => {+ const { app, appended } = fakeApp();+ const logs = [];+ const { calls, listBusNames } = busWith("org.freedesktop.secrets");+ const store = await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv: ["omnirush"], listBusNames, log: (line) => logs.push(line) });+ assert.equal(store, "gnome-libsecret");+ assert.deepEqual(appended, [["password-store", "gnome-libsecret"]]);+ assert.equal(calls.length, 1);+ assert.ok(calls[0].timeoutMs <= 300);+ assert.equal(logs.length, 1);+ assert.match(logs[0], /gnome-libsecret/);+});++test("KWallet is used when it is the only keyring on the bus", async () => {+ for (const [name, expected] of [["org.kde.kwalletd6", "kwallet6"], ["org.kde.kwalletd5", "kwallet5"]]) {+ const { app, appended } = fakeApp();+ const { listBusNames } = busWith(name);+ await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv: [], listBusNames, log: () => undefined });+ assert.deepEqual(appended, [["password-store", expected]]);+ }+});++test("no keyring on the bus leaves Chromium's choice (the private-file fallback takes over)", async () => {+ const { app, appended } = fakeApp();+ const { listBusNames } = busWith();+ assert.equal(await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv: [], listBusNames, log: () => undefined }), null);+ assert.deepEqual(appended, []);++ const unreachable = await selectLinuxPasswordStore({ platform: "linux", env: HYPRLAND, userChoseStore: false, listBusNames: async () => null });+ assert.deepEqual(unreachable, { store: null, reason: "session bus not reachable" });+ const failing = await selectLinuxPasswordStore({ platform: "linux", env: HYPRLAND, userChoseStore: false, listBusNames: async () => { throw new Error("boom"); } });+ assert.equal(failing.store, null);+});++test("the switch is not appended when the user passed --password-store", async () => {+ for (const [argv, switches] of [[["omnirush", "--password-store=basic"], []], [["omnirush"], ["password-store"]]]) {+ const { app, appended } = fakeApp(switches);+ const { calls, listBusNames } = busWith("org.freedesktop.secrets");+ assert.equal(await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv, listBusNames, log: () => undefined }), null);+ assert.deepEqual(appended, []);+ assert.equal(calls.length, 0);+ }+});++test("desktops Chromium recognizes keep its own choice without a probe", async () => {+ const { app, appended } = fakeApp();+ const { calls, listBusNames } = busWith("org.freedesktop.secrets");+ await applyLinuxPasswordStore({ app, platform: "linux", env: { XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" }, argv: [], listBusNames, log: () => undefined });+ assert.deepEqual(appended, []);+ assert.equal(calls.length, 0);+});++test("macOS and Windows never probe or change the password store", async () => {+ for (const platform of /** @type {const} */ (["darwin", "win32"])) {+ const { app, appended } = fakeApp();+ const { calls, listBusNames } = busWith("org.freedesktop.secrets");+ const logs = [];+ assert.equal(await applyLinuxPasswordStore({ app, platform, env: HYPRLAND, argv: [], listBusNames, log: (line) => logs.push(line) }), null);+ assert.deepEqual(appended, []);+ assert.equal(calls.length, 0);+ assert.deepEqual(logs, []);+ }+});++test("listSessionBusNames parses dbus-send, falls back to busctl, and never autolaunches a bus", async () => {+ const runs = [];+ const dbusSend = async (file, args, options) => {+ runs.push({ file, options });+ return { stdout: 'method return time=1 sender=org.freedesktop.DBus\n array [\n string "org.freedesktop.DBus"\n string "org.freedesktop.secrets"\n ]\n' };+ };+ const names = await listSessionBusNames({ env: HYPRLAND, timeoutMs: 300, runCommand: dbusSend });+ assert.equal(names.has("org.freedesktop.secrets"), true);+ assert.equal(runs[0].file, "dbus-send");+ assert.ok(runs[0].options.timeout <= 300);+ assert.equal(runs[0].options.env.DBUS_SESSION_BUS_ADDRESS, HYPRLAND.DBUS_SESSION_BUS_ADDRESS);++ const tried = [];+ const busctlOnly = async (file) => {+ tried.push(file);+ if (file === "dbus-send") throw Object.assign(new Error("missing"), { code: "ENOENT" });+ return { stdout: 'as 3 "org.freedesktop.DBus" ":1.4" "org.kde.kwalletd6"\n' };+ };+ const fromBusctl = await listSessionBusNames({ env: HYPRLAND, timeoutMs: 300, runCommand: busctlOnly });+ assert.deepEqual(tried, ["dbus-send", "busctl"]);+ assert.equal(fromBusctl.has("org.kde.kwalletd6"), true);++ let ran = false;+ const noBus = await listSessionBusNames({+ env: { XDG_RUNTIME_DIR: "/nonexistent-omnirush-runtime-dir" },+ timeoutMs: 300,+ runCommand: async () => { ran = true; return { stdout: "" }; },+ });+ assert.equal(noBus, null);+ assert.equal(ran, false);+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 39406d71..2074667b 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -79,6 +79,7 @@ import {} from "./brand-icon-windows.mjs";import { resetMacDockIcon } from "./brand-icon-darwin.mjs";import { createDesktopVaultKeyProvider } from "./secure-vault-key.mjs";+import { applyLinuxPasswordStore } from "./linux-password-store.mjs";import { createDesktopOmniRushAccountStore, legacyKeychainAllowed } from "./omnirush-account.mjs";import {clearOmniRushSentrySession,@@ -1016,6 +1017,11 @@ if (extraLaunchArgs) {}}}+// Linux: Chromium falls back to its insecure basic_text store when it cannot+// name the desktop (Hyprland, sway, i3, ...), even with gnome-keyring,+// KeePassXC or KWallet on the session bus. Point it at that keyring before+// `ready`; an explicit --password-store always wins. Bounded to ~300 ms.+await applyLinuxPasswordStore({ app });configureFakeMediaForTests(app, envFlagEnabled("OMNIRUSH_ELECTRON_FAKE_MEDIA"));// omnirush.ai has no hosted Den control plane. The default stays empty so no// code path contacts one automatically; a Den base URL only exists when@@ -1314,6 +1320,8 @@ function validateSkillName(raw) {const omnirushAccountStore = createDesktopOmniRushAccountStore({filePath: path.join(app.getPath("userData"), "omnirush-account.bin"),loadSafeStorage: () => require("electron").safeStorage,+ // Linux without a usable keyring only; unencrypted at rest, owner-only.+ fallbackFilePath: path.join(app.getPath("userData"), "private-credentials", "omnirush-account.json"),legacyKeychain: legacyKeychainAllowed({appIdentifier: APP_IDENTIFIER,productionAppIdentifier: TAURI_APP_IDENTIFIER,@@ -1352,6 +1360,8 @@ const runtimeManager = createRuntimeManager({: createDesktopVaultKeyProvider({filePath: path.join(app.getPath("userData"), "local-managed-mcp-vault-key.bin"),loadSafeStorage: () => require("electron").safeStorage,+ // Linux without a usable keyring only; unencrypted at rest, owner-only.+ fallbackFilePath: path.join(app.getPath("userData"), "private-credentials", "local-managed-mcp-vault-key.json"),}),omnirushGatewayCredentials: omnirushAccountStore,// Collector envelopes report environment.app_version from the desktop build, not the server package.diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex f6f1c2e8..522bf442 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -3,6 +3,14 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";import path from "node:path";import { promisify } from "node:util";+import {+ logPlaintextCredentialsOnce,+ readPlaintextCredentialFile,+ removePlaintextCredentialFile,+ usableSafeStorage,+ writePlaintextCredentialFile,+} from "./plaintext-credential-file.mjs";+const execFileAsync = promisify(execFile);/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountStatus} AccountStatus */@@ -30,6 +38,8 @@ const MAX_KEYCHAIN_DELETES = 8;* the server before this store's, while its persist is still on its way.*/const ROTATION_GRACE_MS = 250;+const PLAINTEXT_KIND = "omnirush.ai sign-in";+const PLAINTEXT_NOTE = "Unencrypted at rest: this system has no keyring. Owner-only file; signing out deletes it.";function normalizeCredential(value) {return typeof value === "string" && value.trim() ? value.trim() : null;@@ -214,8 +224,14 @@ export function createDesktopOmniRushAccountStore({sleep = (milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)),// Only the default production profile may use the legacy keychain entries (legacyKeychainAllowed).legacyKeychain = false,+ // Linux only: where the sign-in is kept, unencrypted at rest with owner-only+ // permissions, while no keyring is usable (see plaintext-credential-file.mjs).+ fallbackFilePath = null,+ log = (message) => console.warn(message),}) {let cached = null;+ const fileFallback = platform === "linux" && Boolean(fallbackFilePath);+ let keyringLossLogged = false;// The embedded broker shares this store (persist/latest/invalidate) and// rotates the same device session. Every writer is tracked so a reader,// the broker's latest() in particular, observes a settled store rather@@ -247,16 +263,39 @@ export function createDesktopOmniRushAccountStore({}async function safeStorage() {- const storage = loadSafeStorage();- if (!storage || !(await storage.isAsyncEncryptionAvailable())) return null;- if (platform === "linux" && storage.getSelectedStorageBackend() === "basic_text") return null;- return storage;+ return usableSafeStorage(loadSafeStorage, platform);+ }++ async function loadFallbackFile() {+ try {+ const contents = await readPlaintextCredentialFile(fallbackFilePath);+ return contents ? validCredentials(JSON.parse(contents)?.credentials) : null;+ } catch {+ return null;+ }}async function loadFile() {try {const storage = await safeStorage();- if (!storage) return null;+ if (!storage) {+ if (!fileFallback) return null;+ const credentials = await loadFallbackFile();+ if (credentials) logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);+ return credentials;+ }+ const unprotected = fileFallback ? await loadFallbackFile() : null;+ if (unprotected) {+ // A keyring is usable now: move the sign-in out of the private file.+ // The file is the newest copy, it is written only while no keyring+ // is usable. writeCredentials deletes it once the encrypted copy is+ // in place; if that fails the file stays and a later load retries.+ await enqueueWrite(unprotected).then(+ () => log("[omnirush] Moved the omnirush.ai sign-in from the private file into the system keyring."),+ () => undefined,+ );+ return unprotected;+ }const encrypted = await readFile(filePath);const decrypted = await storage.decryptStringAsync(encrypted);const credentials = validCredentials(JSON.parse(decrypted.result));@@ -339,15 +378,26 @@ export function createDesktopOmniRushAccountStore({async function writeCredentials(normalized) {const storage = await safeStorage();- if (!storage) throw new Error("Secure desktop credential storage is unavailable");- const encrypted = await storage.encryptStringAsync(JSON.stringify(normalized));- await mkdir(path.dirname(filePath), { recursive: true });- const temporary = `${filePath}.${process.pid}.tmp`;- await writeFile(temporary, encrypted, { mode: 0o600 });- await rename(temporary, filePath).catch(async (error) => {- await rm(temporary, { force: true }).catch(() => undefined);- throw error;- });+ if (!storage) {+ if (!fileFallback) throw new Error("Secure desktop credential storage is unavailable");+ // Unencrypted at rest, protected only by owner-only permissions: Linux+ // without a usable keyring. The next load with a keyring migrates it.+ await writePlaintextCredentialFile(+ fallbackFilePath,+ `${JSON.stringify({ note: PLAINTEXT_NOTE, credentials: normalized }, null, 2)}\n`,+ );+ logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);+ } else {+ const encrypted = await storage.encryptStringAsync(JSON.stringify(normalized));+ await mkdir(path.dirname(filePath), { recursive: true });+ const temporary = `${filePath}.${process.pid}.tmp`;+ await writeFile(temporary, encrypted, { mode: 0o600 });+ await rename(temporary, filePath).catch(async (error) => {+ await rm(temporary, { force: true }).catch(() => undefined);+ throw error;+ });+ if (fileFallback) await removePlaintextCredentialFile(fallbackFilePath);+ }await rm(signedOutPath, { force: true });cached = normalized;}@@ -520,6 +570,24 @@ export function createDesktopOmniRushAccountStore({throw new Error("Account link expired before it was approved");}+ /**+ * Whether a sign-in encrypted with a keyring is on disk while no keyring is+ * usable (the keyring was removed or is not running): the user is asked to+ * sign in again rather than shown as silently signed out.+ */+ async function keyringCopyUnreadable() {+ try {+ await readFile(filePath);+ } catch {+ return false;+ }+ if (!keyringLossLogged) {+ keyringLossLogged = true;+ log("[omnirush] The saved sign-in is encrypted with a system keyring that is not usable now; asking to sign in again.");+ }+ return true;+ }+/** @returns {Promise<AccountStatus>} */async function status() {const credentials = await load();@@ -529,13 +597,22 @@ export function createDesktopOmniRushAccountStore({// signed-out app reports the server the next sign-in will use.const gatewayUrl = credentials?.gatewayUrl ?? configured ?? null;const server = { gatewayUrl, gatewayHost: accountServerLabel(gatewayUrl) };- if (!credentials) return { connected: false, gatewayConfigured, ...server };+ // Linux without a usable keyring: the sign-in is (or will be) kept in the private file.+ const fileBacked = fileFallback && !(await safeStorage());+ const storage = fileBacked ? { credentialStorage: /** @type {const} */ ("file") } : {};+ if (!credentials) {+ if (fileBacked && await keyringCopyUnreadable()) {+ return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true };+ }+ return { connected: false, gatewayConfigured, ...server, ...storage };+ }try {const profile = await fetchProfile(credentials);return {connected: true,gatewayConfigured,...server,+ ...storage,email: profile?.email ?? null,displayName: profile?.displayName ?? null,accountStatus: profile?.status ?? null,@@ -548,6 +625,7 @@ export function createDesktopOmniRushAccountStore({connected: false,gatewayConfigured,...server,+ ...storage,reauthorizationRequired: true,email: null,displayName: null,@@ -561,6 +639,7 @@ export function createDesktopOmniRushAccountStore({connected: true,gatewayConfigured,...server,+ ...storage,email: null,displayName: null,accountStatus: null,@@ -602,6 +681,7 @@ export function createDesktopOmniRushAccountStore({await mkdir(path.dirname(signedOutPath), { recursive: true });await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });await rm(filePath, { force: true });+ if (fileFallback) await removePlaintextCredentialFile(fallbackFilePath);if (revokeRemote) await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);return outcome;} finally {diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex 064f3960..1568dc42 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdtemp, readFile, writeFile } from "node:fs/promises";+import { access, mkdtemp, readFile, stat, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import test from "node:test";@@ -748,3 +748,180 @@ test("a bundle persisted before the rotation counter loads as rotation 0 and couassert.equal((await store.status()).email, "[email protected]");assert.equal(JSON.parse(await readFile(options.filePath, "utf8")).rotation, 1);});++// Linux without a usable keyring: the sign-in falls back to an owner-only file.++const FAKE_GATEWAY_URL = "http://127.0.0.1:9/omnirush/v1";++/** A fake safeStorage reporting `backend`; "encrypts" by prefixing so tests can tell sealed bytes apart. */+function linuxStorage(backend, { available = true } = {}) {+ return {+ isAsyncEncryptionAvailable: async () => available,+ getSelectedStorageBackend: () => backend,+ encryptStringAsync: async (value) => Buffer.from(`sealed:${value}`, "utf8"),+ decryptStringAsync: async (value) => {+ const text = value.toString("utf8");+ if (!text.startsWith("sealed:")) throw new Error("not sealed by this keyring");+ return { result: text.slice("sealed:".length), shouldReEncrypt: false };+ },+ };+}++async function fallbackOptions(storage, overrides = {}) {+ const logs = [];+ const options = await storeOptions({+ loadSafeStorage: () => storage,+ fetchImpl: async (url) => {+ const pathname = new URL(url).pathname;+ if (pathname.endsWith("/device/me")) return Response.json({ email: "[email protected]", status: "active" });+ if (pathname.endsWith("/device/logout")) return new Response(null, { status: 204 });+ throw new Error(`Unexpected request ${pathname}`);+ },+ log: (message) => logs.push(message),+ ...overrides,+ });+ const fallbackFilePath = path.join(path.dirname(options.filePath), "private-credentials", "account.json");+ return { options: { ...options, fallbackFilePath }, logs };+}++async function exists(filePath) {+ return access(filePath).then(() => true, () => false);+}++const FAKE_CREDENTIALS = { gatewayUrl: FAKE_GATEWAY_URL, accessToken: "fake-access", refreshToken: "fake-refresh" };++test("Linux basic_text: sign-in lands in an owner-only private file instead of failing", async () => {+ let polls = 0;+ const { options, logs } = await fallbackOptions(linuxStorage("basic_text"), {+ fetchImpl: async (url) => {+ const pathname = new URL(url).pathname;+ if (pathname.endsWith("/device/authorize")) {+ return Response.json({ device_code: "code", user_code: "ABCD", verification_uri_complete: "https://omnirush.ai/console?code=ABCD", interval: 0, expires_in: 60 });+ }+ if (pathname.endsWith("/device/token")) {+ polls += 1;+ return Response.json({ gateway_url: FAKE_GATEWAY_URL, access_token: "fake-access", refresh_token: "fake-refresh" });+ }+ if (pathname.endsWith("/device/me")) return Response.json({ email: "[email protected]", status: "active" });+ throw new Error(`Unexpected request ${pathname}`);+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ const result = await store.authorize({ gatewayUrl: undefined, deviceName: "Test Linux", openVerification: async () => undefined });+ assert.equal(result.connected, true);+ assert.equal(polls, 1);++ assert.equal(await exists(options.filePath), false);+ const saved = JSON.parse(await readFile(options.fallbackFilePath, "utf8"));+ assert.equal(saved.credentials.refreshToken, "fake-refresh");+ assert.match(saved.note, /Unencrypted at rest/);+ if (process.platform !== "win32") {+ assert.equal((await stat(options.fallbackFilePath)).mode & 0o777, 0o600);+ assert.equal((await stat(path.dirname(options.fallbackFilePath))).mode & 0o777, 0o700);+ }+ assert.equal(logs.filter((line) => /unencrypted at rest/.test(line)).length <= 1, true);+ assert.equal(logs.some((line) => line.includes("fake-access") || line.includes("fake-refresh")), false);++ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, true);+ assert.equal(status.credentialStorage, "file");+ assert.equal(status.email, "[email protected]");+});++test("Linux without encryption at all also uses the private file", async () => {+ const { options } = await fallbackOptions(linuxStorage("gnome_libsecret", { available: false }));+ const store = createDesktopOmniRushAccountStore(options);+ await store.save(FAKE_CREDENTIALS);+ assert.equal(await exists(options.fallbackFilePath), true);+ assert.equal((await store.status()).credentialStorage, "file");+});++test("Linux with libsecret keeps the encrypted keyring path and no private file", async () => {+ const { options } = await fallbackOptions(linuxStorage("gnome_libsecret"));+ const store = createDesktopOmniRushAccountStore(options);+ await store.save(FAKE_CREDENTIALS);+ assert.match(await readFile(options.filePath, "utf8"), /^sealed:/);+ assert.equal(await exists(options.fallbackFilePath), false);+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, true);+ assert.equal("credentialStorage" in status, false);+});++test("a keyring that appears later receives the sign-in and the private file is deleted", async () => {+ const { options: plain } = await fallbackOptions(linuxStorage("basic_text"));+ await createDesktopOmniRushAccountStore(plain).save(FAKE_CREDENTIALS);+ assert.equal(await exists(plain.fallbackFilePath), true);++ const { options, logs } = await fallbackOptions(linuxStorage("gnome_libsecret"));+ Object.assign(options, { filePath: plain.filePath, fallbackFilePath: plain.fallbackFilePath });+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, true);+ assert.equal("credentialStorage" in status, false);+ assert.equal(await exists(options.fallbackFilePath), false);+ const sealed = await readFile(options.filePath, "utf8");+ assert.match(sealed, /^sealed:/);+ assert.equal(JSON.parse(sealed.slice("sealed:".length)).refreshToken, "fake-refresh");+ assert.equal(logs.some((line) => /into the system keyring/.test(line)), true);++ // The next launch reads the keyring copy.+ assert.equal((await createDesktopOmniRushAccountStore(options).load())?.refreshToken, "fake-refresh");+});++test("a keyring that disappears asks for a new sign-in instead of failing", async () => {+ const { options: sealed } = await fallbackOptions(linuxStorage("gnome_libsecret"));+ await createDesktopOmniRushAccountStore(sealed).save(FAKE_CREDENTIALS);++ const { options } = await fallbackOptions(linuxStorage("basic_text"));+ Object.assign(options, { filePath: sealed.filePath, fallbackFilePath: sealed.fallbackFilePath });+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.equal(status.credentialStorage, "file");++ // Signing in again works and lands in the private file.+ const store = createDesktopOmniRushAccountStore(options);+ await store.save({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-2" });+ assert.equal((await store.status()).connected, true);+ assert.equal(await exists(options.fallbackFilePath), true);+});++test("sign-out deletes the private file and stays signed out", async () => {+ const { options } = await fallbackOptions(linuxStorage("basic_text"));+ const store = createDesktopOmniRushAccountStore(options);+ await store.save(FAKE_CREDENTIALS);+ assert.equal(await exists(options.fallbackFilePath), true);+ assert.deepEqual(await store.clear(), { remoteRevoked: true, reason: "revoked" });+ assert.equal(await exists(options.fallbackFilePath), false);+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, undefined);+});++for (const platform of /** @type {const} */ (["darwin", "win32"])) {+ test(`${platform}: unavailable secure storage still refuses to store the sign-in, with no private file`, async () => {+ const { options } = await fallbackOptions(linuxStorage("unknown", { available: false }), { platform });+ const store = createDesktopOmniRushAccountStore(options);+ await assert.rejects(store.save(FAKE_CREDENTIALS), /Secure desktop credential storage is unavailable/);+ assert.equal(await exists(options.fallbackFilePath), false);+ const status = await store.status();+ assert.equal(status.connected, false);+ assert.equal("credentialStorage" in status, false);+ });++ test(`${platform}: available secure storage is used exactly as before`, async () => {+ const { options } = await fallbackOptions(linuxStorage(platform === "darwin" ? "keychain" : "dpapi"), { platform });+ const store = createDesktopOmniRushAccountStore(options);+ await store.save(FAKE_CREDENTIALS);+ assert.match(await readFile(options.filePath, "utf8"), /^sealed:/);+ assert.equal(await exists(options.fallbackFilePath), false);+ assert.equal("credentialStorage" in await store.status(), false);+ });+}++test("Linux basic_text without a fallback path keeps refusing (no silent plaintext)", async () => {+ const options = await storeOptions({ loadSafeStorage: () => linuxStorage("basic_text") });+ await assert.rejects(+ createDesktopOmniRushAccountStore(options).save(FAKE_CREDENTIALS),+ /Secure desktop credential storage is unavailable/,+ );+});diff --git a/apps/desktop/electron/plaintext-credential-file.mjs b/apps/desktop/electron/plaintext-credential-file.mjsnew file mode 100644index 00000000..0ad6244f--- /dev/null+++ b/apps/desktop/electron/plaintext-credential-file.mjs@@ -0,0 +1,79 @@+import { randomUUID } from "node:crypto";+import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import path from "node:path";++// Linux fallback for systems without a usable keyring (Electron's safeStorage+// reports the "basic_text" backend or no encryption at all). The secrets kept+// here are NOT encrypted at rest: they are protected only by owner-only file+// permissions (0600 file inside a 0700 folder under the app's userData), like+// an SSH key or a CLI tool's token file. The account store and the vault key+// provider use these files only on Linux, only while no keyring is reachable,+// and move their contents into safeStorage once one is.++const loggedKinds = new Set();++/**+ * Log once per process that `kind` is kept unencrypted. Never logs the secret.+ * @param {string} kind+ * @param {(message: string) => void} [log]+ */+export function logPlaintextCredentialsOnce(kind, log = console.warn) {+ if (loggedKinds.has(kind)) return;+ loggedKinds.add(kind);+ log(`[omnirush] No system keyring is available: the ${kind} is kept unencrypted at rest in an owner-only (0600) file in the app data folder.`);+}++/**+ * Usable safeStorage, or null. Linux's "basic_text" backend encrypts with a+ * constant key, so it counts as unavailable.+ * @param {() => import("electron").SafeStorage | null | undefined} loadSafeStorage+ * @param {NodeJS.Platform} platform+ */+export async function usableSafeStorage(loadSafeStorage, platform) {+ const storage = loadSafeStorage();+ if (!storage || !(await storage.isAsyncEncryptionAvailable())) return null;+ if (platform === "linux" && storage.getSelectedStorageBackend() === "basic_text") return null;+ return storage;+}++/**+ * The file's text, or null when it does not exist. Tightens permissions that+ * were loosened since the file was written.+ * @param {string} filePath+ */+export async function readPlaintextCredentialFile(filePath) {+ let contents;+ try {+ contents = await readFile(filePath, "utf8");+ } catch (error) {+ if (error?.code === "ENOENT") return null;+ throw error;+ }+ await chmod(filePath, 0o600).catch(() => undefined);+ return contents;+}++/**+ * Write atomically: an owner-only temporary file renamed over the target in+ * an owner-only folder, so a reader never sees a partial file.+ * @param {string} filePath+ * @param {string} contents+ */+export async function writePlaintextCredentialFile(filePath, contents) {+ const directory = path.dirname(filePath);+ await mkdir(directory, { recursive: true, mode: 0o700 });+ await chmod(directory, 0o700).catch(() => undefined);+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;+ try {+ await writeFile(temporary, contents, { mode: 0o600 });+ await chmod(temporary, 0o600).catch(() => undefined);+ await rename(temporary, filePath);+ } finally {+ await rm(temporary, { force: true }).catch(() => undefined);+ }+}++/** @param {string} filePath */+export async function removePlaintextCredentialFile(filePath) {+ await rm(filePath, { force: true });+}diff --git a/apps/desktop/electron/secure-vault-key.mjs b/apps/desktop/electron/secure-vault-key.mjsindex f3645efe..94429e3a 100644--- a/apps/desktop/electron/secure-vault-key.mjs+++ b/apps/desktop/electron/secure-vault-key.mjs@@ -2,7 +2,15 @@ import { randomBytes, randomUUID } from "node:crypto";import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";import path from "node:path";+import {+ logPlaintextCredentialsOnce,+ readPlaintextCredentialFile,+ removePlaintextCredentialFile,+ writePlaintextCredentialFile,+} from "./plaintext-credential-file.mjs";+const KEY_BYTES = 32;+const PLAINTEXT_KIND = "MCP credential vault key";/*** @param {string} filePath@@ -58,25 +66,76 @@ function decodeKey(encoded) {* filePath: string;* loadSafeStorage: () => import("electron").SafeStorage;* platform?: NodeJS.Platform;- * }} options+ * fallbackFilePath?: string | null;+ * log?: (message: string) => void;+ * }} options `fallbackFilePath`: Linux only, where the key is kept,+ * unencrypted at rest with owner-only permissions, while no keyring is usable+ * (see plaintext-credential-file.mjs).*/export function createDesktopVaultKeyProvider({filePath,loadSafeStorage,platform = process.platform,+ fallbackFilePath = null,+ log = (message) => console.warn(message),}) {/** @type {Promise<Buffer> | null} */let pending = null;+ const fileFallback = platform === "linux" && Boolean(fallbackFilePath);++ /** The key kept in the private file, or null when there is none or it is invalid. */+ async function readUnprotectedKey() {+ try {+ const contents = await readPlaintextCredentialFile(fallbackFilePath);+ return contents ? decodeKey(JSON.parse(contents).key) : null;+ } catch {+ return null;+ }+ }++ /**+ * Linux without a usable keyring: the key lives in an owner-only file,+ * unencrypted at rest. A key sealed by a keyring that is gone cannot be+ * read, so a fresh key is minted and the vault recovers as it does after a+ * keyring change; the sealed blob is left for the keyring's return.+ */+ async function loadUnprotectedKey() {+ logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);+ const stored = await readUnprotectedKey();+ if (stored) return stored;+ const key = randomBytes(KEY_BYTES);+ await writePlaintextCredentialFile(+ fallbackFilePath,+ `${JSON.stringify({ note: "Unencrypted at rest: this system has no keyring. Owner-only file.", key: key.toString("base64") }, null, 2)}\n`,+ );+ return key;+ }async function loadKey() {const safeStorage = loadSafeStorage();- if (!safeStorage || !(await safeStorage.isAsyncEncryptionAvailable())) {+ const encryptionAvailable = Boolean(safeStorage) && await safeStorage.isAsyncEncryptionAvailable();+ const basicText = encryptionAvailable && platform === "linux" && safeStorage.getSelectedStorageBackend() === "basic_text";+ if (fileFallback && (!encryptionAvailable || basicText)) return loadUnprotectedKey();+ if (!encryptionAvailable) {throw new Error("Operating-system secure storage is unavailable for OmniRush.ai-managed OAuth.");}- if (platform === "linux" && safeStorage.getSelectedStorageBackend() === "basic_text") {+ if (basicText) {throw new Error("A secure Linux password store is required for OmniRush.ai-managed OAuth.");}+ const unprotected = fileFallback ? await readUnprotectedKey() : null;+ if (unprotected) {+ // A keyring is usable now: seal the key the vault uses with it, keep+ // any older sealed blob as a backup, then delete the private file.+ await rename(filePath, `${filePath}.omnirush-backup-${backupTimestamp(new Date())}`).catch((error) => {+ if (error?.code !== "ENOENT") throw error;+ });+ await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(unprotected.toString("base64")));+ await removePlaintextCredentialFile(fallbackFilePath);+ log("[omnirush] Moved the MCP credential vault key from the private file into the system keyring.");+ return unprotected;+ }+/** @type {Buffer | undefined} */let encrypted;try {diff --git a/apps/desktop/electron/secure-vault-key.test.mjs b/apps/desktop/electron/secure-vault-key.test.mjsindex 9f369137..f4d1c995 100644--- a/apps/desktop/electron/secure-vault-key.test.mjs+++ b/apps/desktop/electron/secure-vault-key.test.mjs@@ -1,6 +1,6 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { mkdtemp, readdir, readFile, rm, stat } from "node:fs/promises";+import { access, mkdtemp, readdir, readFile, rm, stat } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -91,7 +91,7 @@ describe("desktop managed MCP vault key", () => {}});- it("rejects Electron's insecure Linux basic-text backend", async () => {+ it("rejects Electron's insecure Linux basic-text backend (no fallback path)", async () => {const filePath = path.join(os.tmpdir(), "unused-omnirush-vault-key.bin");const provider = createDesktopVaultKeyProvider({filePath,@@ -111,4 +111,94 @@ describe("desktop managed MCP vault key", () => {await assert.rejects(provider(), /secure storage is unavailable/);assert.deepEqual(await backupSiblings(filePath), []);});++ describe("Linux without a usable keyring", () => {+ /** @param {string} root */+ function paths(root) {+ return { filePath: path.join(root, "vault-key.bin"), fallbackFilePath: path.join(root, "private-credentials", "vault-key.json") };+ }+ /** @param {string} filePath */+ const exists = (filePath) => access(filePath).then(() => true, () => false);+ const basicText = () => fakeSafeStorage({ getSelectedStorageBackend: () => "basic_text" });+ const quiet = () => undefined;++ it("keeps the key in an owner-only private file and restores it", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));+ const { filePath, fallbackFilePath } = paths(root);+ try {+ const options = { filePath, fallbackFilePath, loadSafeStorage: basicText, platform: /** @type {const} */ ("linux"), log: quiet };+ const key = await createDesktopVaultKeyProvider(options)();+ assert.equal(key.byteLength, 32);+ assert.equal(await exists(filePath), false);+ assert.equal(JSON.parse(await readFile(fallbackFilePath, "utf8")).key, key.toString("base64"));+ if (process.platform !== "win32") {+ assert.equal((await stat(fallbackFilePath)).mode & 0o777, 0o600);+ assert.equal((await stat(path.dirname(fallbackFilePath))).mode & 0o777, 0o700);+ }+ assert.deepEqual(await createDesktopVaultKeyProvider(options)(), key);++ const unavailable = { ...options, loadSafeStorage: () => fakeSafeStorage({ isAsyncEncryptionAvailable: async () => false }) };+ assert.deepEqual(await createDesktopVaultKeyProvider(unavailable)(), key);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("moves the key into a keyring that appears later and deletes the private file", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));+ const { filePath, fallbackFilePath } = paths(root);+ try {+ const base = { filePath, fallbackFilePath, platform: /** @type {const} */ ("linux"), log: quiet };+ const key = await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: basicText })();+ const keyring = fakeSafeStorage();+ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => keyring })(), key);+ assert.equal(await exists(fallbackFilePath), false);+ assert.equal((await readFile(filePath)).includes(key.toString("base64")), false);+ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => keyring })(), key);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("mints a file key when the keyring that sealed the old one is gone, leaving the sealed blob", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));+ const { filePath, fallbackFilePath } = paths(root);+ try {+ const base = { filePath, fallbackFilePath, platform: /** @type {const} */ ("linux"), log: quiet };+ const sealedKey = await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => fakeSafeStorage() })();+ const sealedBlob = await readFile(filePath);+ const fileKey = await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: basicText })();+ assert.notDeepEqual(fileKey, sealedKey);+ assert.deepEqual(await readFile(filePath), sealedBlob);++ // When the keyring returns, the key the vault now uses wins; the old blob is kept as a backup.+ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => fakeSafeStorage() })(), fileKey);+ assert.equal((await backupSiblings(filePath)).length, 1);+ assert.equal(await exists(fallbackFilePath), false);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ for (const platform of /** @type {const} */ (["darwin", "win32"])) {+ it(`${platform}: unavailable secure storage still fails closed and writes no private file`, async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));+ const { filePath, fallbackFilePath } = paths(root);+ try {+ const provider = createDesktopVaultKeyProvider({+ filePath,+ fallbackFilePath,+ platform,+ log: quiet,+ loadSafeStorage: () => fakeSafeStorage({ isAsyncEncryptionAvailable: async () => false }),+ });+ await assert.rejects(provider(), /secure storage is unavailable/);+ assert.equal(await exists(fallbackFilePath), false);+ assert.equal(await exists(filePath), false);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+ }+ });});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex a4bd10b0..836997a5 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex ef349a14..cd1ce3df 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -144,6 +144,11 @@ export type OmniRushAccountStatus = {gatewayUrl?: string | null;/** Display label for the account server, e.g. "omnirush.ai" or "localhost:8090 (local API)". */gatewayHost?: string | null;+ /**+ * "file": Linux without a usable keyring, so the sign-in is kept in an+ * owner-only file on this computer. Absent when a keyring protects it.+ */+ credentialStorage?: "file";};export type EngineDoctorResult = {diff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILDindex cd7bdde1..3ff5d96a 100644--- a/packaging/aur/PKGBUILD+++ b/packaging/aur/PKGBUILD@@ -10,6 +10,8 @@ arch=('x86_64' 'aarch64')url="https://github.com/omnirush-ai/omnirush-gui"license=('MIT')depends=('gtk3' 'nss' 'alsa-lib' 'libxss' 'libxtst' 'xdg-utils' 'at-spi2-core' 'libdrm' 'libxkbcommon' 'mesa' 'dbus' 'hicolor-icon-theme')+optdepends=('libsecret: encrypt the sign-in with a Secret Service keyring'+ 'gnome-keyring: Secret Service keyring for window-manager sessions (Hyprland, sway, i3)')options=(!strip)# Architecture-specific sources and checksums