Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: sign-in without system keyring

ogsamrat9d9aa2ac20db
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.tsx
index ebb5c0b6..df244a38 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
@@ -297,7 +297,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
</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.
+ Signed in. No system keyring is available, so the sign-in is kept in a private file on this computer.
</div>
) : null}
{usage ? (
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 315955f1..1af6e063 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -1353,7 +1353,8 @@ const omnirushAccountStore = createDesktopOmniRushAccountStore({
// Sign-in, device code, token refresh, profile and sign-out.
fetchImpl: desktopExternalFetch,
loadSafeStorage: () => require("electron").safeStorage,
- // Linux without a usable keyring only; unencrypted at rest, owner-only.
+ // Only while no keyring is usable (none on Linux, or one that refuses to
+ // encrypt); unencrypted at rest, owner-only.
fallbackFilePath: path.join(app.getPath("userData"), "private-credentials", "omnirush-account.json"),
onKeyringSealed: recordKeyringSealed("omnirush-account.bin"),
onClientUpdate: (clientUpdate) => updateGate.signal({ kind: "profile", clientUpdate }),
@@ -1398,7 +1399,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.
+ // Only while no keyring is usable (none on Linux, or one that refuses to
+ // encrypt); 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"),
}),
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index 206a7900..69b1cbfc 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -59,7 +59,7 @@ const PERSIST_RETRY_MAX_MS = 60_000;
*/
const NEVER_SENT = /\b(?:ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH|UND_ERR_CONNECT_TIMEOUT|ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_INTERNET_DISCONNECTED|ERR_CONNECTION_REFUSED|ERR_CONNECTION_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_PROXY_CONNECTION_FAILED|ERR_CERT_\w+|ERR_TLS_CERT_\w+|SELF_SIGNED_CERT_IN_CHAIN|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_\w+|CERT_HAS_EXPIRED)\b/;
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.";
+const PLAINTEXT_NOTE = "Unencrypted at rest: no usable system keyring. Owner-only file; signing out deletes it.";
function sameCredentials(left, right) {
return left.gatewayUrl === right.gatewayUrl
@@ -303,8 +303,10 @@ 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).
+ // Where the sign-in is kept, unencrypted at rest with owner-only
+ // permissions, while no keyring is usable: Linux without a keyring, or any
+ // platform whose keyring refuses to encrypt (a macOS keychain entry the
+ // updated app may no longer open). 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.
@@ -362,8 +364,17 @@ export function createDesktopOmniRushAccountStore({
let persistRetry = null;
let persistRetryAttempt = 0;
let loading = null;
- const fileFallback = platform === "linux" && Boolean(fallbackFilePath);
+ const fileFallback = Boolean(fallbackFilePath);
+ /**
+ * The keyring refused to encrypt in this process. Electron keeps its
+ * encryptor for the life of the process, so asking again only fails again
+ * (and on macOS may show the keychain prompt again): the private file is
+ * used until the next launch.
+ */
+ let keyringRefused = false;
let keyringLossLogged = false;
+ /** A keyring copy is on disk but this launch's keyring cannot decrypt it. */
+ let sealedUnreadable = false;
let sealedBackendRecorded = null;
// Every writer is tracked so a reader, the broker's latest() in
// particular, observes a settled store rather than the pair a rotation is
@@ -402,9 +413,19 @@ export function createDesktopOmniRushAccountStore({
}
async function safeStorage() {
+ if (keyringRefused) return null;
return usableSafeStorage(loadSafeStorage, platform);
}
+ /** Writes the private file and warns once. */
+ async function writeFallbackFile(normalized) {
+ await writePlaintextCredentialFile(
+ fallbackFilePath,
+ `${JSON.stringify({ note: PLAINTEXT_NOTE, credentials: normalized }, null, 2)}\n`,
+ );
+ logPlaintextCredentialsOnce(PLAINTEXT_KIND, log);
+ }
+
async function loadFallbackFile() {
try {
const contents = await readPlaintextCredentialFile(fallbackFilePath);
@@ -414,9 +435,14 @@ export function createDesktopOmniRushAccountStore({
}
}
+ function noteSealedUnreadable() {
+ if (!sealedUnreadable) log("[omnirush] The saved omnirush.ai sign-in cannot be decrypted by the system keyring now; asking to sign in again.");
+ sealedUnreadable = true;
+ }
+
/** Tell main which backend sealed the sign-in (once per backend per process). */
async function noteKeyringSealed(storage) {
- if (!fileFallback || !onKeyringSealed) return;
+ if (platform !== "linux" || !fileFallback || !onKeyringSealed) return;
const backend = storage.getSelectedStorageBackend();
if (sealedBackendRecorded === backend) return;
try {
@@ -465,12 +491,20 @@ export function createDesktopOmniRushAccountStore({
// 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."),
+ () => {
+ if (!keyringRefused) log("[omnirush] Moved the omnirush.ai sign-in from the private file into the system keyring.");
+ },
() => undefined,
);
return unprotected;
}
- if (!sealed) return null;
+ if (!sealed) {
+ // A saved sign-in this keyring cannot open (an update changed the
+ // app's identity, the keychain entry was denied or replaced): signed
+ // out, and the user is asked to sign in again.
+ if (await exists(filePath)) noteSealedUnreadable();
+ return null;
+ }
if (unprotected) await discardPlaintextCredentialFile(fallbackFilePath, PLAINTEXT_KIND, log);
await noteKeyringSealed(storage);
if (sealed.shouldReEncrypt) await enqueueWrite(sealed.credentials);
@@ -664,17 +698,30 @@ export function createDesktopOmniRushAccountStore({
async function writeCredentials(normalized) {
const storage = await safeStorage();
- if (!storage) {
+ /** @type {Buffer | null} */
+ let encrypted = null;
+ if (storage) {
+ try {
+ encrypted = await storage.encryptStringAsync(JSON.stringify(normalized));
+ } catch (error) {
+ // isAsyncEncryptionAvailable() only says the encryptor started, not
+ // that the keyring gave it a key: a denied or locked macOS keychain
+ // (the app's code signature changed with an update), a Windows DPAPI
+ // failure. Never fail the sign-in over it.
+ if (!fileFallback) throw new Error(`Secure desktop credential storage is unavailable: ${error?.message ?? error}`);
+ keyringRefused = true;
+ log(`[omnirush] The system keyring could not encrypt the omnirush.ai sign-in (${error?.message ?? error}); keeping it in the private file.`);
+ }
+ }
+ if (!encrypted) {
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);
+ // Unencrypted at rest, protected only by owner-only permissions: no
+ // usable keyring. The next load with a working keyring migrates it.
+ await writeFallbackFile(normalized);
+ // A keyring copy left on disk holds an older pair this one replaces:
+ // never let a later launch read it back.
+ if (storage) await rm(filePath, { force: true }).catch(() => undefined);
} 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 });
@@ -683,20 +730,16 @@ export function createDesktopOmniRushAccountStore({
throw error;
});
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).
+ // 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 writeFallbackFile(normalized);
}
}
}
@@ -1045,7 +1088,9 @@ export function createDesktopOmniRushAccountStore({
if (fileBacked && await keyringCopyUnreadable()) {
return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true, keyringUnavailable: true };
}
- if (signInRequired) return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true };
+ if (signInRequired || (sealedUnreadable && await exists(filePath))) {
+ return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true };
+ }
return { connected: false, gatewayConfigured, ...server, ...storage };
}
try {
diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjs
index 0132bcf2..10e91ade 100644
--- a/apps/desktop/electron/omnirush-account.test.mjs
+++ b/apps/desktop/electron/omnirush-account.test.mjs
@@ -1244,14 +1244,15 @@ test("sign-out deletes the private file and stays signed out", async () => {
});
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 () => {
+ test(`${platform}: unavailable secure storage keeps the sign-in in the 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);
+ await store.save(FAKE_CREDENTIALS);
+ assert.equal(await exists(options.fallbackFilePath), true);
+ assert.equal(await exists(options.filePath), false);
+ const status = await createDesktopOmniRushAccountStore(options).status();
+ assert.equal(status.connected, true);
+ assert.equal(status.credentialStorage, "file");
});
test(`${platform}: available secure storage is used exactly as before`, async () => {
@@ -1264,6 +1265,144 @@ for (const platform of /** @type {const} */ (["darwin", "win32"])) {
});
}
+// Electron's exact rejection when the encryptor started but the keyring gave
+// it no key (a denied macOS keychain entry after the app's signature changed).
+const ENCRYPT_REFUSED = "Error while encrypting the text provided to safeStorage.encryptStringAsync.";
+
+/** A keyring that reports encryption available, then refuses to encrypt; it counts its attempts. */
+function refusingStorage(backend = "unknown") {
+ const storage = {
+ ...linuxStorage(backend),
+ encryptCalls: 0,
+ encryptStringAsync: async () => {
+ storage.encryptCalls += 1;
+ throw new Error(ENCRYPT_REFUSED);
+ },
+ };
+ return storage;
+}
+
+for (const platform of /** @type {const} */ (["darwin", "win32", "linux"])) {
+ test(`${platform}: a keyring that refuses to encrypt never fails the sign-in`, async () => {
+ const storage = refusingStorage(platform === "linux" ? "gnome_libsecret" : "unknown");
+ const { options, logs } = await fallbackOptions(storage, {
+ platform,
+ 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")) 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", openVerification: async () => undefined });
+ assert.equal(result.connected, true);
+
+ const saved = JSON.parse(await readFile(options.fallbackFilePath, "utf8"));
+ assert.equal(saved.credentials.refreshToken, "fake-refresh");
+ if (process.platform !== "win32") assert.equal((await stat(options.fallbackFilePath)).mode & 0o777, 0o600);
+ assert.equal(await exists(options.filePath), false);
+ assert.equal(logs.filter((line) => line.includes(ENCRYPT_REFUSED)).length, 1);
+ assert.equal(logs.some((line) => line.includes("fake-access") || line.includes("fake-refresh")), false);
+
+ const status = await store.status();
+ assert.equal(status.connected, true);
+ assert.equal(status.credentialStorage, "file");
+
+ // The keyring is asked once per launch: a rotation saves straight to the file.
+ await store.save({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-2", rotation: 1 });
+ assert.equal(storage.encryptCalls, 1);
+ assert.equal(JSON.parse(await readFile(options.fallbackFilePath, "utf8")).credentials.refreshToken, "fake-refresh-2");
+
+ // The next launch, still refused, reads the file and stays signed in.
+ const relaunched = createDesktopOmniRushAccountStore({ ...options, loadSafeStorage: () => refusingStorage() });
+ assert.equal((await relaunched.load())?.refreshToken, "fake-refresh-2");
+ assert.equal(await exists(options.fallbackFilePath), true);
+ });
+}
+
+test("after an update the old keyring copy cannot be decrypted: signed out, then sign-in works", async () => {
+ // Sealed by the previous build's keychain identity.
+ const { options: before } = await fallbackOptions(linuxStorage("unknown"), { platform: "darwin" });
+ await createDesktopOmniRushAccountStore(before).save(FAKE_CREDENTIALS);
+ assert.match(await readFile(before.filePath, "utf8"), /^sealed:/);
+
+ // The updated app: decrypt fails, and encrypt is refused too.
+ const storage = refusingStorage();
+ storage.decryptStringAsync = async () => { throw new Error("Error while decrypting the ciphertext provided to safeStorage.decryptStringAsync."); };
+ const { options, logs } = await fallbackOptions(storage, { platform: "darwin" });
+ Object.assign(options, { filePath: before.filePath, fallbackFilePath: before.fallbackFilePath });
+ const store = createDesktopOmniRushAccountStore(options);
+ const status = await store.status();
+ assert.equal(status.connected, false);
+ assert.equal(status.reauthorizationRequired, true);
+ assert.equal(logs.some((line) => /cannot be decrypted/.test(line)), true);
+
+ await store.save({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-new" });
+ assert.equal((await store.status()).connected, true);
+ // The old pair is gone for good: no later launch can read it back.
+ assert.equal(await exists(options.filePath), false);
+ assert.equal(JSON.parse(await readFile(options.fallbackFilePath, "utf8")).credentials.refreshToken, "fake-refresh-new");
+});
+
+test("an undecryptable keyring copy with a working keyring asks to sign in again, and the new sign-in is sealed", async () => {
+ const { options: before } = await fallbackOptions(linuxStorage("unknown"), { platform: "darwin" });
+ await createDesktopOmniRushAccountStore(before).save(FAKE_CREDENTIALS);
+ const storage = linuxStorage("unknown");
+ const original = storage.decryptStringAsync;
+ let rotatedKey = false;
+ storage.decryptStringAsync = async (value) => {
+ if (!rotatedKey) throw new Error("Error while decrypting the ciphertext provided to safeStorage.decryptStringAsync.");
+ return original(value);
+ };
+ const { options } = await fallbackOptions(storage, { platform: "darwin" });
+ Object.assign(options, { filePath: before.filePath, fallbackFilePath: before.fallbackFilePath });
+ const store = createDesktopOmniRushAccountStore(options);
+ const status = await store.status();
+ assert.equal(status.connected, false);
+ assert.equal(status.reauthorizationRequired, true);
+ assert.equal("credentialStorage" in status, false);
+
+ rotatedKey = true;
+ await store.save({ ...FAKE_CREDENTIALS, refreshToken: "fake-refresh-new" });
+ assert.match(await readFile(options.filePath, "utf8"), /^sealed:/);
+ assert.equal(await exists(options.fallbackFilePath), false);
+ assert.equal((await store.status()).connected, true);
+});
+
+test("a keyring that works again on a later launch receives the sign-in from the private file", async () => {
+ const { options } = await fallbackOptions(refusingStorage(), { platform: "darwin" });
+ await createDesktopOmniRushAccountStore(options).save(FAKE_CREDENTIALS);
+ assert.equal(await exists(options.fallbackFilePath), true);
+
+ const logs = [];
+ const healed = createDesktopOmniRushAccountStore({ ...options, loadSafeStorage: () => linuxStorage("unknown"), log: (line) => logs.push(line) });
+ assert.equal((await healed.load())?.refreshToken, "fake-refresh");
+ assert.match(await readFile(options.filePath, "utf8"), /^sealed:/);
+ assert.equal(await exists(options.fallbackFilePath), false);
+ assert.equal(logs.some((line) => /into the system keyring/.test(line)), true);
+});
+
+test("a keyring that throws while reporting availability counts as unusable", async () => {
+ const storage = { ...linuxStorage("unknown"), isAsyncEncryptionAvailable: async () => { throw new Error("safeStorage cannot be used before app is ready"); } };
+ const { options } = await fallbackOptions(storage, { platform: "darwin" });
+ const store = createDesktopOmniRushAccountStore(options);
+ await store.save(FAKE_CREDENTIALS);
+ assert.equal(await exists(options.fallbackFilePath), true);
+ assert.equal((await store.status()).connected, true);
+});
+
+test("without a private file path a refusing keyring still fails the save, naming the cause", async () => {
+ const options = await storeOptions({ platform: "darwin", loadSafeStorage: () => refusingStorage() });
+ await assert.rejects(
+ createDesktopOmniRushAccountStore(options).save(FAKE_CREDENTIALS),
+ /Secure desktop credential storage is unavailable: Error while encrypting/,
+ );
+});
+
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(
diff --git a/apps/desktop/electron/plaintext-credential-file.mjs b/apps/desktop/electron/plaintext-credential-file.mjs
index 59891f64..5cc61003 100644
--- a/apps/desktop/electron/plaintext-credential-file.mjs
+++ b/apps/desktop/electron/plaintext-credential-file.mjs
@@ -3,13 +3,15 @@ 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
-// 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.
+// Fallback for systems without a usable keyring: Linux where Electron's
+// safeStorage reports the "basic_text" backend or no encryption at all, and
+// any platform whose keyring refuses to encrypt (a macOS keychain entry the
+// updated app is denied, a DPAPI failure). 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 while no keyring is usable, and move their contents
+// into safeStorage once one is.
const loggedKinds = new Set();
@@ -21,7 +23,7 @@ const loggedKinds = new Set();
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.`);
+ log(`[omnirush] No usable system keyring: the ${kind} is kept unencrypted at rest in an owner-only (0600) file in the app data folder.`);
}
/**
@@ -31,10 +33,15 @@ export function logPlaintextCredentialsOnce(kind, log = console.warn) {
* @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;
+ try {
+ const storage = loadSafeStorage();
+ if (!storage || !(await storage.isAsyncEncryptionAvailable())) return null;
+ if (platform === "linux" && storage.getSelectedStorageBackend() === "basic_text") return null;
+ return storage;
+ } catch {
+ // Called before `ready`, or the keyring failed to start: not usable.
+ return null;
+ }
}
/**
diff --git a/apps/desktop/electron/secure-vault-key.mjs b/apps/desktop/electron/secure-vault-key.mjs
index e3a29eba..72ec4656 100644
--- a/apps/desktop/electron/secure-vault-key.mjs
+++ b/apps/desktop/electron/secure-vault-key.mjs
@@ -10,6 +10,13 @@ import {
} from "./plaintext-credential-file.mjs";
const KEY_BYTES = 32;
+
+/** safeStorage.encryptStringAsync rejected although encryption was reported available. */
+class KeyringRefusedError extends Error {
+ constructor(cause) {
+ super("The system keyring refused to encrypt", { cause });
+ }
+}
const PLAINTEXT_KIND = "MCP credential vault key";
/**
@@ -69,9 +76,10 @@ function decodeKey(encoded) {
* 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). `onKeyringSealed`: Linux only, told
+ * }} options `fallbackFilePath`: where the key is kept, unencrypted at rest
+ * with owner-only permissions, while no keyring is usable (Linux without a
+ * keyring, or a keyring that refuses to encrypt on any platform; see
+ * plaintext-credential-file.mjs). `onKeyringSealed`: Linux only, told
* which safeStorage backend sealed the key, so later launches keep that
* --password-store.
*/
@@ -85,11 +93,11 @@ export function createDesktopVaultKeyProvider({
}) {
/** @type {Promise<Buffer> | null} */
let pending = null;
- const fileFallback = platform === "linux" && Boolean(fallbackFilePath);
+ const fileFallback = Boolean(fallbackFilePath);
/** @param {import("electron").SafeStorage} safeStorage */
async function noteKeyringSealed(safeStorage) {
- if (!fileFallback || !onKeyringSealed) return;
+ if (platform !== "linux" || !fileFallback || !onKeyringSealed) return;
try {
await onKeyringSealed(safeStorage.getSelectedStorageBackend());
} catch {
@@ -120,7 +128,7 @@ export function createDesktopVaultKeyProvider({
}
/**
- * Linux without a usable keyring: the key lives in an owner-only file,
+ * No 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.
@@ -132,14 +140,45 @@ export function createDesktopVaultKeyProvider({
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`,
+ `${JSON.stringify({ note: "Unencrypted at rest: no usable system keyring. Owner-only file.", key: key.toString("base64") }, null, 2)}\n`,
);
return key;
}
+ /**
+ * The key, sealed by the keyring when it can encrypt. A keyring that
+ * refuses (a denied macOS keychain entry, a DPAPI failure) falls back to
+ * the private file when there is one.
+ */
async function loadKey() {
+ try {
+ return await loadSealedKey();
+ } catch (error) {
+ if (!(error instanceof KeyringRefusedError)) throw error;
+ if (!fileFallback) throw error.cause;
+ const cause = error.cause instanceof Error ? error.cause.message : String(error.cause);
+ log(`[omnirush] The system keyring could not encrypt the MCP credential vault key (${cause}); keeping it in the private file.`);
+ return loadUnprotectedKey();
+ }
+ }
+
+ /** @param {import("electron").SafeStorage} safeStorage @param {string} value */
+ async function seal(safeStorage, value) {
+ try {
+ return await safeStorage.encryptStringAsync(value);
+ } catch (error) {
+ throw new KeyringRefusedError(error);
+ }
+ }
+
+ async function loadSealedKey() {
const safeStorage = loadSafeStorage();
- const encryptionAvailable = Boolean(safeStorage) && await safeStorage.isAsyncEncryptionAvailable();
+ let encryptionAvailable = false;
+ try {
+ encryptionAvailable = Boolean(safeStorage) && await safeStorage.isAsyncEncryptionAvailable();
+ } catch {
+ encryptionAvailable = false;
+ }
const basicText = encryptionAvailable && platform === "linux" && safeStorage.getSelectedStorageBackend() === "basic_text";
if (fileFallback && (!encryptionAvailable || basicText)) return loadUnprotectedKey();
if (!encryptionAvailable) {
@@ -160,7 +199,11 @@ export function createDesktopVaultKeyProvider({
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")));
+ try {
+ await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(unprotected.toString("base64")));
+ } catch {
+ // The keyring refused: the private file keeps the vault usable.
+ }
}
const readBack = existing?.equals(unprotected) ? existing : await readSealedKey(safeStorage);
if (readBack?.equals(unprotected)) {
@@ -197,7 +240,11 @@ export function createDesktopVaultKeyProvider({
}
if (decrypted && key) {
if (decrypted.shouldReEncrypt) {
- await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(decrypted.result));
+ // Best effort: the key read back fine either way.
+ await safeStorage.encryptStringAsync(decrypted.result).then(
+ (sealed) => replaceProtectedKey(filePath, sealed),
+ () => undefined,
+ );
}
await noteKeyringSealed(safeStorage);
return key;
@@ -205,7 +252,7 @@ export function createDesktopVaultKeyProvider({
}
const key = randomBytes(KEY_BYTES);
- await replaceProtectedKey(filePath, await safeStorage.encryptStringAsync(key.toString("base64")));
+ await replaceProtectedKey(filePath, await seal(safeStorage, 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.mjs
index 5b4de093..a6c7248d 100644
--- a/apps/desktop/electron/secure-vault-key.test.mjs
+++ b/apps/desktop/electron/secure-vault-key.test.mjs
@@ -201,20 +201,63 @@ describe("desktop managed MCP vault key", () => {
}
});
+ const REFUSED = "Error while encrypting the text provided to safeStorage.encryptStringAsync.";
+
for (const platform of /** @type {const} */ (["darwin", "win32"])) {
- it(`${platform}: unavailable secure storage still fails closed and writes no private file`, async () => {
+ it(`${platform}: unavailable secure storage keeps the key in the private file`, async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));
const { filePath, fallbackFilePath } = paths(root);
try {
- const provider = createDesktopVaultKeyProvider({
+ const options = {
filePath,
fallbackFilePath,
platform,
log: quiet,
loadSafeStorage: () => fakeSafeStorage({ isAsyncEncryptionAvailable: async () => false }),
- });
- await assert.rejects(provider(), /secure storage is unavailable/);
+ };
+ const key = await createDesktopVaultKeyProvider(options)();
+ assert.equal(key.byteLength, 32);
+ assert.equal(await exists(fallbackFilePath), true);
+ assert.equal(await exists(filePath), false);
+ assert.deepEqual(await createDesktopVaultKeyProvider(options)(), key);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it(`${platform}: a keyring that refuses to encrypt keeps the key in the private file`, async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));
+ const { filePath, fallbackFilePath } = paths(root);
+ const logs = [];
+ try {
+ const refusing = () => fakeSafeStorage({ encryptStringAsync: async () => { throw new Error(REFUSED); } });
+ const options = { filePath, fallbackFilePath, platform, log: (line) => logs.push(line), loadSafeStorage: refusing };
+ const key = await createDesktopVaultKeyProvider(options)();
+ assert.equal(key.byteLength, 32);
+ assert.equal(JSON.parse(await readFile(fallbackFilePath, "utf8")).key, key.toString("base64"));
+ assert.equal(await exists(filePath), false);
+ assert.equal(logs.some((line) => line.includes("could not encrypt")), true);
+ // A later launch whose keyring works again seals the same key and drops the file.
+ const healed = await createDesktopVaultKeyProvider({ ...options, loadSafeStorage: () => fakeSafeStorage() })();
+ assert.deepEqual(healed, key);
assert.equal(await exists(fallbackFilePath), false);
+ assert.equal(await exists(filePath), true);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it(`${platform}: without a private file path a refusing keyring still fails with its own error`, async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-vault-key-"));
+ const { filePath } = paths(root);
+ try {
+ const provider = createDesktopVaultKeyProvider({
+ filePath,
+ platform,
+ log: quiet,
+ loadSafeStorage: () => fakeSafeStorage({ encryptStringAsync: async () => { throw new Error(REFUSED); } }),
+ });
+ await assert.rejects(provider(), /safeStorage\.encryptStringAsync/);
assert.equal(await exists(filePath), false);
} finally {
await rm(root, { recursive: true, force: true });