Skip to content

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

fix(security): prevent key loss when keychain backend becomes unavailable (#722)

Alcahestd0a7c74d2518
diff --git a/src/helpers/secretCrypto.js b/src/helpers/secretCrypto.js
index 95b597917..f9f882949 100644
--- a/src/helpers/secretCrypto.js
+++ b/src/helpers/secretCrypto.js
@@ -1,5 +1,7 @@
const crypto = require("crypto");
-const { safeStorage } = require("electron");
+const fs = require("fs");
+const path = require("path");
+const { app, safeStorage } = require("electron");
const debugLogger = require("./debugLogger");
const SERVICE = "OpenWhispr";
@@ -8,10 +10,43 @@ const ALGO = "aes-256-gcm";
const IV_LEN = 12;
const TAG_LEN = 16;
const KEY_LEN = 32;
+const BACKUP_FILE = "master-key-backup.enc";
let mode = null;
let masterKey = null;
+function _backupPath() {
+ return path.join(app.getPath("userData"), "secure-keys", BACKUP_FILE);
+}
+
+function _saveMasterKeyBackup() {
+ if (!masterKey || !safeStorage.isEncryptionAvailable()) return;
+ const target = _backupPath();
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ const encrypted = safeStorage.encryptString(masterKey.toString("base64"));
+ const tmp = target + ".tmp";
+ fs.writeFileSync(tmp, encrypted, { mode: 0o600 });
+ fs.renameSync(tmp, target);
+ } catch (error) {
+ debugLogger.warn("failed to save master key backup", { error: error?.message }, "secretCrypto");
+ }
+}
+
+function _loadMasterKeyBackup() {
+ if (!safeStorage.isEncryptionAvailable()) return false;
+ try {
+ const buf = fs.readFileSync(_backupPath());
+ const b64 = safeStorage.decryptString(buf);
+ const key = Buffer.from(b64, "base64");
+ if (key.length !== KEY_LEN) return false;
+ masterKey = key;
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function _initKeychain() {
let Entry;
try {
@@ -35,6 +70,7 @@ function _initKeychain() {
masterKey = crypto.randomBytes(KEY_LEN);
entry.setPassword(masterKey.toString("base64"));
}
+ _saveMasterKeyBackup();
return true;
} catch (error) {
debugLogger.warn(
@@ -52,6 +88,11 @@ function _ensureInit() {
mode = "keychain";
return;
}
+ if (_loadMasterKeyBackup()) {
+ mode = "keychain";
+ debugLogger.info("recovered master key from safeStorage backup", {}, "secretCrypto");
+ return;
+ }
mode = safeStorage.isEncryptionAvailable() ? "safeStorage" : "unavailable";
}