A desktop coding agent with free access to frontier models.
TypeScript
fix(desktop): keep the Linux keyring choice stable across launches
ogsamratb6e1fb5298c8
diff --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 ac3f5ed1..3e7de751 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,7 +252,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {: "omnirush.ai models are ready on this Mac.": account.gatewayConfigured? account.reauthorizationRequired- ? account.credentialStorage === "file"+ ? account.keyringUnavailable? "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."diff --git a/apps/desktop/electron/linux-password-store.mjs b/apps/desktop/electron/linux-password-store.mjsindex b8cc3091..a6ab5aa5 100644--- a/apps/desktop/electron/linux-password-store.mjs+++ b/apps/desktop/electron/linux-password-store.mjs@@ -1,5 +1,7 @@import { execFile } from "node:child_process";-import { existsSync } from "node:fs";+import { randomUUID } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";import path from "node:path";import { promisify } from "node:util";@@ -8,16 +10,32 @@ const execFileAsync = promisify(execFile);/** Upper bound on the startup D-Bus probe; it runs before `ready`. */export const PASSWORD_STORE_PROBE_TIMEOUT_MS = 300;+/** Where the store that sealed each keyring-encrypted file is recorded, in userData. */+export const PASSWORD_STORE_RECORD_FILE = "linux-password-store.json";+/** Keyring-sealed files in userData whose store is kept sticky, most important first. */+export const KEYRING_SEALED_FILES = ["omnirush-account.bin", "local-managed-mcp-vault-key.bin"];+const SECRET_SERVICE_NAME = "org.freedesktop.secrets";const KWALLET6_NAME = "org.kde.kwalletd6";const KWALLET5_NAME = "org.kde.kwalletd5";+const KEYRING_NAMES = /** @type {const} */ ([+ [SECRET_SERVICE_NAME, "gnome-libsecret"],+ [KWALLET6_NAME, "kwallet6"],+ [KWALLET5_NAME, "kwallet5"],+]);+/** safeStorage.getSelectedStorageBackend() values and the --password-store value that selects each. */+const BACKEND_TO_SWITCH = { gnome_libsecret: "gnome-libsecret", kwallet: "kwallet", kwallet5: "kwallet5", kwallet6: "kwallet6" };+const STICKY_STORES = new Set(Object.values(BACKEND_TO_SWITCH));-// 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"];+// Mirrors Chromium's base::nix::GetDesktopEnvironment plus the backend it+// maps each desktop to (os_crypt SelectBackend): these desktops get+// gnome-libsecret or KWallet without help. XDG_CURRENT_DESKTOP entries are+// compared exactly, as Chromium does; LXQt and a MATE named only there map+// to basic_text in Chromium, so they are left out. Anything KDE-like stays+// matched loosely: overriding a KWallet desktop could strand its secrets.+const KNOWN_XDG_DESKTOPS = new Set(["unity", "deepin", "gnome", "x-cinnamon", "pantheon", "xfce", "ukui"]);+const KNOWN_DESKTOP_SESSIONS = new Set(["deepin", "gnome", "mate", "ukui", "xubuntu"]);+const KDE_LIKE = /kde|plasma/;/*** Whether Chromium picks the insecure basic_text store on its own: it does@@ -27,18 +45,25 @@ const KNOWN_DESKTOP_SESSIONS = ["deepin", "gnome", "mate", "kde", "plasma", "xfc*/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;+ if (current.some((value) => KNOWN_XDG_DESKTOPS.has(value) || KDE_LIKE.test(value))) return false;const session = (env.DESKTOP_SESSION ?? "").trim().toLowerCase();- if (session && KNOWN_DESKTOP_SESSIONS.some((known) => session.includes(known))) return false;+ if (session && (KNOWN_DESKTOP_SESSIONS.has(session) || session.includes("xfce") || KDE_LIKE.test(session))) return false;return !env.GNOME_DESKTOP_SESSION_ID && !env.KDE_FULL_SESSION;}+/** @param {string | Buffer} stdout */+function parseNames(stdout) {+ return new Set(String(stdout).split(/[\s"]+/).filter(Boolean));+}+/**- * 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.+ * Names on the session bus: those running now and those D-Bus starts on+ * demand (gnome-keyring on Arch is usually activatable, not yet running, at+ * login on a window manager; libsecret inside Chromium starts it). 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>}+ * @returns {Promise<{ running: Set<string>, activatable: 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;@@ -46,58 +71,126 @@ export async function listSessionBusNames({ env, timeoutMs, runCommand = execFil|| (runtimeBus && existsSync(runtimeBus) ? `unix:path=${runtimeBus}` : "");if (!address) return null;const deadline = Date.now() + timeoutMs;- /** @type {Array<[string, string[]]>} */+ /** @type {Array<[string, (method: 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"]],+ ["dbus-send", (method) => ["--session", "--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus", `org.freedesktop.DBus.${method}`]],+ ["busctl", (method) => ["--user", "call", "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", method]],];- for (const [file, args] of probes) {+ for (const [file, argsFor] 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.- }+ const options = {+ env: { ...env, DBUS_SESSION_BUS_ADDRESS: address },+ timeout: remaining,+ killSignal: "SIGKILL",+ maxBuffer: 256 * 1024,+ };+ // Both calls share the remaining budget and run side by side.+ const [running, activatable] = await Promise.allSettled([+ runCommand(file, argsFor("ListNames"), options),+ runCommand(file, argsFor("ListActivatableNames"), options),+ ]);+ if (running.status !== "fulfilled" && activatable.status !== "fulfilled") continue; // Tool missing, bus unreachable or too slow.+ return {+ running: running.status === "fulfilled" ? parseNames(running.value.stdout) : new Set(),+ activatable: activatable.status === "fulfilled" ? parseNames(activatable.value.stdout) : new Set(),+ };}return null;}+/**+ * The --password-store value recorded for a keyring-sealed file that still+ * exists in userData, or null. Keeps later launches on the store that sealed+ * the sign-in even when the probe misses the keyring.+ * @param {string | null | undefined} userDataPath+ * @param {{ exists?: (filePath: string) => boolean, readText?: (filePath: string) => string }} [io]+ * @returns {{ store: string, file: string } | null}+ */+export function recordedLinuxPasswordStore(userDataPath, { exists = existsSync, readText = (filePath) => readFileSync(filePath, "utf8") } = {}) {+ if (!userDataPath) return null;+ let record;+ try {+ record = JSON.parse(readText(path.join(userDataPath, PASSWORD_STORE_RECORD_FILE)))?.stores;+ } catch {+ return null;+ }+ if (!record || typeof record !== "object") return null;+ for (const file of KEYRING_SEALED_FILES) {+ const store = record[file];+ if (typeof store === "string" && STICKY_STORES.has(store) && exists(path.join(userDataPath, file))) return { store, file };+ }+ return null;+}++/**+ * Record which store sealed `fileName` (safeStorage.getSelectedStorageBackend()).+ * Linux only; basic_text and unknown backends are not recorded.+ * @param {{ userDataPath: string, fileName: string, backend: string }} options+ * @returns {Promise<boolean>} whether the record changed+ */+export async function recordLinuxPasswordStore({ userDataPath, fileName, backend }) {+ const store = BACKEND_TO_SWITCH[/** @type {keyof typeof BACKEND_TO_SWITCH} */ (backend)];+ if (!store) return false;+ const recordPath = path.join(userDataPath, PASSWORD_STORE_RECORD_FILE);+ /** @type {Record<string, string>} */+ let stores = {};+ try {+ const parsed = JSON.parse(await readFile(recordPath, "utf8"))?.stores;+ if (parsed && typeof parsed === "object") stores = parsed;+ } catch {+ // Missing or unreadable: start a new record.+ }+ if (stores[fileName] === store) return false;+ stores = { ...stores, [fileName]: store };+ await mkdir(userDataPath, { recursive: true });+ const temporary = `${recordPath}.${process.pid}.${randomUUID()}.tmp`;+ try {+ await writeFile(temporary, `${JSON.stringify({ stores }, null, 2)}\n`, { mode: 0o600 });+ await rename(temporary, recordPath);+ } finally {+ await rm(temporary, { force: true }).catch(() => undefined);+ }+ return true;+}+/*** 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.+ * leave Chromium's own choice. A store recorded for a sealed file that still+ * exists wins; otherwise only overrides the case where Chromium would fall+ * back to basic_text while a Secret Service provider (gnome-keyring,+ * KeePassXC, ...) or KWallet is running or D-Bus activatable.* @param {{* platform?: NodeJS.Platform,* env?: NodeJS.ProcessEnv,* userChoseStore: boolean,- * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<Set<string> | null>,+ * recorded?: { store: string, file: string } | null,+ * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<{ running: Set<string>, activatable: Set<string> } | null>,* timeoutMs?: number,* }} options- * @returns {Promise<{ store: "gnome-libsecret" | "kwallet6" | "kwallet5" | null, reason: string }>}+ * @returns {Promise<{ store: string | null, reason: string }>}*/export async function selectLinuxPasswordStore({platform = process.platform,env = process.env,userChoseStore,+ recorded = null,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 (recorded) return { store: recorded.store, reason: `${recorded.file} is sealed with it` };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" };+ if (!names) return { store: null, reason: "session bus not reachable" };+ // A running keyring first, then one D-Bus starts on demand.+ for (const [set, state] of /** @type {const} */ ([[names.running, "running"], [names.activatable, "activatable"]])) {+ for (const [name, store] of KEYRING_NAMES) {+ if (set?.has(name)) return { store, reason: `${name} ${state} on the session bus` };+ }+ }+ return { store: null, reason: "no keyring on the session bus" };}/**@@ -108,7 +201,9 @@ export async function selectLinuxPasswordStore({* platform?: NodeJS.Platform,* env?: NodeJS.ProcessEnv,* argv?: string[],- * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<Set<string> | null>,+ * userDataPath?: string | null,+ * readRecorded?: (userDataPath: string | null | undefined) => { store: string, file: string } | null,+ * listBusNames?: (options: { env: NodeJS.ProcessEnv, timeoutMs: number }) => Promise<{ running: Set<string>, activatable: Set<string> } | null>,* log?: (message: string) => void,* }} options*/@@ -117,13 +212,16 @@ export async function applyLinuxPasswordStore({platform = process.platform,env = process.env,argv = process.argv,+ userDataPath = null,+ readRecorded = recordedLinuxPasswordStore,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 });+ const recorded = userChoseStore ? null : readRecorded(userDataPath);+ const { store, reason } = await selectLinuxPasswordStore({ platform, env, userChoseStore, recorded, 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.mjsindex d4542738..37cb320b 100644--- a/apps/desktop/electron/linux-password-store.test.mjs+++ b/apps/desktop/electron/linux-password-store.test.mjs@@ -1,10 +1,15 @@import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";import test from "node:test";import {applyLinuxPasswordStore,chromiumPicksBasicText,listSessionBusNames,+ recordedLinuxPasswordStore,+ recordLinuxPasswordStore,selectLinuxPasswordStore,} from "./linux-password-store.mjs";@@ -24,10 +29,14 @@ function fakeApp(argvSwitches = []) {}function busWith(...names) {+ return busWithActivatable(names, []);+}++function busWithActivatable(running, activatable) {const calls = [];const listBusNames = async (options) => {calls.push(options);- return new Set(["org.freedesktop.DBus", ":1.0", ...names]);+ return { running: new Set(["org.freedesktop.DBus", ":1.0", ...running]), activatable: new Set(["org.freedesktop.DBus", ...activatable]) };};return { calls, listBusNames };}@@ -46,9 +55,14 @@ test("Chromium's basic_text choice is predicted only for desktops it cannot name{ DESKTOP_SESSION: "mate" },{ KDE_FULL_SESSION: "true" },{ GNOME_DESKTOP_SESSION_ID: "this-is-deprecated" },+ { DESKTOP_SESSION: "xfce4" },]) {assert.equal(chromiumPicksBasicText(env), false, JSON.stringify(env));}+ // Chromium maps LXQt, and MATE named only in XDG_CURRENT_DESKTOP, to basic_text.+ for (const env of [{ XDG_CURRENT_DESKTOP: "LXQt" }, { XDG_CURRENT_DESKTOP: "MATE" }, { XDG_CURRENT_DESKTOP: "Hyprland", DESKTOP_SESSION: "hyprland-gnomeish" }]) {+ assert.equal(chromiumPicksBasicText(env), true, JSON.stringify(env));+ }});test("a Secret Service provider on the bus selects gnome-libsecret (gnome-keyring, KeePassXC)", async () => {@@ -122,20 +136,30 @@ test("listSessionBusNames parses dbus-send, falls back to busctl, and never autoreturn { 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(names.running.has("org.freedesktop.secrets"), true);+ assert.equal(runs.length, 2);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);+ const busctlOnly = async (file, args) => {+ tried.push(`${file} ${args.at(-1)}`);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' };+ return args.at(-1) === "ListNames"+ ? { stdout: 'as 3 "org.freedesktop.DBus" ":1.4" "org.kde.kwalletd6"\n' }+ : { stdout: 'as 2 "org.freedesktop.DBus" "org.freedesktop.secrets"\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);+ assert.deepEqual(tried.sort(), [+ "busctl ListActivatableNames",+ "busctl ListNames",+ "dbus-send org.freedesktop.DBus.ListActivatableNames",+ "dbus-send org.freedesktop.DBus.ListNames",+ ]);+ assert.equal(fromBusctl.running.has("org.kde.kwalletd6"), true);+ assert.equal(fromBusctl.activatable.has("org.freedesktop.secrets"), true);+ assert.equal(fromBusctl.running.has("org.freedesktop.secrets"), false);let ran = false;const noBus = await listSessionBusNames({@@ -146,3 +170,87 @@ test("listSessionBusNames parses dbus-send, falls back to busctl, and never autoassert.equal(noBus, null);assert.equal(ran, false);});++test("a Secret Service that D-Bus starts on demand but is not running yet selects gnome-libsecret", async () => {+ const { app, appended } = fakeApp();+ const logs = [];+ const { listBusNames } = busWithActivatable([], ["org.freedesktop.secrets", "org.kde.kwalletd6"]);+ const store = await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv: [], listBusNames, log: (line) => logs.push(line) });+ assert.equal(store, "gnome-libsecret");+ assert.deepEqual(appended, [["password-store", "gnome-libsecret"]]);+ assert.match(logs[0], /activatable/);++ // A running keyring wins over one that is only activatable.+ const running = fakeApp();+ await applyLinuxPasswordStore({+ app: running.app, platform: "linux", env: HYPRLAND, argv: [],+ listBusNames: busWithActivatable(["org.kde.kwalletd6"], ["org.freedesktop.secrets"]).listBusNames,+ log: () => undefined,+ });+ assert.deepEqual(running.appended, [["password-store", "kwallet6"]]);+});++test("listSessionBusNames reports activatable names when ListNames fails and stays within the budget", async () => {+ const runs = [];+ const names = await listSessionBusNames({+ env: HYPRLAND,+ timeoutMs: 300,+ runCommand: async (file, args, options) => {+ runs.push({ file, method: args.at(-1), timeout: options.timeout });+ if (args.at(-1).endsWith("ListActivatableNames")) return { stdout: 'array [ string "org.freedesktop.secrets" ]' };+ throw new Error("timed out");+ },+ });+ assert.equal(names.running.size, 0);+ assert.equal(names.activatable.has("org.freedesktop.secrets"), true);+ assert.equal(runs.length, 2);+ assert.ok(runs.every((run) => run.file === "dbus-send" && run.timeout <= 300));+});++test("the store that sealed the sign-in stays chosen on a launch where the probe finds nothing", async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), "omnirush-password-store-"));+ try {+ assert.equal(await recordLinuxPasswordStore({ userDataPath: userData, fileName: "omnirush-account.bin", backend: "gnome_libsecret" }), true);+ assert.equal(await recordLinuxPasswordStore({ userDataPath: userData, fileName: "omnirush-account.bin", backend: "gnome_libsecret" }), false);+ assert.equal(await recordLinuxPasswordStore({ userDataPath: userData, fileName: "omnirush-account.bin", backend: "basic_text" }), false);+ assert.equal((await stat(path.join(userData, "linux-password-store.json"))).mode & 0o777, 0o600);+ assert.deepEqual(JSON.parse(await readFile(path.join(userData, "linux-password-store.json"), "utf8")), { stores: { "omnirush-account.bin": "gnome-libsecret" } });++ // No sealed file: the record alone does not pin the store.+ assert.equal(recordedLinuxPasswordStore(userData), null);+ await writeFile(path.join(userData, "omnirush-account.bin"), "sealed");+ assert.deepEqual(recordedLinuxPasswordStore(userData), { store: "gnome-libsecret", file: "omnirush-account.bin" });++ // The keyring is neither running nor activatable on this launch.+ const nothing = busWith();+ const { app, appended } = fakeApp();+ const logs = [];+ const store = await applyLinuxPasswordStore({ app, platform: "linux", env: HYPRLAND, argv: [], userDataPath: userData, listBusNames: nothing.listBusNames, log: (line) => logs.push(line) });+ assert.equal(store, "gnome-libsecret");+ assert.deepEqual(appended, [["password-store", "gnome-libsecret"]]);+ assert.equal(nothing.calls.length, 0);+ assert.match(logs[0], /omnirush-account\.bin is sealed with it/);++ // It also holds on a desktop Chromium names (a KDE user who signed in from sway).+ const kde = fakeApp();+ await applyLinuxPasswordStore({ app: kde.app, platform: "linux", env: { XDG_CURRENT_DESKTOP: "KDE" }, argv: [], userDataPath: userData, listBusNames: nothing.listBusNames, log: () => undefined });+ assert.deepEqual(kde.appended, [["password-store", "gnome-libsecret"]]);++ // An explicit --password-store still wins, and macOS/Windows never read the record.+ const explicit = fakeApp(["password-store"]);+ assert.equal(await applyLinuxPasswordStore({ app: explicit.app, platform: "linux", env: HYPRLAND, argv: [], userDataPath: userData, listBusNames: nothing.listBusNames, log: () => undefined }), null);+ assert.deepEqual(explicit.appended, []);+ for (const platform of /** @type {const} */ (["darwin", "win32"])) {+ const other = fakeApp();+ assert.equal(await applyLinuxPasswordStore({ app: other.app, platform, env: HYPRLAND, argv: [], userDataPath: userData, readRecorded: () => { throw new Error("read"); }, log: () => undefined }), null);+ assert.deepEqual(other.appended, []);+ }++ // Once the sealed file is gone (signed out) the probe decides again.+ await rm(path.join(userData, "omnirush-account.bin"));+ const after = fakeApp();+ assert.equal(await applyLinuxPasswordStore({ app: after.app, platform: "linux", env: HYPRLAND, argv: [], userDataPath: userData, listBusNames: nothing.listBusNames, log: () => undefined }), null);+ } finally {+ await rm(userData, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 2074667b..5b53a9f6 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -79,7 +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 { applyLinuxPasswordStore, recordLinuxPasswordStore } from "./linux-password-store.mjs";import { createDesktopOmniRushAccountStore, legacyKeychainAllowed } from "./omnirush-account.mjs";import {clearOmniRushSentrySession,@@ -1021,7 +1021,19 @@ if (extraLaunchArgs) {// 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 });+// Once a sign-in or vault key is sealed with a store, later launches keep+// that store while the sealed file exists, even if the keyring is not yet+// running (D-Bus starts it on demand).+await applyLinuxPasswordStore({ app, userDataPath: app.getPath("userData") });+/** Linux: remember which keyring backend sealed `fileName` in userData. */+function recordKeyringSealed(fileName) {+ return (backend) => recordLinuxPasswordStore({ userDataPath: app.getPath("userData"), fileName, backend }).then(+ (changed) => {+ if (changed) console.log(`[omnirush] Linux password store recorded for ${fileName}: ${backend}`);+ },+ () => undefined,+ );+}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@@ -1322,6 +1334,7 @@ const omnirushAccountStore = createDesktopOmniRushAccountStore({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"),+ onKeyringSealed: recordKeyringSealed("omnirush-account.bin"),legacyKeychain: legacyKeychainAllowed({appIdentifier: APP_IDENTIFIER,productionAppIdentifier: TAURI_APP_IDENTIFIER,@@ -1362,6 +1375,7 @@ const runtimeManager = createRuntimeManager({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"),+ onKeyringSealed: recordKeyringSealed("local-managed-mcp-vault-key.bin"),}),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 522bf442..8f36a87b 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -1,9 +1,10 @@import { execFile } from "node:child_process";-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";import { promisify } from "node:util";import {+ discardPlaintextCredentialFile,logPlaintextCredentialsOnce,readPlaintextCredentialFile,removePlaintextCredentialFile,@@ -41,6 +42,12 @@ 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 sameCredentials(left, right) {+ return left.gatewayUrl === right.gatewayUrl+ && left.accessToken === right.accessToken+ && left.refreshToken === right.refreshToken;+}+function normalizeCredential(value) {return typeof value === "string" && value.trim() ? value.trim() : null;}@@ -227,11 +234,15 @@ export function createDesktopOmniRushAccountStore({// 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,+ // Linux only: told which safeStorage backend sealed the sign-in once it is+ // written and read back, so later launches keep that --password-store.+ onKeyringSealed = null,log = (message) => console.warn(message),}) {let cached = null;const fileFallback = platform === "linux" && Boolean(fallbackFilePath);let keyringLossLogged = false;+ let sealedBackendRecorded = null;// 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@@ -275,6 +286,37 @@ export function createDesktopOmniRushAccountStore({}}+ /** Tell main which backend sealed the sign-in (once per backend per process). */+ async function noteKeyringSealed(storage) {+ if (!fileFallback || !onKeyringSealed) return;+ const backend = storage.getSelectedStorageBackend();+ if (sealedBackendRecorded === backend) return;+ try {+ await onKeyringSealed(backend);+ sealedBackendRecorded = backend;+ } catch {+ // Best effort: without the record the startup probe still decides.+ }+ }++ async function modifiedAt(file) {+ try {+ return (await stat(file)).mtimeMs;+ } catch {+ return 0;+ }+ }++ async function decryptKeyringCopy(storage) {+ try {+ const decrypted = await storage.decryptStringAsync(await readFile(filePath));+ const credentials = validCredentials(JSON.parse(decrypted.result));+ return credentials ? { credentials, shouldReEncrypt: Boolean(decrypted.shouldReEncrypt) } : null;+ } catch {+ return null;+ }+ }+async function loadFile() {try {const storage = await safeStorage();@@ -284,23 +326,27 @@ export function createDesktopOmniRushAccountStore({if (credentials) logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);return credentials;}+ const sealed = await decryptKeyringCopy(storage);const unprotected = fileFallback ? await loadFallbackFile() : null;- if (unprotected) {+ // The private file is written only while no keyring is usable, so it is+ // normally the newest copy; a readable keyring copy written after it+ // wins (the file is then a leftover whose delete failed).+ if (unprotected && !(sealed && await modifiedAt(filePath) > await modifiedAt(fallbackFilePath))) {// 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.+ // writeCredentials deletes the file only once the encrypted copy has+ // been written and read back; otherwise the file stays and keeps the+ // user signed in, 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));- if (credentials && decrypted.shouldReEncrypt) await enqueueWrite(credentials);- return credentials;+ if (!sealed) return null;+ if (unprotected) await discardPlaintextCredentialFile(fallbackFilePath, PLAINTEXT_KIND, log);+ await noteKeyringSealed(storage);+ if (sealed.shouldReEncrypt) await enqueueWrite(sealed.credentials);+ return sealed.credentials;} catch {return null;}@@ -396,7 +442,23 @@ export function createDesktopOmniRushAccountStore({await rm(temporary, { force: true }).catch(() => undefined);throw error;});- if (fileFallback) await removePlaintextCredentialFile(fallbackFilePath);+ if (fileFallback) {+ // Linux: only trust the keyring copy once it reads back. Until then+ // the private file keeps the sign-in (a keyring that encrypts but+ // cannot decrypt, a locked or half-started Secret Service).+ const readBack = await decryptKeyringCopy(storage);+ if (readBack && sameCredentials(readBack.credentials, normalized)) {+ await discardPlaintextCredentialFile(fallbackFilePath, PLAINTEXT_KIND, log);+ await noteKeyringSealed(storage);+ } else {+ log("[omnirush] The system keyring did not return the saved omnirush.ai sign-in; keeping it in the private file.");+ await writePlaintextCredentialFile(+ fallbackFilePath,+ `${JSON.stringify({ note: PLAINTEXT_NOTE, credentials: normalized }, null, 2)}\n`,+ );+ logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);+ }+ }}await rm(signedOutPath, { force: true });cached = normalized;@@ -602,7 +664,7 @@ export function createDesktopOmniRushAccountStore({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, reauthorizationRequired: true, keyringUnavailable: true };}return { connected: false, gatewayConfigured, ...server, ...storage };}diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex 1568dc42..4f000f61 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -877,6 +877,7 @@ test("a keyring that disappears asks for a new sign-in instead of failing", asynassert.equal(status.connected, false);assert.equal(status.reauthorizationRequired, true);assert.equal(status.credentialStorage, "file");+ assert.equal(status.keyringUnavailable, true);// Signing in again works and lands in the private file.const store = createDesktopOmniRushAccountStore(options);@@ -925,3 +926,62 @@ test("Linux basic_text without a fallback path keeps refusing (no silent plainte/Secure desktop credential storage is unavailable/,);});++test("migration keeps the private file until the keyring copy reads back, and the user stays signed in", async () => {+ const { options: plain } = await fallbackOptions(linuxStorage("basic_text"));+ await createDesktopOmniRushAccountStore(plain).save(FAKE_CREDENTIALS);++ // A keyring that encrypts but cannot return what it sealed (locked, half-started).+ const broken = { ...linuxStorage("gnome_libsecret"), decryptStringAsync: async () => { throw new Error("locked"); } };+ const recorded = [];+ const { options, logs } = await fallbackOptions(broken, { onKeyringSealed: (backend) => { recorded.push(backend); } });+ Object.assign(options, { filePath: plain.filePath, fallbackFilePath: plain.fallbackFilePath });+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, true);+ assert.equal(await exists(options.fallbackFilePath), true);+ assert.equal(JSON.parse(await readFile(options.fallbackFilePath, "utf8")).credentials.refreshToken, "fake-refresh");+ assert.deepEqual(recorded, []);+ assert.equal(logs.some((line) => /did not return/.test(line)), true);+ assert.equal(logs.some((line) => line.includes("fake-access") || line.includes("fake-refresh")), false);++ // A rotation saved while the keyring cannot read back also stays in the file.+ const store = createDesktopOmniRushAccountStore(options);+ await store.save({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-2" });+ assert.equal(JSON.parse(await readFile(options.fallbackFilePath, "utf8")).credentials.refreshToken, "fake-refresh-2");++ // Once the keyring works, the copy is verified, the file deleted and the store recorded.+ const { options: working } = await fallbackOptions(linuxStorage("gnome_libsecret"), { onKeyringSealed: (backend) => { recorded.push(backend); } });+ Object.assign(working, { filePath: plain.filePath, fallbackFilePath: plain.fallbackFilePath });+ assert.equal((await createDesktopOmniRushAccountStore(working).load())?.refreshToken, "fake-refresh-2");+ assert.equal(await exists(working.fallbackFilePath), false);+ assert.deepEqual(recorded, ["gnome_libsecret"]);+});++test("a leftover private file older than a readable keyring copy never replaces it", async () => {+ const { options } = await fallbackOptions(linuxStorage("gnome_libsecret"));+ const { options: plain } = await fallbackOptions(linuxStorage("basic_text"));+ Object.assign(plain, { filePath: options.filePath, fallbackFilePath: options.fallbackFilePath });+ await createDesktopOmniRushAccountStore(plain).save(FAKE_CREDENTIALS);+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));+ // The keyring copy holds a newer rotation (its delete of the file failed).+ await writeFile(options.filePath, `sealed:${JSON.stringify({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-newer" })}`);+ assert.equal((await createDesktopOmniRushAccountStore(options).load())?.refreshToken, "fake-refresh-newer");+ assert.equal(await exists(options.fallbackFilePath), false);+});++test("a session the server ended in file mode is not reported as a missing keyring", async () => {+ const { options } = await fallbackOptions(linuxStorage("basic_text"), {+ fetchImpl: async (url) => {+ const pathname = new URL(url).pathname;+ if (pathname.endsWith("/device/me") || pathname.endsWith("/device/refresh")) return new Response(null, { status: 401 });+ if (pathname.endsWith("/device/logout")) return new Response(null, { status: 204 });+ throw new Error(`Unexpected request ${pathname}`);+ },+ sleep: async () => undefined,+ });+ await createDesktopOmniRushAccountStore(options).save(FAKE_CREDENTIALS);+ const status = await createDesktopOmniRushAccountStore(options).status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.equal(status.keyringUnavailable, undefined);+});diff --git a/apps/desktop/electron/plaintext-credential-file.mjs b/apps/desktop/electron/plaintext-credential-file.mjsindex 0ad6244f..59891f64 100644--- a/apps/desktop/electron/plaintext-credential-file.mjs+++ b/apps/desktop/electron/plaintext-credential-file.mjs@@ -1,5 +1,6 @@import { randomUUID } from "node:crypto";-import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import { constants } from "node:fs";+import { chmod, mkdir, open, rename, rm, writeFile } from "node:fs/promises";import path from "node:path";// Linux fallback for systems without a usable keyring (Electron's safeStorage@@ -37,20 +38,25 @@ export async function usableSafeStorage(loadSafeStorage, platform) {}/**- * The file's text, or null when it does not exist. Tightens permissions that- * were loosened since the file was written.+ * The file's text, or null when it does not exist. Never follows a symlink+ * (O_NOFOLLOW), and tightens permissions on the opened file itself when they+ * were loosened since it was written.* @param {string} filePath*/export async function readPlaintextCredentialFile(filePath) {- let contents;+ let handle;try {- contents = await readFile(filePath, "utf8");+ handle = await open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));} catch (error) {if (error?.code === "ENOENT") return null;throw error;}- await chmod(filePath, 0o600).catch(() => undefined);- return contents;+ try {+ await handle.chmod(0o600).catch(() => undefined);+ return await handle.readFile("utf8");+ } finally {+ await handle.close().catch(() => undefined);+ }}/**@@ -77,3 +83,21 @@ export async function writePlaintextCredentialFile(filePath, contents) {export async function removePlaintextCredentialFile(filePath) {await rm(filePath, { force: true });}++/**+ * Remove the private file once its contents are safely elsewhere. A failure+ * is logged, not thrown: the caller's newer copy is already in place, and a+ * stale file only means the next load migrates it again.+ * @param {string} filePath+ * @param {string} kind+ * @param {(message: string) => void} log+ */+export async function discardPlaintextCredentialFile(filePath, kind, log) {+ try {+ await removePlaintextCredentialFile(filePath);+ return true;+ } catch (error) {+ log(`[omnirush] Could not delete the private file for the ${kind} (${error?.code ?? "error"}); it will be retried.`);+ return false;+ }+}diff --git a/apps/desktop/electron/secure-vault-key.mjs b/apps/desktop/electron/secure-vault-key.mjsindex 94429e3a..e3a29eba 100644--- a/apps/desktop/electron/secure-vault-key.mjs+++ b/apps/desktop/electron/secure-vault-key.mjs@@ -3,9 +3,9 @@ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"import path from "node:path";import {+ discardPlaintextCredentialFile,logPlaintextCredentialsOnce,readPlaintextCredentialFile,- removePlaintextCredentialFile,writePlaintextCredentialFile,} from "./plaintext-credential-file.mjs";@@ -67,22 +67,48 @@ function decodeKey(encoded) {* loadSafeStorage: () => import("electron").SafeStorage;* platform?: NodeJS.Platform;* fallbackFilePath?: string | null;+ * onKeyringSealed?: ((backend: string) => unknown) | 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).+ * (see plaintext-credential-file.mjs). `onKeyringSealed`: Linux only, told+ * which safeStorage backend sealed the key, so later launches keep that+ * --password-store.*/export function createDesktopVaultKeyProvider({filePath,loadSafeStorage,platform = process.platform,fallbackFilePath = null,+ onKeyringSealed = null,log = (message) => console.warn(message),}) {/** @type {Promise<Buffer> | null} */let pending = null;const fileFallback = platform === "linux" && Boolean(fallbackFilePath);+ /** @param {import("electron").SafeStorage} safeStorage */+ async function noteKeyringSealed(safeStorage) {+ if (!fileFallback || !onKeyringSealed) return;+ try {+ await onKeyringSealed(safeStorage.getSelectedStorageBackend());+ } catch {+ // Best effort: without the record the startup probe still decides.+ }+ }++ /**+ * The key sealed in `filePath`, or null when it is missing or unreadable.+ * @param {import("electron").SafeStorage} safeStorage+ */+ async function readSealedKey(safeStorage) {+ try {+ return decodeKey((await safeStorage.decryptStringAsync(await readFile(filePath))).result);+ } catch {+ return null;+ }+ }+/** The key kept in the private file, or null when there is none or it is invalid. */async function readUnprotectedKey() {try {@@ -126,13 +152,24 @@ export function createDesktopVaultKeyProvider({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.");+ // any older, different sealed blob as a backup, and delete the private+ // file only once the sealed copy reads back as the same key. Until+ // then the file keeps the vault usable and a later launch retries.+ const existing = await readSealedKey(safeStorage);+ if (!existing?.equals(unprotected)) {+ 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")));+ }+ const readBack = existing?.equals(unprotected) ? existing : await readSealedKey(safeStorage);+ if (readBack?.equals(unprotected)) {+ await discardPlaintextCredentialFile(fallbackFilePath, PLAINTEXT_KIND, log);+ await noteKeyringSealed(safeStorage);+ log("[omnirush] Moved the MCP credential vault key from the private file into the system keyring.");+ } else {+ log("[omnirush] The system keyring did not return the MCP credential vault key; keeping it in the private file.");+ }return unprotected;}@@ -162,12 +199,14 @@ export function createDesktopVaultKeyProvider({if (decrypted.shouldReEncrypt) {await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(decrypted.result));}+ await noteKeyringSealed(safeStorage);return key;}}const key = randomBytes(KEY_BYTES);await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(key.toString("base64")));+ await noteKeyringSealed(safeStorage);return key;}diff --git a/apps/desktop/electron/secure-vault-key.test.mjs b/apps/desktop/electron/secure-vault-key.test.mjsindex f4d1c995..5b4de093 100644--- a/apps/desktop/electron/secure-vault-key.test.mjs+++ b/apps/desktop/electron/secure-vault-key.test.mjs@@ -180,6 +180,27 @@ describe("desktop managed MCP vault key", () => {}});+ it("keeps the private file until the sealed key reads back, then records the store", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));+ const { filePath, fallbackFilePath } = paths(root);+ try {+ const recorded = [];+ const base = { filePath, fallbackFilePath, platform: /** @type {const} */ ("linux"), log: quiet, onKeyringSealed: (backend) => { recorded.push(backend); } };+ const key = await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: basicText })();+ const broken = fakeSafeStorage({ decryptStringAsync: async () => { throw new Error("locked"); } });+ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => broken })(), key);+ assert.equal(await exists(fallbackFilePath), true);+ assert.deepEqual(recorded, []);++ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => fakeSafeStorage() })(), key);+ assert.equal(await exists(fallbackFilePath), false);+ assert.deepEqual(recorded, ["gnome_libsecret"]);+ assert.deepEqual(await createDesktopVaultKeyProvider({ ...base, loadSafeStorage: () => fakeSafeStorage() })(), key);+ } 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-"));diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex cd1ce3df..b16914ae 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -149,6 +149,12 @@ export type OmniRushAccountStatus = {* owner-only file on this computer. Absent when a keyring protects it.*/credentialStorage?: "file";+ /**+ * Linux: a sign-in sealed by a system keyring is on disk but no keyring is+ * usable now, so the user is asked to sign in again. Distinct from a+ * session the server ended (reauthorizationRequired alone).+ */+ keyringUnavailable?: boolean;};export type EngineDoctorResult = {