Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(auth): switch desktop to Authorization: Bearer + safeStorage (#704)
Gabriel Stein72b7ed3970fd
diff --git a/main.js b/main.jsindex 8b3d620ae..bdae5bce9 100644--- a/main.js+++ b/main.js@@ -463,7 +463,7 @@ app.on("open-url", (event, url) => {return;}- handleOAuthDeepLink(url);+ void handleOAuthDeepLink(url);if (windowManager && isLiveWindow(windowManager.controlPanelWindow)) {windowManager.controlPanelWindow.show();@@ -471,27 +471,86 @@ app.on("open-url", (event, url) => {}});-// Inject the Better Auth session cookie into Electron's session, then reload-// the control panel so the renderer's authClient picks up the new session.-async function applySessionTokenAndRefresh(token) {- if (!token) return;- if (!isLiveWindow(windowManager?.controlPanelWindow)) return;+function resolveAuthUrl() {+ const fs = require("fs");+ const envPath = path.join(__dirname, "src", "dist", "runtime-env.json");+ let runtimeEnv = {};+ try {+ if (fs.existsSync(envPath)) runtimeEnv = JSON.parse(fs.readFileSync(envPath, "utf8"));+ } catch {}+ return (+ process.env.AUTH_URL ||+ process.env.VITE_AUTH_URL ||+ runtimeEnv.VITE_AUTH_URL ||+ "https://auth.openwhispr.com"+ );+}++function getOauthCookieName() {+ return process.env.NODE_ENV === "production"+ ? "__Secure-openwhispr.session_token"+ : "openwhispr.session_token";+}+// Older website builds send the signed cookie value as `?token=`; trade it+// for the raw session.token the bearer plugin expects.+async function exchangeSignedTokenForRawBearer(signedToken) {try {- await session.defaultSession.cookies.set({- url: "https://auth.openwhispr.com",- name: "__Secure-openwhispr.session_token",- value: token,- domain: ".openwhispr.com",- path: "/",- secure: true,- httpOnly: true,- sameSite: "lax",+ const res = await fetch(`${resolveAuthUrl()}/api/auth/get-session`, {+ headers: { Cookie: `${getOauthCookieName()}=${signedToken}` },+ signal: AbortSignal.timeout(5000),});+ if (!res.ok) return null;+ const data = await res.json();+ return data?.session?.token || null;} catch (err) {- if (debugLogger) debugLogger.error("Failed to set OAuth session cookie:", err);- return;+ if (debugLogger) {+ debugLogger.warn("Signed-token bearer exchange failed (non-fatal)", {+ error: err?.message,+ });+ }+ return null;+ }+}++// One-time bridge for users upgrading from a build that injected the session+// cookie into Electron's jar: exchange the existing cookie for a raw bearer+// token, store it, and remove the cookie. Non-fatal — failures fall through+// to the normal sign-in flow.+async function migrateCookieToBearerToken() {+ const tokenStore = require("./src/helpers/tokenStore");+ if (tokenStore.get()) return;++ const cookieName = getOauthCookieName();+ const authUrl = resolveAuthUrl();++ try {+ const cookies = await session.defaultSession.cookies.get({ url: authUrl, name: cookieName });+ if (!cookies.length) return;++ const rawToken = await exchangeSignedTokenForRawBearer(cookies[0].value);+ if (!rawToken) return;++ tokenStore.set(rawToken);+ await session.defaultSession.cookies.remove(authUrl, cookieName);+ if (debugLogger) debugLogger.debug("Migrated cookie to bearer token");+ } catch (err) {+ if (debugLogger) {+ debugLogger.warn("Cookie→bearer token migration failed (non-fatal)", {+ error: err?.message,+ });+ }}+}++// Persist the bearer token and reload the control panel so the renderer's+// authClient sends `Authorization: Bearer <token>` on its next request.+async function applySessionTokenAndRefresh(token) {+ if (!token) return;+ if (!isLiveWindow(windowManager?.controlPanelWindow)) return;++ const tokenStore = require("./src/helpers/tokenStore");+ tokenStore.set(token);const appUrl = DevServerManager.getAppUrl(true);if (appUrl) {@@ -504,7 +563,7 @@ async function applySessionTokenAndRefresh(token) {}if (debugLogger) {- debugLogger.debug("Applied OAuth session cookie and reloaded control panel", {+ debugLogger.debug("Applied bearer token and reloaded control panel", {appChannel: APP_CHANNEL,oauthProtocol: OAUTH_PROTOCOL,});@@ -513,12 +572,18 @@ async function applySessionTokenAndRefresh(token) {windowManager.controlPanelWindow.focus();}-function handleOAuthDeepLink(deepLinkUrl) {+async function handleOAuthDeepLink(deepLinkUrl) {try {const parsed = new URL(deepLinkUrl);- const token = parsed.searchParams.get("token");- if (!token) return;- void applySessionTokenAndRefresh(token);+ const bearerToken = parsed.searchParams.get("bearer_token");+ if (bearerToken) {+ void applySessionTokenAndRefresh(bearerToken);+ return;+ }+ const signedToken = parsed.searchParams.get("token");+ if (!signedToken) return;+ const rawToken = await exchangeSignedTokenForRawBearer(signedToken);+ if (rawToken) void applySessionTokenAndRefresh(rawToken);} catch (err) {if (debugLogger) debugLogger.error("Failed to handle OAuth deep link:", err);}@@ -582,11 +647,11 @@ function startAuthBridgeServer() {return;}- let token = requestUrl.searchParams.get("token");+ let token = requestUrl.searchParams.get("bearer_token") || requestUrl.searchParams.get("token");if (!token && req.method === "POST") {try {const body = await parseJsonBody(req);- token = body?.token || null;+ token = body?.bearer_token || body?.token || null;} catch (error) {res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });res.end(error.message || "Invalid request");@@ -639,6 +704,8 @@ async function startApp() {cliBridge = null;});+ await migrateCookieToBearerToken();+// Electron's file:// renderer sends Origin: null, which Better Auth's// trustedOrigins check rejects. Spoof Origin to the request's own URL so// calls to OpenWhispr's auth and API hosts are treated as same-origin.@@ -1300,7 +1367,7 @@ if (gotSingleInstanceLock) {if (url.includes("upgrade-success")) {handleUpgradeDeepLink();} else {- handleOAuthDeepLink(url);+ void handleOAuthDeepLink(url);}}});diff --git a/preload.js b/preload.jsindex 22c14a4a2..30018e574 100644--- a/preload.js+++ b/preload.js@@ -465,6 +465,8 @@ contextBridge.exposeInMainWorld("electronAPI", {resumeMediaPlayback: () => ipcRenderer.invoke("resume-media-playback"),openWhisperModelsFolder: () => ipcRenderer.invoke("open-whisper-models-folder"),authClearSession: () => ipcRenderer.invoke("auth-clear-session"),+ authGetToken: () => ipcRenderer.invoke("auth-get-token"),+ authSetToken: (token) => ipcRenderer.invoke("auth-set-token", token),// OpenWhispr Cloud APIcloudHealthCheck: () => ipcRenderer.invoke("cloud-health-check"),diff --git a/src/helpers/environment.js b/src/helpers/environment.jsindex dc49c009e..ed9b5369f 100644--- a/src/helpers/environment.js+++ b/src/helpers/environment.js@@ -136,7 +136,7 @@ class EnvironmentManager {if (error.code === "ENOENT") return;debugLogger.error("Failed to decrypt secret — user must re-enter",- { key: envVarName, error: error.message },+ { key: envVarName, code: error.code, error: error.message },"environment");}@@ -203,10 +203,7 @@ class EnvironmentManager {return;}- // Sentinel before .env rewrite: if the rewrite fails, next launch loads- // stale plaintext but encrypted values overwrite it on _loadAllSecrets,- // and the next saveAllKeysToEnvFile cleans the .env. Reverse order risks- // stripping plaintext for secrets that haven't been encrypted yet.+ // Write sentinel before stripping plaintext from .env so a crash mid-rewrite is recoverable.await fsPromises.writeFile(this._getMigrationSentinelPath(), "");const envPath = path.join(app.getPath("userData"), ".env");if (fs.existsSync(envPath)) await this._writeEnvFileAtomic(envPath);@@ -240,8 +237,6 @@ class EnvironmentManager {_saveKey(envVarName, key) {if (SECRET_KEY_SET.has(envVarName) && this._encryptionAvailable()) {- // _saveSecretKey updates process.env before its first await, so- // in-process reads see the new value while the encrypted write lands.this._saveSecretKey(envVarName, key).catch((error) => {debugLogger.error("Failed to persist encrypted secret",diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 33aee5ffb..fb5a931b2 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -6,6 +6,7 @@ const http = require("http");const https = require("https");const crypto = require("crypto");const debugLogger = require("./debugLogger");+const tokenStore = require("./tokenStore");const { classifyAndLog } = require("./networkErrors");const GnomeShortcutManager = require("./gnomeShortcut");const HyprlandShortcutManager = require("./hyprlandShortcut");@@ -165,7 +166,7 @@ async function chunkedCloudTranscribe({buffer = null,filePath = null,apiUrl,- cookieHeader,+ authHeader,multipartFields = {},onProgress,concurrencyLimit = CLOUD_CHUNK_CONCURRENCY,@@ -208,7 +209,7 @@ async function chunkedCloudTranscribe({multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, { Cookie: cookieHeader });+ const data = await postMultipart(url, body, boundary, authHeader);results[index] = interpretTranscribeResponse(data);completedCount++;@@ -3276,13 +3277,9 @@ class IPCHandlers {});});- // Auth: clear all session cookies for sign-out.- // This clears every cookie in the renderer session rather than targeting- // individual auth cookies, which is acceptable because the app only sets- // cookies for Better Auth. Avoids CSRF/Origin header issues that occur when- // the renderer tries to call the server-side sign-out endpoint directly.ipcMain.handle("auth-clear-session", async (event) => {try {+ tokenStore.clear();const win = BrowserWindow.fromWebContents(event.sender);if (win) {await win.webContents.session.clearStorageData({ storages: ["cookies"] });@@ -3294,6 +3291,19 @@ class IPCHandlers {}});+ ipcMain.handle("auth-get-token", () => tokenStore.get());+ ipcMain.handle("auth-set-token", (_event, token) => {+ if (typeof token === "string" && token) {+ tokenStore.set(token);+ } else {+ // Surface silent rotation-to-empty so we can spot regressions where the+ // renderer thinks it's persisting a token but the value never lands.+ debugLogger.debug("auth-set-token ignored: empty or non-string token", {+ type: typeof token,+ });+ }+ });+// In production, VITE_* env vars aren't available in the main process because// Vite only inlines them into the renderer bundle at build time. Load the// runtime-env.json that the Vite build writes to src/dist/ as a fallback.@@ -3370,9 +3380,22 @@ class IPCHandlers {return getSessionCookiesFromWindow(win);};- // Honors system proxy via Electron's net stack. useSessionCookies:false- // because we set the Cookie header manually from getSessionCookies() —- // letting Electron also attach session cookies risks duplicates.+ // Bearer auth is preferred. Cookie fallback covers the brief window before+ // main.js's startup migration bridge runs (or if it failed for this user).+ const getAuthHeaderFromWindow = async (win) => {+ const token = tokenStore.get();+ if (token) return { Authorization: `Bearer ${token}` };+ const cookieHeader = win ? await getSessionCookiesFromWindow(win) : "";+ return cookieHeader ? { Cookie: cookieHeader } : {};+ };++ const getAuthHeader = async (event) => {+ const win = BrowserWindow.fromWebContents(event.sender);+ return getAuthHeaderFromWindow(win);+ };++ // Honors system proxy via Electron's net stack. useSessionCookies:false so+ // Electron doesn't auto-attach jar cookies on top of our explicit headers.const proxyFetch = (url, init = {}) => net.fetch(url, { ...init, useSessionCookies: false });ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {@@ -3380,8 +3403,8 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const audioData = Buffer.from(audioBuffer);// Reused for the local SQLite row so SyncService upserts the existing@@ -3404,7 +3427,7 @@ class IPCHandlers {const { text, responses, lastResponse } = await chunkedCloudTranscribe({buffer: audioData,apiUrl,- cookieHeader,+ authHeader,multipartFields,});const sum = (field) => responses.reduce((s, r) => s + (r?.[field] || 0), 0);@@ -3432,7 +3455,7 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, { Cookie: cookieHeader });+ const data = await postMultipart(url, body, boundary, authHeader);debugLogger.debug("Cloud transcribe response",@@ -3513,8 +3536,8 @@ class IPCHandlers {} else if (settings?.cloudTranscriptionMode === "openwhispr") {const win = BrowserWindow.fromWebContents(event.sender);if (win) {- const cookieHeader = await getSessionCookiesFromWindow(win);- if (cookieHeader) {+ const authHeader = await getAuthHeaderFromWindow(win);+ if (Object.keys(authHeader).length) {const apiUrl = getApiUrl();if (apiUrl) {const multipartFields = {@@ -3526,7 +3549,7 @@ class IPCHandlers {const { text } = await chunkedCloudTranscribe({buffer,apiUrl,- cookieHeader,+ authHeader,multipartFields,});result = { text, source: "openwhispr", model: "cloud" };@@ -3538,9 +3561,7 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, {- Cookie: cookieHeader,- });+ const data = await postMultipart(url, body, boundary, authHeader);const responseData = interpretTranscribeResponse(data);result = {text: responseData.text,@@ -4037,14 +4058,14 @@ class IPCHandlers {const postServerToken = async (path, body = {}) => {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const url = `${apiUrl}${path}`;let response;try {response = await proxyFetch(url, {method: "POST",- headers: { "Content-Type": "application/json", Cookie: cookieHeader },+ headers: { "Content-Type": "application/json", ...authHeader },body: JSON.stringify(body),});} catch (err) {@@ -5532,8 +5553,8 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");debugLogger.debug("Cloud reason request",@@ -5549,7 +5570,7 @@ class IPCHandlers {method: "POST",headers: {"Content-Type": "application/json",- Cookie: cookieHeader,+ ...authHeader,},body: JSON.stringify({text,@@ -5618,14 +5639,14 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/agent/stream`, {method: "POST",headers: {"Content-Type": "application/json",- Cookie: cookieHeader,+ ...authHeader,},body: JSON.stringify({messages,@@ -5711,8 +5732,8 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");debugLogger.debug("Agent web search request", { query, numResults }, "cloud-api");@@ -5720,7 +5741,7 @@ class IPCHandlers {method: "POST",headers: {"Content-Type": "application/json",- Cookie: cookieHeader,+ ...authHeader,},body: JSON.stringify({ query, numResults }),});@@ -5754,14 +5775,14 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/streaming-usage`, {method: "POST",headers: {"Content-Type": "application/json",- Cookie: cookieHeader,+ ...authHeader,},body: JSON.stringify({text,@@ -5805,11 +5826,11 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/usage`, {- headers: { Cookie: cookieHeader },+ headers: authHeader,});if (!response.ok) {@@ -5835,10 +5856,10 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");- const headers = { Cookie: cookieHeader };+ const headers = { ...authHeader };const fetchOpts = { method: "POST", headers };if (body) {headers["Content-Type"] = "application/json";@@ -5879,12 +5900,12 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/stripe/switch-plan`, {method: "POST",- headers: { Cookie: cookieHeader, "Content-Type": "application/json" },+ headers: { ...authHeader, "Content-Type": "application/json" },body: JSON.stringify(opts),});@@ -5911,12 +5932,12 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/stripe/preview-switch`, {method: "POST",- headers: { Cookie: cookieHeader, "Content-Type": "application/json" },+ headers: { ...authHeader, "Content-Type": "application/json" },body: JSON.stringify(opts),});@@ -5943,11 +5964,11 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const method = (opts.method || "GET").toUpperCase();- const headers = { Cookie: cookieHeader };+ const headers = { ...authHeader };const fetchOpts = { method, headers };if (opts.body !== undefined) {@@ -5986,11 +6007,11 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/stt-config`, {- headers: { Cookie: cookieHeader },+ headers: authHeader,});if (!response.ok) {@@ -6016,11 +6037,11 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const response = await proxyFetch(`${apiUrl}/api/note-recording-config`, {- headers: { Cookie: cookieHeader },+ headers: authHeader,});if (!response.ok) {@@ -6043,8 +6064,8 @@ class IPCHandlers {const apiUrl = getApiUrl();if (!apiUrl) throw new Error("OpenWhispr API URL not configured");- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const multipartFields = {source: "file_upload",@@ -6064,7 +6085,7 @@ class IPCHandlers {const { text, warning } = await chunkedCloudTranscribe({filePath,apiUrl,- cookieHeader,+ authHeader,multipartFields,onProgress: (payload) => event.sender.send("upload-transcription-progress", payload),});@@ -6083,7 +6104,7 @@ class IPCHandlers {multipartFields);const url = new URL(`${apiUrl}/api/transcribe`);- const data = await postMultipart(url, body, boundary, { Cookie: cookieHeader });+ const data = await postMultipart(url, body, boundary, authHeader);const result = interpretTranscribeResponse(data);return { success: true, text: result.text };@@ -6159,14 +6180,14 @@ class IPCHandlers {throw new Error("OpenWhispr API URL not configured");}- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) {- throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) {+ throw new Error("Not authenticated");}const response = await proxyFetch(`${apiUrl}/api/referrals/stats`, {headers: {- Cookie: cookieHeader,+ ...authHeader,},});@@ -6195,15 +6216,15 @@ class IPCHandlers {throw new Error("OpenWhispr API URL not configured");}- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) {- throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) {+ throw new Error("Not authenticated");}const response = await proxyFetch(`${apiUrl}/api/referrals/invite`, {method: "POST",headers: {- Cookie: cookieHeader,+ ...authHeader,"Content-Type": "application/json",},body: JSON.stringify({ email }),@@ -6233,14 +6254,14 @@ class IPCHandlers {throw new Error("OpenWhispr API URL not configured");}- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) {- throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) {+ throw new Error("Not authenticated");}const response = await proxyFetch(`${apiUrl}/api/referrals/invites`, {headers: {- Cookie: cookieHeader,+ ...authHeader,},});@@ -6423,15 +6444,15 @@ class IPCHandlers {throw new Error("OpenWhispr API URL not configured");}- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) {- throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) {+ throw new Error("Not authenticated");}const tokenResponse = await proxyFetch(`${apiUrl}/api/streaming-token`, {method: "POST",headers: {- Cookie: cookieHeader,+ ...authHeader,},});@@ -6626,12 +6647,12 @@ class IPCHandlers {const win = BrowserWindow.fromId(windowId);if (!win || win.isDestroyed()) throw new Error("Window not available for token refresh");- const cookieHeader = await getSessionCookiesFromWindow(win);- if (!cookieHeader) throw new Error("No session cookies available");+ const authHeader = await getAuthHeaderFromWindow(win);+ if (!Object.keys(authHeader).length) throw new Error("Not authenticated");const tokenResponse = await proxyFetch(`${apiUrl}/api/deepgram-streaming-token`, {method: "POST",- headers: { Cookie: cookieHeader },+ headers: authHeader,});if (!tokenResponse.ok) {@@ -6654,15 +6675,15 @@ class IPCHandlers {throw new Error("OpenWhispr API URL not configured");}- const cookieHeader = await getSessionCookies(event);- if (!cookieHeader) {- throw new Error("No session cookies available");+ const authHeader = await getAuthHeader(event);+ if (!Object.keys(authHeader).length) {+ throw new Error("Not authenticated");}const tokenResponse = await proxyFetch(`${apiUrl}/api/deepgram-streaming-token`, {method: "POST",headers: {- Cookie: cookieHeader,+ ...authHeader,},});diff --git a/src/helpers/tokenStore.js b/src/helpers/tokenStore.jsnew file mode 100644index 000000000..dd723c210--- /dev/null+++ b/src/helpers/tokenStore.js@@ -0,0 +1,49 @@+const { safeStorage, app } = require("electron");+const fs = require("fs");+const path = require("path");+const debugLogger = require("./debugLogger");++const tokenFile = () => path.join(app.getPath("userData"), "auth-token.bin");++let cached = null;++function get() {+ if (cached !== null) return cached || null;+ try {+ const file = tokenFile();+ if (!fs.existsSync(file)) return (cached = "");+ const buf = fs.readFileSync(file);+ cached = safeStorage.isEncryptionAvailable()+ ? safeStorage.decryptString(buf)+ : buf.toString("utf8");+ return cached || null;+ } catch (err) {+ debugLogger.error("tokenStore.get failed", { error: err?.message });+ cached = "";+ return null;+ }+}++function set(token) {+ try {+ const file = tokenFile();+ const data = safeStorage.isEncryptionAvailable()+ ? safeStorage.encryptString(token)+ : Buffer.from(token, "utf8");+ fs.writeFileSync(file, data, { mode: 0o600 });+ cached = token;+ } catch (err) {+ debugLogger.error("tokenStore.set failed", { error: err?.message });+ }+}++function clear() {+ cached = "";+ try {+ fs.rmSync(tokenFile(), { force: true });+ } catch (err) {+ debugLogger.error("tokenStore.clear failed", { error: err?.message });+ }+}++module.exports = { get, set, clear };diff --git a/src/lib/auth.ts b/src/lib/auth.tsindex d4a042924..457745934 100644--- a/src/lib/auth.ts+++ b/src/lib/auth.ts@@ -6,7 +6,15 @@ export const AUTH_URL = import.meta.env.VITE_AUTH_URL || "https://auth.openwhispexport const authClient = createAuthClient({baseURL: AUTH_URL,fetchOptions: {+ auth: {+ type: "Bearer",+ token: async () => (await window.electronAPI?.authGetToken?.()) ?? "",+ },headers: { "x-openwhispr-source": "desktop" },+ onSuccess: async (ctx: { response: Response }) => {+ const newToken = ctx.response.headers.get("set-auth-token");+ if (newToken) await window.electronAPI?.authSetToken?.(newToken);+ },},});@@ -121,10 +129,10 @@ export async function deleteAccount(): Promise<{ error?: Error }> {export async function signOut(): Promise<void> {try {+ await authClient.signOut();if (window.electronAPI?.authClearSession) {await window.electronAPI.authClearSession();}- await authClient.signOut();markSignedOutState();} catch {markSignedOutState();diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 06f1cc0d7..e2d274e33 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -560,7 +560,13 @@ function debouncedSaveSecret(provider: SecretProvider, key: string) {const save = api?.[SECRET_IPC_SAVERS[provider]] as| ((k: string) => Promise<unknown>)| undefined;- void save?.(key);+ save?.(key)?.catch((err) => {+ logger.warn(+ "Failed to persist secret to safeStorage",+ { provider, error: (err as Error).message },+ "settings"+ );+ });}, 250);}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 8ab1a836d..b72077fe8 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -955,6 +955,8 @@ declare global {// AuthauthClearSession?: () => Promise<void>;+ authGetToken?: () => Promise<string | null>;+ authSetToken?: (token: string) => Promise<void>;// OpenWhispr Cloud APIcloudTranscribe?: (