Skip to content

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

fix(network): route remaining GitHub/cloud/calendar fetches through Electron net (#810)

Gabriel Stein39368e7a692e
diff --git a/main.js b/main.js
index f8dca3fe1..12f38d425 100644
--- a/main.js
+++ b/main.js
@@ -23,6 +23,7 @@ const {
BrowserWindow,
dialog,
ipcMain,
+ net,
session,
systemPreferences,
} = require("electron");
@@ -525,9 +526,10 @@ function getOauthCookieName() {
// for the raw session.token the bearer plugin expects.
async function exchangeSignedTokenForRawBearer(signedToken) {
try {
- const res = await fetch(`${resolveAuthUrl()}/api/auth/get-session`, {
+ const res = await net.fetch(`${resolveAuthUrl()}/api/auth/get-session`, {
headers: { Cookie: `${getOauthCookieName()}=${signedToken}` },
signal: AbortSignal.timeout(5000),
+ useSessionCookies: false,
});
if (!res.ok) return null;
const data = await res.json();
diff --git a/src/helpers/downloadUtils.js b/src/helpers/downloadUtils.js
index 29d75d59d..0916da299 100644
--- a/src/helpers/downloadUtils.js
+++ b/src/helpers/downloadUtils.js
@@ -234,6 +234,22 @@ function downloadAttempt(url, tempPath, options) {
});
}
+async function fetchJson(url, options = {}) {
+ const headers = { "User-Agent": USER_AGENT, ...(options.headers || {}) };
+ const response = await net.fetch(url, {
+ method: "GET",
+ headers,
+ useSessionCookies: false,
+ });
+ if (!response.ok) {
+ const err = new Error(`HTTP ${response.status} fetching ${url}`);
+ err.isHttpError = true;
+ err.statusCode = response.status;
+ throw err;
+ }
+ return response.json();
+}
+
async function downloadFile(url, destPath, options = {}) {
const { onProgress, maxRetries = DEFAULT_MAX_RETRIES, signal, expectedSize = 0 } = options;
@@ -472,6 +488,7 @@ async function findFiles(dir, pattern, maxDepth = 5, depth = 0) {
module.exports = {
downloadFile,
+ fetchJson,
createDownloadSignal,
validateFileSize,
cleanupStaleDownloads,
diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.js
index 7af92c262..872233f12 100644
--- a/src/helpers/googleCalendarManager.js
+++ b/src/helpers/googleCalendarManager.js
@@ -1,5 +1,4 @@
-const https = require("https");
-const { Notification, BrowserWindow } = require("electron");
+const { net, Notification, BrowserWindow } = require("electron");
const debugLogger = require("./debugLogger");
const GoogleCalendarOAuth = require("./googleCalendarOAuth");
@@ -456,44 +455,26 @@ class GoogleCalendarManager {
async _apiGet(path, accountEmail = null) {
const accessToken = await this.oauth.getValidAccessToken(accountEmail);
const urlString = path.startsWith("http") ? path : `${CALENDAR_API_BASE}${path}`;
- const url = new URL(urlString);
-
- return new Promise((resolve, reject) => {
- const req = https.request(
- {
- hostname: url.hostname,
- port: 443,
- path: url.pathname + url.search,
- method: "GET",
- headers: {
- Authorization: `Bearer ${accessToken}`,
- },
- },
- (res) => {
- let data = "";
- res.on("data", (chunk) => (data += chunk));
- res.on("end", () => {
- try {
- const parsed = JSON.parse(data);
- if (res.statusCode >= 400) {
- const err = new Error(parsed.error?.message || `API error ${res.statusCode}`);
- err.statusCode = res.statusCode;
- reject(err);
- return;
- }
- resolve(parsed);
- } catch (e) {
- reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
- }
- });
- }
- );
- req.on("error", reject);
- req.setTimeout(10000, () => {
- req.destroy(new Error("Request timed out after 10s"));
- });
- req.end();
+
+ const response = await net.fetch(urlString, {
+ method: "GET",
+ headers: { Authorization: `Bearer ${accessToken}` },
+ signal: AbortSignal.timeout(10000),
+ useSessionCookies: false,
});
+ const text = await response.text();
+ let parsed;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
+ }
+ if (response.status >= 400) {
+ const err = new Error(parsed.error?.message || `API error ${response.status}`);
+ err.statusCode = response.status;
+ throw err;
+ }
+ return parsed;
}
}
diff --git a/src/helpers/googleCalendarOAuth.js b/src/helpers/googleCalendarOAuth.js
index 6a55be7fa..352a2f5da 100644
--- a/src/helpers/googleCalendarOAuth.js
+++ b/src/helpers/googleCalendarOAuth.js
@@ -1,7 +1,6 @@
const http = require("http");
-const https = require("https");
const crypto = require("crypto");
-const { shell } = require("electron");
+const { net, shell } = require("electron");
const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -226,36 +225,19 @@ class GoogleCalendarOAuth {
}
}
- _httpsPost(urlString, body) {
- const url = new URL(urlString);
- return new Promise((resolve, reject) => {
- const req = https.request(
- {
- hostname: url.hostname,
- port: 443,
- path: url.pathname,
- method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded",
- "Content-Length": Buffer.byteLength(body),
- },
- },
- (res) => {
- let data = "";
- res.on("data", (chunk) => (data += chunk));
- res.on("end", () => {
- try {
- resolve(JSON.parse(data));
- } catch (e) {
- reject(new Error(`Invalid JSON response: ${data.slice(0, 200)}`));
- }
- });
- }
- );
- req.on("error", reject);
- req.write(body);
- req.end();
+ async _httpsPost(urlString, body) {
+ const response = await net.fetch(urlString, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body,
+ useSessionCookies: false,
});
+ const text = await response.text();
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
+ }
}
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 36233c732..1a54bb21b 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -2,8 +2,6 @@ const { ipcMain, app, shell, BrowserWindow, systemPreferences, net } = require("
const path = require("path");
const fs = require("fs");
const os = require("os");
-const http = require("http");
-const https = require("https");
const crypto = require("crypto");
const debugLogger = require("./debugLogger");
const tokenStore = require("./tokenStore");
@@ -110,37 +108,23 @@ function buildMultipartBody(fileBuffer, fileName, contentType, fields = {}) {
return { body: Buffer.concat(bodyParts), boundary };
}
-function postMultipart(url, body, boundary, headers = {}) {
- const httpModule = url.protocol === "https:" ? https : http;
- return new Promise((resolve, reject) => {
- const req = httpModule.request(
- {
- hostname: url.hostname,
- port: url.port || (url.protocol === "https:" ? 443 : 80),
- path: url.pathname,
- method: "POST",
- headers: {
- "Content-Type": `multipart/form-data; boundary=${boundary}`,
- "Content-Length": body.length,
- ...headers,
- },
- },
- (res) => {
- let responseData = "";
- res.on("data", (chunk) => (responseData += chunk));
- res.on("end", () => {
- try {
- resolve({ statusCode: res.statusCode, data: JSON.parse(responseData) });
- } catch (e) {
- reject(new Error(`Invalid JSON response: ${responseData.slice(0, 200)}`));
- }
- });
- }
- );
- req.on("error", reject);
- req.write(body);
- req.end();
+async function postMultipart(url, body, boundary, headers = {}) {
+ const response = await net.fetch(url.toString(), {
+ method: "POST",
+ headers: {
+ "Content-Type": `multipart/form-data; boundary=${boundary}`,
+ "Content-Length": String(body.length),
+ ...headers,
+ },
+ body,
+ useSessionCookies: false,
});
+ const text = await response.text();
+ try {
+ return { statusCode: response.status, data: JSON.parse(text) };
+ } catch {
+ throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
+ }
}
function interpretTranscribeResponse(data) {
diff --git a/src/helpers/llamaVulkanManager.js b/src/helpers/llamaVulkanManager.js
index 5ab11b0dd..0bb598f5e 100644
--- a/src/helpers/llamaVulkanManager.js
+++ b/src/helpers/llamaVulkanManager.js
@@ -5,6 +5,7 @@ const { app } = require("electron");
const debugLogger = require("./debugLogger");
const {
downloadFile,
+ fetchJson,
createDownloadSignal,
checkDiskSpace,
cleanupStaleDownloads,
@@ -13,6 +14,13 @@ const {
findFiles,
} = require("./downloadUtils");
+function githubReleaseHeaders() {
+ const headers = { Accept: "application/vnd.github+json" };
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
+ if (token) headers.Authorization = `Bearer ${token}`;
+ return headers;
+}
+
const GITHUB_RELEASE_URL = "https://api.github.com/repos/ggerganov/llama.cpp/releases/latest";
const VULKAN_ASSETS = {
@@ -86,7 +94,7 @@ class LlamaVulkanManager {
await fsPromises.mkdir(this.binDir, { recursive: true });
await cleanupStaleDownloads(this.binDir);
- const release = await this._fetchJson(GITHUB_RELEASE_URL);
+ const release = await fetchJson(GITHUB_RELEASE_URL, { headers: githubReleaseHeaders() });
if (!release?.assets) throw new Error("Could not fetch llama.cpp release info");
const config = this._getConfig();
@@ -171,42 +179,6 @@ class LlamaVulkanManager {
debugLogger.info("Vulkan llama-server deleted", { deletedCount });
return { success: true, deletedCount };
}
-
- _fetchJson(url) {
- const https = require("https");
- return new Promise((resolve, reject) => {
- const headers = {
- "User-Agent": "OpenWhispr/1.0",
- Accept: "application/vnd.github+json",
- };
- const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
- if (token) headers.Authorization = `Bearer ${token}`;
-
- https
- .get(url, { headers, timeout: 15000 }, (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
- res.resume();
- this._fetchJson(res.headers.location).then(resolve, reject);
- return;
- }
- if (res.statusCode !== 200) {
- res.resume();
- reject(new Error(`GitHub API returned ${res.statusCode}`));
- return;
- }
- let data = "";
- res.on("data", (chunk) => (data += chunk));
- res.on("end", () => {
- try {
- resolve(JSON.parse(data));
- } catch {
- reject(new Error("Failed to parse GitHub release JSON"));
- }
- });
- })
- .on("error", reject);
- });
- }
}
module.exports = LlamaVulkanManager;
diff --git a/src/helpers/whisperCudaManager.js b/src/helpers/whisperCudaManager.js
index 187c28b7e..8c08389eb 100644
--- a/src/helpers/whisperCudaManager.js
+++ b/src/helpers/whisperCudaManager.js
@@ -1,11 +1,11 @@
const fs = require("fs");
const { promises: fsPromises } = require("fs");
const path = require("path");
-const https = require("https");
const { app } = require("electron");
const debugLogger = require("./debugLogger");
const {
downloadFile,
+ fetchJson,
createDownloadSignal,
checkDiskSpace,
cleanupStaleDownloads,
@@ -72,7 +72,9 @@ class WhisperCudaManager {
throw new Error(`CUDA binaries not available for ${process.platform}`);
}
- const release = await this._fetchJson(GITHUB_RELEASE_URL);
+ const release = await fetchJson(GITHUB_RELEASE_URL, {
+ headers: { Accept: "application/vnd.github+json" },
+ });
const assetName = PLATFORM_ASSET_NAMES[process.platform];
const asset = release.assets?.find((a) => a.name === assetName);
@@ -238,56 +240,6 @@ class WhisperCudaManager {
freed_mb: Math.round(freedBytes / (1024 * 1024)),
};
}
-
- _fetchJson(url) {
- return new Promise((resolve, reject) => {
- https
- .get(
- url,
- {
- headers: {
- "User-Agent": "OpenWhispr/1.0",
- Accept: "application/vnd.github+json",
- },
- timeout: 15000,
- },
- (res) => {
- if (res.statusCode >= 300 && res.statusCode < 400) {
- const location = res.headers.location;
- if (!location) {
- reject(new Error("Redirect without location header"));
- return;
- }
- res.resume();
- this._fetchJson(location).then(resolve, reject);
- return;
- }
-
- if (res.statusCode !== 200) {
- res.resume();
- reject(new Error(`GitHub API returned HTTP ${res.statusCode}`));
- return;
- }
-
- let data = "";
- res.on("data", (chunk) => (data += chunk));
- res.on("end", () => {
- try {
- resolve(JSON.parse(data));
- } catch (e) {
- reject(new Error(`Failed to parse GitHub API response: ${e.message}`));
- }
- });
- res.on("error", reject);
- }
- )
- .on("error", reject)
- .on("timeout", function () {
- this.destroy();
- reject(new Error("GitHub API request timed out"));
- });
- });
- }
}
module.exports = WhisperCudaManager;