Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(desktop): trust the OS certificate store behind TLS-intercepting proxies

Samrat Talukdard87df5bc8fb1
diff --git a/apps/desktop/electron/external-fetch.mjs b/apps/desktop/electron/external-fetch.mjs
new file mode 100644
index 00000000..df307e1c
--- /dev/null
+++ b/apps/desktop/electron/external-fetch.mjs
@@ -0,0 +1,67 @@
+/**
+ * The Electron main process's fetch for everything that leaves the machine.
+ *
+ * Node's global fetch, which is undici, verifies TLS against Node's own roots, so a
+ * TLS-intercepting antivirus or corporate proxy whose root CA sits only in
+ * the OS store (Windows certificate store, macOS keychain, the distro/NSS
+ * store) fails with "self signed certificate in certificate chain". Electron's
+ * net.fetch goes through Chromium's network stack instead: the OS verifier
+ * and trust store, the system proxy, and the session's certificate verify
+ * proc, with full certificate verification.
+ *
+ * Loopback targets (the embedded server, local development APIs) stay on
+ * Node's fetch, where CA trust is irrelevant.
+ */
+
+const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
+
+/**
+ * @typedef {(input: string | URL | Request, init?: RequestInit) => Promise<Response>} ExternalFetch
+ */
+
+/**
+ * @param {unknown} input
+ * @returns {string | null}
+ */
+export function requestUrl(input) {
+ if (typeof input === "string") return input;
+ if (input instanceof URL) return input.href;
+ if (input && typeof input === "object" && "url" in input && typeof input.url === "string") return input.url;
+ return null;
+}
+
+/**
+ * @param {unknown} input
+ * @returns {boolean}
+ */
+export function isLoopbackUrl(input) {
+ const raw = requestUrl(input);
+ if (!raw) return false;
+ try {
+ const { hostname } = new URL(raw);
+ return LOOPBACK_HOSTNAMES.has(hostname) || /^127(?:\.\d{1,3}){3}$/.test(hostname);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * @param {{
+ * net?: { fetch?: (input: string | Request, init?: RequestInit) => Promise<Response> } | null,
+ * isReady?: () => boolean,
+ * nodeFetch?: typeof globalThis.fetch,
+ * }} options
+ * @returns {ExternalFetch}
+ */
+export function createExternalFetch({ net, isReady = () => true, nodeFetch = globalThis.fetch }) {
+ return function externalFetch(input, init = {}) {
+ // Tests, standalone runs and anything before app ready have no net module.
+ if (isLoopbackUrl(input) || typeof net?.fetch !== "function" || !isReady()) {
+ return nodeFetch(input, init);
+ }
+ const url = input instanceof URL ? input.href : input;
+ // Main-process calls authenticate with bearer tokens; never attach the
+ // default session's cookies to them.
+ return net.fetch(/** @type {string | Request} */ (url), { credentials: "omit", ...init });
+ };
+}
diff --git a/apps/desktop/electron/external-fetch.test.mjs b/apps/desktop/electron/external-fetch.test.mjs
new file mode 100644
index 00000000..95a9acbe
--- /dev/null
+++ b/apps/desktop/electron/external-fetch.test.mjs
@@ -0,0 +1,60 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { createExternalFetch, isLoopbackUrl, requestUrl } from "./external-fetch.mjs";
+
+function recorder() {
+ const calls = [];
+ const fn = async (input, init) => {
+ calls.push({ input, init });
+ return new Response("ok");
+ };
+ return { calls, fn };
+}
+
+test("classifies loopback targets", () => {
+ for (const url of ["http://127.0.0.1:8787/x", "http://localhost:8090/omnirush/v1", "http://[::1]:3000/", "http://127.4.5.6/", new URL("http://localhost/")]) {
+ assert.equal(isLoopbackUrl(url), true, String(url));
+ }
+ for (const url of ["https://omnirush.ai/omnirush/v1", "https://localhost.example/", "http://10.0.0.2/", "not a url", null]) {
+ assert.equal(isLoopbackUrl(url), false, String(url));
+ }
+ assert.equal(requestUrl(new Request("https://omnirush.ai/a")), "https://omnirush.ai/a");
+});
+
+test("requests off the machine go through Electron's net.fetch without cookies", async () => {
+ const net = recorder();
+ const node = recorder();
+ const externalFetch = createExternalFetch({ net: { fetch: net.fn }, nodeFetch: node.fn });
+
+ await externalFetch(new URL("https://omnirush.ai/omnirush/v1/device/authorize"), { method: "POST", body: "{}" });
+ await externalFetch("https://omnirush.ai/omnirush/v1/me", { credentials: "include" });
+
+ assert.equal(node.calls.length, 0);
+ assert.deepEqual(net.calls.map((call) => call.input), [
+ "https://omnirush.ai/omnirush/v1/device/authorize",
+ "https://omnirush.ai/omnirush/v1/me",
+ ]);
+ assert.equal(net.calls[0].init.credentials, "omit");
+ assert.equal(net.calls[0].init.method, "POST");
+ assert.equal(net.calls[1].init.credentials, "include");
+});
+
+test("loopback targets, and calls before app ready or without net, stay on Node's fetch", async () => {
+ const net = recorder();
+ const node = recorder();
+ let ready = false;
+ const externalFetch = createExternalFetch({ net: { fetch: net.fn }, nodeFetch: node.fn, isReady: () => ready });
+
+ await externalFetch("https://omnirush.ai/");
+ ready = true;
+ await externalFetch("http://127.0.0.1:8787/health");
+ await createExternalFetch({ net: null, nodeFetch: node.fn })("https://omnirush.ai/");
+
+ assert.equal(net.calls.length, 0);
+ assert.deepEqual(node.calls.map((call) => String(call.input)), [
+ "https://omnirush.ai/",
+ "http://127.0.0.1:8787/health",
+ "https://omnirush.ai/",
+ ]);
+});
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 7865c6b2..de3a0548 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -84,6 +84,7 @@ import { readSkillFolder } from "./skill-folder.mjs";
import { createDesktopVaultKeyProvider } from "./secure-vault-key.mjs";
import { applyLinuxPasswordStore, recordLinuxPasswordStore } from "./linux-password-store.mjs";
import { createDesktopOmniRushAccountStore, legacyKeychainAllowed } from "./omnirush-account.mjs";
+import { createExternalFetch } from "./external-fetch.mjs";
import {
clearOmniRushSentrySession,
initOmniRushSentry,
@@ -118,6 +119,9 @@ const {
systemPreferences,
} = require("electron");
const pty = require(["node", "pty"].join("-"));
+// Chromium's network stack (OS trust store, system proxy) for the main
+// process's own requests off the machine; see external-fetch.mjs.
+const desktopExternalFetch = createExternalFetch({ net: electronNet, isReady: () => app.isReady() });
const NATIVE_DEEP_LINK_EVENT = "omnirush:deep-link-native";
const AUTOMATION_RUNNER_CREDENTIAL_REJECTED_EVENT = "omnirush:automation-runner:credential-rejected";
const isDevMode = process.env.OMNIRUSH_DEV_MODE === "1";
@@ -1328,6 +1332,8 @@ function validateSkillName(raw) {
const omnirushAccountStore = createDesktopOmniRushAccountStore({
filePath: path.join(app.getPath("userData"), "omnirush-account.bin"),
+ // 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.
fallbackFilePath: path.join(app.getPath("userData"), "private-credentials", "omnirush-account.json"),
@@ -1353,6 +1359,7 @@ function omnirushUiMcpLaunch() {
const runtimeManager = createRuntimeManager({
app,
desktopRoot: path.resolve(__dirname, ".."),
+ externalFetch: desktopExternalFetch,
// Rewrites persisted `npx -y omnirush-ui-mcp` entries to the bundled launch
// before the engine starts. Null (bundle missing) removes them instead.
omnirushUiMcpLaunch: () => {
@@ -1388,6 +1395,8 @@ const legacyRunnerBaseUrls = [
DEFAULT_DEN_BASE_URL ? `${DEFAULT_DEN_BASE_URL}/api/den` : null,
].map((value) => normalizeRunnerBaseUrl(value)).filter(Boolean);
const desktopAutomationRunner = createDesktopAutomationRunner({
+ // Den polling leaves the machine; the local runtime calls stay on loopback.
+ fetchImpl: desktopExternalFetch,
// v1 credentials predate token audiences. Keep them usable during the Den
// rollout only for endpoints trusted before the renderer starts issuing IPC.
legacyBaseUrls: legacyRunnerBaseUrls,
diff --git a/apps/desktop/electron/runtime-ca.test.mjs b/apps/desktop/electron/runtime-ca.test.mjs
index 766d364b..fe7c83f9 100644
--- a/apps/desktop/electron/runtime-ca.test.mjs
+++ b/apps/desktop/electron/runtime-ca.test.mjs
@@ -191,32 +191,50 @@ test("keeps NODE_EXTRA_CA_CERTS from user env file over generated bundle", () =>
assert.equal(childEnv.NODE_EXTRA_CA_CERTS, "/user/file-ca.pem");
});
-test("respects user-set NODE_EXTRA_CA_CERTS", async () => {
+test("merges a user-set NODE_EXTRA_CA_CERTS with the OS store, in process and for children", async () => {
const userDataDir = await mkdtemp(path.join(tmpdir(), "omnirush-runtime-ca-"));
- let called = false;
+ const configured = path.join(userDataDir, "custom-ca.pem");
+ await writeFile(configured, `${CERT_THREE}\n`);
let logged = false;
+ const setDefaultCalls = [];
const env = await resolveSystemCaEnv({
tlsModule: {
- getCACertificates() {
- called = true;
- return [CERT_ONE];
+ getCACertificates(scope) {
+ return scope === "default" ? ["default-root"] : [CERT_ONE];
+ },
+ setDefaultCACertificates(certs) {
+ setDefaultCalls.push(certs);
},
},
userDataDir,
- parentEnv: { NODE_EXTRA_CA_CERTS: "/custom/ca.pem" },
+ parentEnv: { NODE_EXTRA_CA_CERTS: configured },
logInfo(message) {
- logged = String(message).includes("NODE_EXTRA_CA_CERTS is already set");
- },
- loadPlatformCertificates: async () => {
- called = true;
- return [CERT_TWO];
+ logged ||= String(message).includes("NODE_EXTRA_CA_CERTS is already set");
},
+ loadPlatformCertificates: async () => [CERT_TWO],
});
- assert.deepEqual(env, {});
- assert.equal(called, false);
+ const bundlePath = path.join(userDataDir, "system-ca-bundle.pem");
+ assert.deepEqual(env, { NODE_EXTRA_CA_CERTS: bundlePath });
+ assert.equal(await readFile(bundlePath, "utf8"), `${CERT_THREE}\n${CERT_ONE}\n${CERT_TWO}\n`);
assert.equal(logged, true);
+ assert.deepEqual(setDefaultCalls, [["default-root", CERT_THREE, CERT_ONE, CERT_TWO]]);
+ // The bundle replaces the user's value only while it is the file it was built from.
+ assert.equal(mergeSystemCaChildEnv({ NODE_EXTRA_CA_CERTS: configured }, env, {}, configured).NODE_EXTRA_CA_CERTS, bundlePath);
+ assert.equal(mergeSystemCaChildEnv({ NODE_EXTRA_CA_CERTS: "/changed/ca.pem" }, env, {}, configured).NODE_EXTRA_CA_CERTS, "/changed/ca.pem");
+});
+
+test("keeps an unreadable user-set NODE_EXTRA_CA_CERTS for children as is", async () => {
+ const userDataDir = await mkdtemp(path.join(tmpdir(), "omnirush-runtime-ca-"));
+ const env = await resolveSystemCaEnv({
+ tlsModule: { getCACertificates: () => [CERT_ONE] },
+ userDataDir,
+ parentEnv: { NODE_EXTRA_CA_CERTS: path.join(userDataDir, "missing.pem") },
+ logInfo: () => {},
+ loadPlatformCertificates: async () => [],
+ });
+ assert.deepEqual(env, {});
});
test("no-ops when tls.getCACertificates is unavailable", async () => {
diff --git a/apps/desktop/electron/runtime-chain-repair.test.mjs b/apps/desktop/electron/runtime-chain-repair.test.mjs
index 1997dc79..1693957a 100644
--- a/apps/desktop/electron/runtime-chain-repair.test.mjs
+++ b/apps/desktop/electron/runtime-chain-repair.test.mjs
@@ -240,7 +240,7 @@ test("user NODE_EXTRA_CA_CERTS disables repair", async () => {
userDataDir,
parentEnv: { NODE_EXTRA_CA_CERTS: "/custom/ca.pem" },
logInfo(message) {
- logged = String(message).includes("NODE_EXTRA_CA_CERTS is already set");
+ logged ||= String(message).includes("NODE_EXTRA_CA_CERTS is set");
},
loadPlatformCertificates: async () => [systemCert],
chainRepair: {
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index f111dc58..6bc4a24c 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -23,6 +23,7 @@ import {
} from "@omnirush/paths";
import {
dedupeCertificates,
+ extendDefaultCaCertificates,
resolveSystemCaBundle,
summarizeSystemCaSources,
systemPlatformCertificateLoader,
@@ -1277,9 +1278,12 @@ async function repairIncompleteChains(options) {
}
}
+const CONFIGURED_EXTRA_CA_MESSAGE = "OmniRush.ai runtime: NODE_EXTRA_CA_CERTS is already set; child processes get it merged with the OS trust store.";
+const UNREADABLE_EXTRA_CA_MESSAGE = "OmniRush.ai runtime: NODE_EXTRA_CA_CERTS is set but unreadable; child processes keep it as is.";
+
/**
* @param {ResolveSystemCaEnvOptions} options
- * @returns {Promise<{ childEnv: NodeJS.ProcessEnv, trustedCertificates: string[] }>}
+ * @returns {Promise<{ childEnv: NodeJS.ProcessEnv, trustedCertificates: string[], mergedFrom: string | null }>}
*/
async function resolveSystemCa({
tlsModule = tls,
@@ -1292,17 +1296,26 @@ async function resolveSystemCa({
chainRepair,
}) {
const env = parentEnv ?? {};
- if (Object.prototype.hasOwnProperty.call(env, "NODE_EXTRA_CA_CERTS")) {
- if (typeof logInfo === "function") {
- logInfo("OmniRush.ai runtime: NODE_EXTRA_CA_CERTS is already set; skipping system CA bundle export.");
- }
+ const info = (message) => {
+ if (typeof logInfo === "function") logInfo(message);
+ };
+ // A user-set NODE_EXTRA_CA_CERTS is kept: child processes get its
+ // certificates merged with the OS trust store, and this process adds both.
+ const configuredPath = Object.prototype.hasOwnProperty.call(env, "NODE_EXTRA_CA_CERTS")
+ ? String(env.NODE_EXTRA_CA_CERTS)
+ : null;
+ /** @type {string[]} */
+ let configuredCertificates = [];
+ let configuredReadable = false;
+ if (configuredPath !== null) {
try {
- const configuredPem = await readFile(String(env.NODE_EXTRA_CA_CERTS), "utf8");
- return { childEnv: {}, trustedCertificates: parsePemCertificates(configuredPem) };
+ configuredCertificates = parsePemCertificates(await readFile(configuredPath, "utf8"));
+ configuredReadable = true;
} catch {
- return { childEnv: {}, trustedCertificates: [] };
+ configuredCertificates = [];
}
}
+ const mergedFrom = configuredReadable ? configuredPath : null;
try {
const platformLoader = loadPlatformCertificates
@@ -1316,12 +1329,12 @@ async function resolveSystemCa({
},
platform: platformLoader,
});
- if (typeof logInfo === "function") {
- logInfo(`OmniRush.ai runtime: system CA bundle sources ${summarizeSystemCaSources(bundle.sources)}`);
- }
+ info(`OmniRush.ai runtime: system CA bundle sources ${summarizeSystemCaSources(bundle.sources)}`);
+ const trustedCertificates = dedupeCertificates([...configuredCertificates, ...bundle.certificates]);
let repairedPems = [];
try {
- const repaired = await repairIncompleteChains({
+ // Chain repair stays off when the user manages NODE_EXTRA_CA_CERTS.
+ const repaired = configuredPath !== null ? { pems: [], timedOut: false } : await repairIncompleteChains({
tlsModule,
userDataDir,
parentEnv: env,
@@ -1332,33 +1345,41 @@ async function resolveSystemCa({
chainRepair,
});
repairedPems = repaired.pems;
- if (repaired.timedOut && typeof logInfo === "function") {
- logInfo("OmniRush.ai runtime: chain repair skipped: timed out");
- }
+ if (repaired.timedOut) info("OmniRush.ai runtime: chain repair skipped: timed out");
} catch {
repairedPems = [];
}
- const certificates = dedupeCertificates([...bundle.certificates, ...repairedPems]);
- if (certificates.length === 0) return { childEnv: {}, trustedCertificates: bundle.certificates };
- if (typeof tlsModule?.getCACertificates === "function" && typeof tlsModule?.setDefaultCACertificates === "function") {
- try {
- const defaultCerts = tlsModule.getCACertificates("default");
- tlsModule.setDefaultCACertificates(dedupeCertificates([...(Array.isArray(defaultCerts) ? defaultCerts : []), ...certificates]));
- } catch {
- // Best-effort only; child processes still receive NODE_EXTRA_CA_CERTS.
- }
+ const certificates = dedupeCertificates([...trustedCertificates, ...repairedPems]);
+ if (certificates.length === 0) return { childEnv: {}, trustedCertificates, mergedFrom: null };
+
+ const trust = extendDefaultCaCertificates(tlsModule, certificates);
+ if (trust.applied) {
+ info(`OmniRush.ai runtime: main-process TLS trusts ${trust.certificates.length} OS certificates${trust.rejected ? ` (skipped ${trust.rejected} the TLS library cannot parse)` : ""}`);
+ } else if (typeof tlsModule?.setDefaultCACertificates === "function") {
+ info(`OmniRush.ai runtime: main-process TLS trust unchanged: ${trust.error ?? "unknown error"}`);
+ }
+ if (configuredPath !== null && !configuredReadable) {
+ info(UNREADABLE_EXTRA_CA_MESSAGE);
+ return { childEnv: {}, trustedCertificates, mergedFrom: null };
}
- const pem = certificates.join("\n");
- if (!pem) return { childEnv: {}, trustedCertificates: bundle.certificates };
+ if (configuredPath !== null) info(CONFIGURED_EXTRA_CA_MESSAGE);
+
+ // Child processes (Node, and Bun, which honors NODE_EXTRA_CA_CERTS too)
+ // get the certificates as a PEM file, including a user-set
+ // NODE_EXTRA_CA_CERTS file's. Unparsable entries are left out: a single
+ // bad certificate makes Node and Bun ignore the whole file.
+ const pem = trust.certificates.join("\n");
+ if (!pem) return { childEnv: {}, trustedCertificates, mergedFrom: null };
const bundlePath = path.join(userDataDir, "system-ca-bundle.pem");
await mkdir(path.dirname(bundlePath), { recursive: true });
await writeFile(bundlePath, `${pem}\n`, "utf8");
return {
childEnv: { NODE_EXTRA_CA_CERTS: bundlePath },
- trustedCertificates: bundle.certificates,
+ trustedCertificates,
+ mergedFrom,
};
} catch {
- return { childEnv: {}, trustedCertificates: [] };
+ return { childEnv: {}, trustedCertificates: configuredCertificates, mergedFrom: null };
}
}
@@ -1370,12 +1391,17 @@ export async function resolveSystemCaEnv(options) {
* @param {NodeJS.ProcessEnv} [baseEnv]
* @param {NodeJS.ProcessEnv} [caEnv]
* @param {NodeJS.ProcessEnv} [extra]
+ * @param {string | null} [mergedFrom] the user-set NODE_EXTRA_CA_CERTS the generated bundle includes
* @returns {NodeJS.ProcessEnv}
*/
-export function mergeSystemCaChildEnv(baseEnv = {}, caEnv = {}, extra = {}) {
+export function mergeSystemCaChildEnv(baseEnv = {}, caEnv = {}, extra = {}, mergedFrom = null) {
+ // The generated bundle replaces a user-set NODE_EXTRA_CA_CERTS only when it
+ // was built from that same file (a superset of it). A value that changed
+ // since startup, or one the bundle does not include, is kept.
+ const userSet = Object.prototype.hasOwnProperty.call(baseEnv, "NODE_EXTRA_CA_CERTS");
return {
...baseEnv,
- ...(Object.prototype.hasOwnProperty.call(baseEnv, "NODE_EXTRA_CA_CERTS") ? {} : caEnv),
+ ...(!userSet || (mergedFrom !== null && String(baseEnv.NODE_EXTRA_CA_CERTS) === mergedFrom) ? caEnv : {}),
...extra,
};
}
@@ -1390,6 +1416,8 @@ export function createRuntimeManager({
omnirushUiMcpLaunch = () => null,
workspaceMkdir = mkdir,
workspacePlatform = process.platform,
+ // Chromium-backed fetch for requests off the machine (see external-fetch.mjs).
+ externalFetch = null,
}) {
const inheritedProcessEnv = { ...process.env };
let injectedUserEnvKeys = new Set();
@@ -1434,6 +1462,8 @@ export function createRuntimeManager({
tlsModule: tls,
userDataDir,
parentEnv: { ...loadUserEnvFile(process.env), ...process.env },
+ // AIA intermediate downloads for chain repair.
+ chainRepair: typeof externalFetch === "function" ? { fetchImpl: externalFetch } : undefined,
});
return systemCaPromise;
}
@@ -1584,10 +1614,10 @@ export function createRuntimeManager({
...process.env,
BUN_CONFIG_DNS_RESULT_ORDER: "verbatim",
};
- const caEnv = Object.prototype.hasOwnProperty.call(baseEnv, "NODE_EXTRA_CA_CERTS") ? {} : (await systemCa()).childEnv;
+ const { childEnv: caEnv, mergedFrom } = await systemCa();
// Bun honors Node's NODE_EXTRA_CA_CERTS, so bundled Bun sidecars inherit
// the exported OS trust store through the same child env variable.
- const env = mergeSystemCaChildEnv(baseEnv, caEnv, extra);
+ const env = mergeSystemCaChildEnv(baseEnv, caEnv, extra, mergedFrom);
const pathKey =
Object.prototype.hasOwnProperty.call(env, "PATH") ||
!Object.prototype.hasOwnProperty.call(env, "Path")
diff --git a/apps/desktop/electron/system-ca-trust.test.mjs b/apps/desktop/electron/system-ca-trust.test.mjs
new file mode 100644
index 00000000..22db23c1
--- /dev/null
+++ b/apps/desktop/electron/system-ca-trust.test.mjs
@@ -0,0 +1,98 @@
+// Node's own TLS (fetch/undici, https, and child processes) behind a
+// TLS-intercepting proxy whose root is only in the OS trust store.
+import assert from "node:assert/strict";
+import { execFile, execFileSync } from "node:child_process";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import https from "node:https";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+import tls from "node:tls";
+import { promisify } from "node:util";
+
+import { resolveSystemCaEnv } from "./runtime.mjs";
+import { commandEnv, extendDefaultCaCertificates, isUsableCaCertificate } from "./system-ca.mjs";
+
+const UNPARSABLE = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----";
+
+async function interceptionFixture() {
+ const directory = await mkdtemp(path.join(tmpdir(), "omnirush-intercept-"));
+ const run = (...args) => execFileSync("openssl", args, { cwd: directory, stdio: "ignore" });
+ await writeFile(path.join(directory, "root.ext"), "basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n");
+ run("req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", "root.key", "-out", "root.csr", "-subj", "/CN=Test Interception Root");
+ run("x509", "-req", "-in", "root.csr", "-signkey", "root.key", "-out", "root.pem", "-days", "2", "-sha256", "-extfile", "root.ext");
+ await writeFile(path.join(directory, "leaf.ext"), "extendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost\n");
+ run("req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", "leaf.key", "-out", "leaf.csr", "-subj", "/CN=localhost");
+ run("x509", "-req", "-in", "leaf.csr", "-CA", "root.pem", "-CAkey", "root.key", "-set_serial", "9", "-out", "leaf.pem", "-days", "1", "-sha256", "-extfile", "leaf.ext");
+ const root = await readFile(path.join(directory, "root.pem"), "utf8");
+ const leaf = await readFile(path.join(directory, "leaf.pem"), "utf8");
+ // Interception products serve their root in the chain.
+ const server = https.createServer({ key: await readFile(path.join(directory, "leaf.key")), cert: `${leaf}${root}` }, (_request, response) => response.end("ok"));
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined)));
+ const address = server.address();
+ return { directory, root: root.trim(), url: `https://localhost:${typeof address === "object" && address ? address.port : 0}/`, close: () => server.close() };
+}
+
+test("extendDefaultCaCertificates keeps the parsable roots when one certificate is rejected", () => {
+ const calls = [];
+ const tlsModule = {
+ getCACertificates: () => ["bundled"],
+ setDefaultCACertificates(certs) {
+ calls.push(certs);
+ if (certs.includes("bad")) throw new Error("PEM routines");
+ },
+ };
+ const result = extendDefaultCaCertificates(tlsModule, ["good-1", "bad", "good-2"], (pem) => pem !== "bad");
+ assert.deepEqual(result, { applied: true, certificates: ["good-1", "good-2"], rejected: 1, error: null });
+ assert.deepEqual(calls.at(-1), ["bundled", "good-1", "good-2"]);
+});
+
+test("isUsableCaCertificate rejects what the TLS library cannot parse", async () => {
+ const fixture = await interceptionFixture();
+ fixture.close();
+ assert.equal(isUsableCaCertificate(fixture.root), true);
+ assert.equal(isUsableCaCertificate(UNPARSABLE), false);
+});
+
+test("Node fetch and Node child processes trust an OS-store interception root after startup", async () => {
+ const fixture = await interceptionFixture();
+ try {
+ // The reported failure: Node's bundled roots reject the intercepted chain.
+ await assert.rejects(fetch(fixture.url), (/** @type {any} */ error) => /self[- ]signed certificate in certificate chain/i.test(String(error?.cause?.message)));
+
+ const userDataDir = await mkdtemp(path.join(tmpdir(), "omnirush-system-ca-"));
+ const logs = [];
+ const childEnv = await resolveSystemCaEnv({
+ tlsModule: tls,
+ userDataDir,
+ parentEnv: {},
+ logInfo: (message) => logs.push(String(message)),
+ // The OS store as enumerated: one entry BoringSSL/OpenSSL refuses, and the interception root.
+ loadPlatformCertificates: async () => [UNPARSABLE, fixture.root],
+ platformSourceName: "test-store",
+ chainRepair: { disabled: true },
+ });
+
+ const response = await fetch(fixture.url);
+ assert.equal(await response.text(), "ok");
+ assert.ok(logs.some((line) => /main-process TLS trusts \d+ OS certificates \(skipped 1 /.test(line)), logs.join("\n"));
+
+ const bundle = await readFile(String(childEnv.NODE_EXTRA_CA_CERTS), "utf8");
+ assert.ok(bundle.includes(fixture.root));
+ assert.ok(!bundle.includes(UNPARSABLE));
+
+ // Asynchronous: the fixture server runs on this event loop.
+ const child = await promisify(execFile)(process.execPath, ["-e", `fetch(${JSON.stringify(fixture.url)}).then(async (r) => console.log(await r.text()), (e) => { console.log(e.cause?.message); process.exitCode = 1; })`], {
+ env: { ...process.env, ...childEnv },
+ encoding: "utf8",
+ });
+ assert.equal(child.stdout.trim(), "ok", child.stdout + child.stderr);
+ } finally {
+ fixture.close();
+ }
+});
+
+test("trust-store commands do not inherit a PowerShell 7 module path", () => {
+ assert.deepEqual(commandEnv({ Path: "C:\\Windows", PSModulePath: "C:\\pwsh7\\Modules", SystemRoot: "C:\\Windows" }), { Path: "C:\\Windows", SystemRoot: "C:\\Windows" });
+ assert.deepEqual(commandEnv({ PSMODULEPATH: "x", HOME: "/home/u" }), { HOME: "/home/u" });
+});
diff --git a/apps/desktop/electron/system-ca.mjs b/apps/desktop/electron/system-ca.mjs
index 4a4c91fc..521c47f3 100644
--- a/apps/desktop/electron/system-ca.mjs
+++ b/apps/desktop/electron/system-ca.mjs
@@ -1,4 +1,6 @@
import { spawn } from "node:child_process";
+import { X509Certificate } from "node:crypto";
+import tls from "node:tls";
const COMMAND_TIMEOUT_MS = 10_000;
const OUTPUT_LIMIT_CHARS = 8 * 1024 * 1024;
@@ -90,6 +92,18 @@ export function parseDarwinSecurityCertificates(output) {
return dedupeCertificates(certs);
}
+/**
+ * The environment for the trust-store commands. Windows PowerShell 5.1 cannot
+ * load its own modules, and so has no Cert: drive, with the PSModulePath that
+ * PowerShell 7 exports to anything started from it (the app launched from a
+ * pwsh terminal); without the variable it rebuilds its default module path.
+ * @param {NodeJS.ProcessEnv} env
+ * @returns {NodeJS.ProcessEnv}
+ */
+export function commandEnv(env) {
+ return Object.fromEntries(Object.entries(env).filter(([key]) => key.toUpperCase() !== "PSMODULEPATH"));
+}
+
/**
* @param {string} command
* @param {string[]} args
@@ -100,7 +114,7 @@ export function runCommand(command, args, windowsHide) {
return new Promise((resolve) => {
let child;
try {
- child = spawn(command, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide });
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "ignore"], windowsHide, env: commandEnv(process.env) });
} catch {
resolve(null);
return;
@@ -221,3 +235,75 @@ export function summarizeSystemCaSources(sources) {
if (sources.length === 0) return "no OS trust sources returned certificates";
return sources.map((source) => `${source.name}=${source.count}`).join(" ");
}
+
+/**
+ * @typedef {Object} DefaultCaTlsModule
+ * @property {(type?: string) => string[]} [getCACertificates]
+ * @property {(certificates: string[]) => void} [setDefaultCACertificates]
+ */
+
+/**
+ * @typedef {Object} DefaultCaResult
+ * @property {boolean} applied Whether Node's default CA list now includes the additions.
+ * @property {string[]} certificates The additions that were accepted (all of them, or the parsable ones).
+ * @property {number} rejected Additions dropped because the TLS library could not parse them.
+ * @property {string | null} error Why the defaults could not be extended, when they could not.
+ */
+
+/**
+ * Whether the TLS library accepts a PEM certificate as a trust anchor.
+ * @param {string} pem
+ * @returns {boolean}
+ */
+export function isUsableCaCertificate(pem) {
+ try {
+ new X509Certificate(pem);
+ tls.createSecureContext({ ca: pem });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Extends Node's default CA list (what fetch/undici, https and tls.connect
+ * verify against when no `ca` is given) with the OS trust store, in this
+ * process. setDefaultCACertificates rejects the whole list when any one
+ * certificate does not parse, and OS stores (the Windows CA/Root stores in
+ * particular) can hold certificates that BoringSSL refuses; those are dropped
+ * one by one rather than losing every OS root, including the antivirus or
+ * corporate proxy root the user depends on.
+ *
+ * @param {DefaultCaTlsModule | undefined} tlsModule
+ * @param {string[]} additions
+ * @param {(pem: string) => boolean} [isUsable]
+ * @returns {DefaultCaResult}
+ */
+export function extendDefaultCaCertificates(tlsModule, additions, isUsable = isUsableCaCertificate) {
+ if (additions.length === 0) return { applied: false, certificates: [], rejected: 0, error: null };
+ if (typeof tlsModule?.getCACertificates !== "function" || typeof tlsModule?.setDefaultCACertificates !== "function") {
+ return { applied: false, certificates: additions, rejected: 0, error: "tls.setDefaultCACertificates is unavailable" };
+ }
+ let base;
+ try {
+ const defaults = tlsModule.getCACertificates("default");
+ base = Array.isArray(defaults) ? defaults : [];
+ } catch (error) {
+ return { applied: false, certificates: additions, rejected: 0, error: String(error?.message ?? error) };
+ }
+ try {
+ tlsModule.setDefaultCACertificates(dedupeCertificates([...base, ...additions]));
+ return { applied: true, certificates: additions, rejected: 0, error: null };
+ } catch {
+ // One or more unparsable certificates; keep the rest.
+ }
+ const usable = additions.filter((pem) => isUsable(pem));
+ const rejected = additions.length - usable.length;
+ if (usable.length === 0) return { applied: false, certificates: [], rejected, error: "no parsable certificates" };
+ try {
+ tlsModule.setDefaultCACertificates(dedupeCertificates([...base, ...usable]));
+ return { applied: true, certificates: usable, rejected, error: null };
+ } catch (error) {
+ return { applied: false, certificates: usable, rejected, error: String(error?.message ?? error) };
+ }
+}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index a53bc5b7..1df668ba 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,8 +27,8 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
- "test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs",
+ "test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},
"dependencies": {
diff --git a/apps/server/src/cloud-provider-sync.ts b/apps/server/src/cloud-provider-sync.ts
index 794690d4..24b54cf7 100644
--- a/apps/server/src/cloud-provider-sync.ts
+++ b/apps/server/src/cloud-provider-sync.ts
@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";
import type { EnvService } from "./env-file.js";
import { selectPrimaryCredentialEnvName, syncManagedProviderAuth } from "./managed-provider-auth.js";
+import { externalFetch } from "./server-fetch.js";
import { writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
import {
hasOmniRushWorkspaceConfig,
@@ -341,8 +342,11 @@ export function parseCloudProviderDenSession(value: unknown): CloudProviderDenSe
return { baseUrl: baseUrl.replace(/\/+$/, ""), token, orgId };
}
+/** Den requests: always a URL string and a plain init. */
+type DenFetch = (input: string, init?: RequestInit) => Promise<Response>;
+
async function requestJson(
- fetchImpl: typeof globalThis.fetch,
+ fetchImpl: DenFetch,
session: CloudProviderDenSession,
path: string,
): Promise<unknown> {
@@ -369,7 +373,7 @@ async function requestJson(
}
async function fetchProviders(
- fetchImpl: typeof globalThis.fetch,
+ fetchImpl: DenFetch,
session: CloudProviderDenSession,
): Promise<DenProviderConnection[]> {
const providers = parseProviderList(await requestJson(fetchImpl, session, "/v1/llm-providers"));
@@ -616,6 +620,7 @@ export class CloudProviderSync {
private readonly reloadEngine: () => Promise<void>;
private readonly engineBusy?: () => Promise<boolean>;
private readonly fetchImpl: typeof globalThis.fetch;
+ private readonly denFetchImpl: DenFetch;
private readonly logger?: CloudProviderSyncLogger;
private readonly intervalMs: number;
private session: CloudProviderDenSession | null = null;
@@ -642,6 +647,9 @@ export class CloudProviderSync {
this.reloadEngine = options.reloadEngine;
this.engineBusy = options.engineBusy;
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
+ // Den is off the machine: Chromium's network stack under Electron (OS
+ // trust store, system proxy). Provider auth pushes stay on loopback.
+ this.denFetchImpl = options.fetchImpl ?? externalFetch;
this.logger = options.logger;
this.intervalMs = options.intervalMs ?? configuredIntervalMs();
this.reloadRetryMs = configuredReloadRetryMs();
@@ -912,7 +920,7 @@ export class CloudProviderSync {
const { reason, session } = request;
try {
const [providers, storedEnv] = await Promise.all([
- fetchProviders(this.fetchImpl, session),
+ fetchProviders(this.denFetchImpl, session),
this.env.list(),
]);
// Local credentials only satisfy materialization eligibility. Never add