Skip to content

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

fix(policy): Preserve config failures and audit API headers

Chadpiha6dd11f8bafa8
diff --git a/src/stores/streamingProvidersStore.ts b/src/stores/streamingProvidersStore.ts
index d9e075fa5..6520c2a70 100644
--- a/src/stores/streamingProvidersStore.ts
+++ b/src/stores/streamingProvidersStore.ts
@@ -1,17 +1,13 @@
import { create } from "zustand";
import logger from "../utils/logger";
+import type {
+ NoteRecordingConfigFailure,
+ NoteRecordingConfigResult,
+ NoteRecordingProvider,
+ NoteRecordingProviderModel,
+} from "../types/electron";
-export interface NoteRecordingProviderModel {
- id: string;
- name: string;
- default?: boolean;
-}
-
-export interface NoteRecordingProvider {
- id: string;
- name: string;
- models: NoteRecordingProviderModel[];
-}
+export type { NoteRecordingProvider, NoteRecordingProviderModel };
interface StreamingProvidersState {
providers: NoteRecordingProvider[] | null;
@@ -21,24 +17,31 @@ export const useStreamingProvidersStore = create<StreamingProvidersState>()(() =
providers: null,
}));
-let inFlight: Promise<NoteRecordingProvider[] | null> | null = null;
+let inFlight: Promise<NoteRecordingConfigResult | null> | null = null;
-export async function fetchProviders(): Promise<NoteRecordingProvider[] | null> {
+export async function fetchProviders(): Promise<NoteRecordingConfigResult | null> {
if (inFlight) return inFlight;
if (!window.electronAPI?.getNoteRecordingConfig) return null;
inFlight = (async () => {
try {
const data = await window.electronAPI.getNoteRecordingConfig!();
- if (!data?.success) {
- throw new Error("Note recording config unavailable");
+ if (!data) return null;
+ if (data.success === false) {
+ logger.warn("Failed to fetch note recording providers", data, "streamingProviders");
+ return data;
}
const providers = Array.isArray(data.providers) ? data.providers : [];
+ const result = { ...data, providers };
useStreamingProvidersStore.setState({ providers });
- return providers;
+ return result;
} catch (err) {
+ const failure: NoteRecordingConfigFailure = {
+ success: false,
+ error: err instanceof Error ? err.message : String(err),
+ };
logger.warn("Failed to fetch note recording providers", err, "streamingProviders");
- return null;
+ return failure;
} finally {
inFlight = null;
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index ce6098c34..c598b92f0 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -21,6 +21,23 @@ export interface PolicyFailureMetadata {
details?: unknown;
}
+export interface NoteRecordingProviderModel {
+ id: string;
+ name: string;
+ default?: boolean;
+}
+
+export interface NoteRecordingProvider {
+ id: string;
+ name: string;
+ models: NoteRecordingProviderModel[];
+}
+
+export type NoteRecordingConfigFailure = { success: false } & PolicyFailureMetadata;
+
+export type NoteRecordingConfigResult =
+ { success: true; providers: NoteRecordingProvider[] } | NoteRecordingConfigFailure;
+
export type TranscriptionErrorCode =
| "TIMEOUT"
| "NETWORK"
@@ -825,14 +842,7 @@ declare global {
) => void
) => () => void;
- getNoteRecordingConfig?: () => Promise<{
- success: boolean;
- providers: Array<{
- id: string;
- name: string;
- models: Array<{ id: string; name: string; default?: boolean }>;
- }>;
- } | null>;
+ getNoteRecordingConfig?: () => Promise<NoteRecordingConfigResult | null>;
// Database operations
saveTranscription: (
diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.js
index 57b4b43db..900cef0a2 100644
--- a/test/helpers/ipcPolicyHeaderCoverage.test.js
+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js
@@ -2,8 +2,27 @@ const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
+const { inspectDirectOpenWhisprApiCalls } = require("../lib/ipcPolicyHeaderInventory");
-const source = fs.readFileSync(path.join(__dirname, "../../src/helpers/ipcHandlers.js"), "utf8");
+const helpersDirectory = path.join(__dirname, "../../src/helpers");
+const source = fs.readFileSync(path.join(helpersDirectory, "ipcHandlers.js"), "utf8");
+const helperSources = fs
+ .readdirSync(helpersDirectory)
+ .filter((fileName) => fileName.endsWith(".js"))
+ .map((fileName) => ({
+ fileName,
+ source: fs.readFileSync(path.join(helpersDirectory, fileName), "utf8"),
+ }));
+
+const NON_POLICY_ROUTE_REASONS = new Map([
+ ["streaming-usage", "usage accounting does not perform a policy-gated action"],
+ ["usage", "entitlement and recovery status must remain available"],
+ ["stripe/switch-plan", "billing recovery must remain available"],
+ ["stripe/preview-switch", "billing recovery must remain available"],
+ ["referrals/stats", "referral data is outside the policy capability surface"],
+ ["referrals/invite", "referral actions are outside the policy capability surface"],
+ ["referrals/invites", "referral data is outside the policy capability surface"],
+]);
test("all OpenWhispr multipart transcription transports use policy headers", () => {
assert.match(source, /async function chunkedCloudTranscribe\([\s\S]*?policyHeaders/);
@@ -18,29 +37,48 @@ test("all OpenWhispr multipart transcription transports use policy headers", ()
);
});
-test("direct policy-aware JSON and token routes apply the shared headers", () => {
+test("the shared realtime-token helper applies policy headers", () => {
assert.match(
source,
/const postServerToken[\s\S]{0,900}?headers:\s*withPolicyHeaders\(/,
"the shared realtime-token helper must apply policy headers"
);
- for (const route of [
- "streaming-token",
- "deepgram-streaming-token",
- "reason",
- "agent/stream",
- "agent/web-search",
- ]) {
- const directCalls = source.match(
- new RegExp(
- "proxyFetch\\(`\\$\\{apiUrl\\}/api/" +
- route +
- "`[\\s\\S]{0,300}?headers:\\s*withPolicyHeaders\\(",
- "g"
- )
- );
- assert.ok(directCalls?.length, `/api/${route} direct calls must use policy headers`);
- }
+});
+
+test("the structural inventory discovers newly added unprotected API routes", () => {
+ const fixture = [
+ "proxyFetch(`${apiUrl}/api/reason`, { headers: withPolicyHeaders(authHeader) });",
+ "proxyFetch(`${apiUrl}/api/new-route`, { headers: authHeader });",
+ "proxyFetch(`${identity.apiUrl}/api/workspace-policy`, { headers: withPolicyRequestHeaders(authHeader) });",
+ 'proxyFetch("https://api.openai.com/v1/audio/transcriptions", { headers: authHeader });',
+ ].join("\n");
+
+ assert.deepEqual(inspectDirectOpenWhisprApiCalls(fixture, "fixture.js"), [
+ { fileName: "fixture.js", line: 1, route: "reason", hasPolicyHeaders: true },
+ { fileName: "fixture.js", line: 2, route: "new-route", hasPolicyHeaders: false },
+ { fileName: "fixture.js", line: 3, route: "workspace-policy", hasPolicyHeaders: true },
+ ]);
+});
+
+test("every direct OpenWhispr API route is policy-protected or explicitly exempt", () => {
+ const calls = helperSources.flatMap(({ fileName, source: helperSource }) =>
+ inspectDirectOpenWhisprApiCalls(helperSource, fileName)
+ );
+ assert.ok(calls.length > 0, "the helper inventory must discover OpenWhispr API calls");
+
+ const unclassified = calls
+ .filter((call) => !call.hasPolicyHeaders && !NON_POLICY_ROUTE_REASONS.has(call.route))
+ .map((call) => `${call.fileName}:${call.line} /api/${call.route}`);
+ assert.deepEqual(
+ unclassified,
+ [],
+ "new direct OpenWhispr routes must use policy headers or declare a non-policy reason"
+ );
+
+ const unusedExemptions = [...NON_POLICY_ROUTE_REASONS.keys()].filter(
+ (route) => !calls.some((call) => call.route === route && !call.hasPolicyHeaders)
+ );
+ assert.deepEqual(unusedExemptions, [], "remove stale non-policy route exemptions");
});
test("policy headers are not injected into BYOK or self-hosted transports", () => {
diff --git a/test/helpers/streamingProvidersStore.test.js b/test/helpers/streamingProvidersStore.test.js
new file mode 100644
index 000000000..5b2000ac9
--- /dev/null
+++ b/test/helpers/streamingProvidersStore.test.js
@@ -0,0 +1,48 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const path = require("node:path");
+
+test("note recording config failures retain their structured policy metadata", async (t) => {
+ t.mock.method(console, "warn", () => {});
+ const previousWindow = globalThis.window;
+ const failure = {
+ success: false,
+ error: "Blocked by workspace policy",
+ code: "POLICY_RESTRICTED",
+ status: 403,
+ };
+ globalThis.window = {
+ electronAPI: {
+ getNoteRecordingConfig: async () => failure,
+ },
+ };
+ t.after(() => {
+ globalThis.window = previousWindow;
+ });
+
+ const { build } = await import("vite");
+ const buildResult = await build({
+ configFile: false,
+ logLevel: "silent",
+ build: {
+ ssr: path.join(__dirname, "../../src/stores/streamingProvidersStore.ts"),
+ write: false,
+ rolldownOptions: { output: { format: "cjs" } },
+ },
+ });
+ const chunk = buildResult.output.find((entry) => entry.type === "chunk");
+ assert.ok(chunk, "the store must compile to an SSR chunk");
+ const compiledModule = new Module(chunk.fileName);
+ compiledModule.filename = path.join(__dirname, chunk.fileName);
+ compiledModule.paths = Module._nodeModulePaths(path.join(__dirname, "../.."));
+ compiledModule._compile(chunk.code, compiledModule.filename);
+ const { fetchProviders, useStreamingProvidersStore } = compiledModule.exports;
+ const existingProviders = [{ id: "openai", name: "OpenAI", models: [] }];
+ useStreamingProvidersStore.setState({ providers: existingProviders });
+
+ const result = await fetchProviders();
+
+ assert.deepEqual(result, failure);
+ assert.deepEqual(useStreamingProvidersStore.getState().providers, existingProviders);
+});
diff --git a/test/lib/ipcPolicyHeaderInventory.js b/test/lib/ipcPolicyHeaderInventory.js
new file mode 100644
index 000000000..a4d95ce31
--- /dev/null
+++ b/test/lib/ipcPolicyHeaderInventory.js
@@ -0,0 +1,97 @@
+const { parse } = require("espree");
+
+const POLICY_HEADER_BUILDERS = new Set(["withPolicyHeaders", "withPolicyRequestHeaders"]);
+
+function walkSyntaxTree(value, visit) {
+ if (!value || typeof value !== "object") return;
+ if (Array.isArray(value)) {
+ value.forEach((item) => walkSyntaxTree(item, visit));
+ return;
+ }
+ if (typeof value.type === "string") visit(value);
+ for (const [key, child] of Object.entries(value)) {
+ if (key === "loc" || key === "range") continue;
+ walkSyntaxTree(child, visit);
+ }
+}
+
+function templateRoute(argument) {
+ if (argument?.type !== "TemplateLiteral" || !isApiUrlExpression(argument.expressions[0])) {
+ return null;
+ }
+
+ const routePrefix = argument.quasis[1]?.value.cooked;
+ if (!routePrefix?.startsWith("/api/")) return null;
+
+ let route = routePrefix.slice("/api/".length);
+ for (let index = 1; index < argument.expressions.length; index += 1) {
+ const expression = argument.expressions[index];
+ const label = expression.type === "Identifier" ? expression.name : "dynamic";
+ route += `\${${label}}${argument.quasis[index + 1]?.value.cooked ?? ""}`;
+ }
+ return route;
+}
+
+function isApiUrlExpression(expression) {
+ if (expression?.type === "Identifier") return expression.name === "apiUrl";
+ if (expression?.type !== "MemberExpression") return false;
+ if (!expression.computed && expression.property?.type === "Identifier") {
+ return expression.property.name === "apiUrl";
+ }
+ return expression.property?.type === "Literal" && expression.property.value === "apiUrl";
+}
+
+function containsPolicyHeaderBuilder(value) {
+ let found = false;
+ walkSyntaxTree(value, (node) => {
+ if (
+ node.type === "CallExpression" &&
+ node.callee?.type === "Identifier" &&
+ POLICY_HEADER_BUILDERS.has(node.callee.name)
+ ) {
+ found = true;
+ }
+ });
+ return found;
+}
+
+function hasPolicyHeaders(options) {
+ if (options?.type !== "ObjectExpression") return false;
+ const headers = options.properties.find((property) => {
+ if (property.type !== "Property") return false;
+ if (!property.computed && property.key?.type === "Identifier") {
+ return property.key.name === "headers";
+ }
+ return property.key?.type === "Literal" && property.key.value === "headers";
+ });
+ return containsPolicyHeaderBuilder(headers?.value);
+}
+
+function inspectDirectOpenWhisprApiCalls(source, fileName) {
+ const syntaxTree = parse(source, {
+ ecmaVersion: "latest",
+ sourceType: "module",
+ loc: true,
+ });
+ const calls = [];
+ walkSyntaxTree(syntaxTree, (node) => {
+ if (
+ node.type !== "CallExpression" ||
+ node.callee?.type !== "Identifier" ||
+ node.callee.name !== "proxyFetch"
+ ) {
+ return;
+ }
+ const route = templateRoute(node.arguments[0]);
+ if (route === null) return;
+ calls.push({
+ fileName,
+ line: node.loc.start.line,
+ route,
+ hasPolicyHeaders: hasPolicyHeaders(node.arguments[1]),
+ });
+ });
+ return calls.sort((left, right) => left.line - right.line);
+}
+
+module.exports = { inspectDirectOpenWhisprApiCalls };