Turn meetings into live agent loops. Record, transcribe, and analyze meetings with real-time AI intelligence — before, during, and after calls.
fix: security hardening, transcription language, platform docs
codeashu0d8eb3a12e03
diff --git a/README.md b/README.mdindex fb2e61b..a53144d 100644--- a/README.md+++ b/README.md@@ -47,15 +47,31 @@ https://github.com/user-attachments/assets/94470e99-c0f6-4e35-9d03-b28efa362b3bcurl -fsSL https://artifacts.videodb.io/call.md/install | bash```-<p>- <em>Currently available for macOS and Windows — Linux support coming soon</em>-</p>-After installation:1. Launch Call.md from Applications or Spotlight2. Grant system permissions when prompted (Microphone and Screen Recording required)3. Register with your VideoDB API key ([get one free](https://console.videodb.io))+### Platform Support++| Platform | Installer | Status |+|----------|-----------|--------|+| macOS 12+ (Apple Silicon & Intel) | `curl` command above | Supported |+| Windows | — | Not available yet ([#29](https://github.com/video-db/call.md/issues/29)) |+| Linux | — | Not available yet |++**There is no Windows installer today.** The blocker is not the Electron app —+that builds on Windows and Linux — but the capture engine underneath it:+[`@videodb/recorder`](https://www.npmjs.com/package/@videodb/recorder) ships+binaries for `darwin-x64` and `darwin-arm64` only. With no Windows binary there+is nothing to record microphone, system audio or screen with, so the app now+says so up front instead of failing partway into a meeting.++You can still build and run everything around recording (UI, MCP servers,+workflows, exports) on Windows and Linux — see+[Building for other platforms](#building-for-other-platforms). Follow+[#29](https://github.com/video-db/call.md/issues/29) for Windows support.+---## Overview@@ -66,6 +82,7 @@ Call.md turns meetings into live agent loops. It records locally, transcribes in### During the Meeting (Live Intelligence)- **Dual-Channel Transcription** - Separate transcription for you (mic) vs them (system audio), powered by VideoDB+- **Transcription Language** - Pick the meeting language in **Settings → Transcription**, or leave it on Automatic- **Live Assist** - AI generates contextual suggestions: things to say, questions to ask- **Conversation Metrics** - Real-time monitoring of talk ratio, speaking pace (WPM), questions asked, monologue detection- **Coaching Nudges** - Gentle rate-limited alerts when conversation needs steering@@ -121,7 +138,7 @@ Call.md turns meetings into live agent loops. It records locally, transcribes in## Prerequisites-- macOS 12+ (Monterey or later)+- macOS 12+ (Monterey or later) — required for recording, see [Platform Support](#platform-support)- VideoDB API Key ([console.videodb.io](https://console.videodb.io))- System permissions: Microphone and Screen Recording@@ -176,12 +193,33 @@ The app will transcribe in real-time, show live assists, and generate a summary| `npm run dev` | Start development mode (main + renderer with hot reload) || `npm run build` | Build TypeScript and React for production || `npm run dist:mac` | Build macOS distributable DMG |+| `npm run dist:win` | Build Windows NSIS installer (recording unsupported, see below) |+| `npm run dist:linux` | Build Linux AppImage (recording unsupported, see below) || `npm run typecheck` | Run TypeScript type checking |+| `npm run test` | Run unit tests || `npm run lint` | Run ESLint || `npm run rebuild` | Rebuild native modules for Electron || `npm run db:generate` | Generate database migration files || `npm run db:migrate` | Apply database migrations |+### Building for other platforms++electron-builder is already configured for Windows (NSIS) and Linux (AppImage),+so you can produce an installer on those platforms:++```bash+npm install && npm run rebuild && npm run dist:win+```++Build on the target OS. Cross-building is not supported here because+`better-sqlite3` is a native module that has to be rebuilt for the host.++What works in such a build: the full UI, MCP servers, workflows, settings,+history, and markdown export. What does not: starting a recording — the VideoDB+capture engine has no binary for the platform, and the app returns a clear+error rather than crashing. Track+[#29](https://github.com/video-db/call.md/issues/29) for progress.+## MCP Server SetupConnect MCP servers in **Settings → MCP Servers**:@@ -273,6 +311,14 @@ Grant these in **System Preferences > Privacy & Security**.- Wait 5-10 seconds for first transcripts- Check internet connectivity+**Transcription is in the wrong language:**+- Set the meeting language in **Settings → Transcription** (it applies to the+ next recording, not one already in progress)+- If transcripts still come back in English, the language is not yet supported+ by the VideoDB transcription backend. The app sends `language_code` and falls+ back to the engine default rather than failing — see+ [#25](https://github.com/video-db/call.md/issues/25)+**Development issues:**- Rebuild native modules: `npm run rebuild`- Check Node.js version (requires 18+)@@ -283,12 +329,41 @@ Grant these in **System Preferences > Privacy & Security**.Application data is stored in:```~/Library/Application Support/call-md/+├── config.json # Settings; credentials encrypted at rest├── data/-│ └── call-md.db # SQLite database+│ └── call-md.db # SQLite database└── logs/└── app-YYYY-MM-DD.log # Daily log files```+## Security++Everything below stays on your machine; only audio, video and prompts go to+VideoDB.++- **Credentials at rest** — the VideoDB API key in `config.json` and in the+ SQLite `users` table is encrypted through the OS keychain (Keychain on macOS,+ DPAPI on Windows, libsecret on Linux). Access tokens are stored as SHA-256+ digests, never in the clear. MCP server env vars, HTTP headers and OAuth+ tokens are encrypted with AES-256-GCM under a keychain-wrapped key.+- **Local API** — the tRPC server binds to `127.0.0.1` only and accepts CORS+ requests from loopback origins, so nothing on your network can reach it.+ Every procedure except registration requires a valid access token.+- **File permissions** — the app data directory is `0700` and the database,+ config, tokens and logs are `0600`.+- **Renderer** — both windows run with `contextIsolation`, no Node integration,+ and the Chromium sandbox enabled. The API key is never written to+ localStorage.+- **Webhooks** — workflow URLs are validated at save time *and* at call time.+ Non-HTTP(S) schemes, embedded credentials, redirects, and hosts that resolve+ to loopback, private, link-local or cloud-metadata addresses are rejected, so+ a webhook cannot be used to reach inside your network.+- **Logs** — credential-shaped fields are redacted before anything is written.++Upgrades migrate existing data in place on first launch; you do not need to log+in again. Report security issues via+[GitHub Issues](https://github.com/video-db/call.md/issues).+## Community & Support- **Documentation:** [docs.videodb.io](https://docs.videodb.io)diff --git a/package.json b/package.jsonindex 07b32ad..5a6156f 100644--- a/package.json+++ b/package.json@@ -22,7 +22,10 @@"postinstall": "electron-rebuild -f -w better-sqlite3 || true","dist": "npm run build && electron-builder","dist:mac": "npm run build && electron-builder --mac",+ "dist:win": "npm run build && electron-builder --win",+ "dist:linux": "npm run build && electron-builder --linux","typecheck": "tsc --noEmit && tsc -p tsconfig.node.json --noEmit",+ "test": "tsx --test tests/*.test.ts","lint": "eslint src --ext .ts,.tsx","db:generate": "drizzle-kit generate","db:migrate": "drizzle-kit migrate"diff --git a/src/main/db/index.ts b/src/main/db/index.tsindex 30ee650..e99fa24 100644--- a/src/main/db/index.ts+++ b/src/main/db/index.ts@@ -2,10 +2,19 @@ import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';import { eq, desc, and, gte, lte } from 'drizzle-orm';import { app } from 'electron';+import crypto from 'crypto';import path from 'path';import fs from 'fs';import * as schema from './schema';import { logger } from '../lib/logger';+import {+ encryptSecret,+ decryptSecret,+ isEncrypted,+ restrictPermissions,+ FILE_MODE,+ DIR_MODE,+} from '../lib/secure-store';let db: ReturnType<typeof drizzle<typeof schema>> | null = null;let sqlite: Database.Database | null = null;@@ -15,12 +24,33 @@ export function getDbPath(): string {const dbDir = path.join(userDataPath, 'data');if (!fs.existsSync(dbDir)) {- fs.mkdirSync(dbDir, { recursive: true });+ fs.mkdirSync(dbDir, { recursive: true, mode: DIR_MODE });}return path.join(dbDir, 'call-md.db');}+/**+ * Access tokens are stored as a SHA-256 digest, never in the clear.+ *+ * The token is a random UUID, so a plain digest is enough: there is no+ * guessable input space for an offline attack, and lookups stay exact-match.+ */+export function hashAccessToken(accessToken: string): string {+ return crypto.createHash('sha256').update(accessToken).digest('hex');+}++/**+ * Locks down the SQLite files, which hold transcripts and meeting content.+ * better-sqlite3 creates them 0644; -wal and -shm are created alongside.+ */+function restrictDatabasePermissions(dbPath: string): void {+ restrictPermissions(path.dirname(dbPath), DIR_MODE);+ for (const suffix of ['', '-wal', '-shm']) {+ restrictPermissions(`${dbPath}${suffix}`, FILE_MODE);+ }+}+export function initDatabase(): ReturnType<typeof drizzle<typeof schema>> {if (db) return db;@@ -28,6 +58,7 @@ export function initDatabase(): ReturnType<typeof drizzle<typeof schema>> {logger.info({ dbPath }, 'Initializing database');sqlite = new Database(dbPath);+ restrictDatabasePermissions(dbPath);db = drizzle(sqlite, { schema });sqlite.exec(`@@ -265,6 +296,7 @@ export function initDatabase(): ReturnType<typeof drizzle<typeof schema>> {ensureNudgesHistorySchema();ensureMCPServerColumns();ensureUserColumns();+ ensureUserCredentialsProtected();seedDefaultCueCards();@@ -378,6 +410,47 @@ function ensureUserColumns(): void {}}+/**+ * Upgrades rows written by builds that stored credentials in the clear:+ * encrypts `api_key` and replaces `access_token` with its SHA-256 digest.+ *+ * Both are idempotent - already-migrated rows are left alone - so this can run+ * on every startup. Sessions survive because the app sends the same token it+ * saved in config.json, and lookups now hash before comparing.+ */+function ensureUserCredentialsProtected(): void {+ if (!sqlite) return;++ const rows = sqlite+ .prepare('SELECT id, api_key, access_token FROM users')+ .all() as { id: number; api_key: string; access_token: string }[];++ const update = sqlite.prepare('UPDATE users SET api_key = ?, access_token = ? WHERE id = ?');+ let migrated = 0;++ for (const row of rows) {+ const needsKeyEncryption = !!row.api_key && !isEncrypted(row.api_key);+ const needsTokenHashing = !!row.access_token && !isHashedToken(row.access_token);++ if (!needsKeyEncryption && !needsTokenHashing) continue;++ update.run(+ needsKeyEncryption ? encryptSecret(row.api_key) : row.api_key,+ needsTokenHashing ? hashAccessToken(row.access_token) : row.access_token,+ row.id+ );+ migrated += 1;+ }++ if (migrated > 0) {+ logger.info({ migrated }, 'Migrated stored user credentials to protected storage');+ }+}++function isHashedToken(value: string): boolean {+ return /^[a-f0-9]{64}$/.test(value);+}+export function getDatabase(): ReturnType<typeof drizzle<typeof schema>> {if (!db) {throw new Error('Database not initialized. Call initDatabase() first.');@@ -394,28 +467,65 @@ export function closeDatabase(): void {}}+/**+ * Restores the plaintext API key on a row read back from the database.+ * Every caller needs the real key to talk to VideoDB.+ */+function withDecryptedApiKey<T extends { apiKey: string } | undefined>(user: T): T {+ if (!user) return user;+ return { ...user, apiKey: decryptSecret(user.apiKey) };+}+export function getUserByAccessToken(accessToken: string) {const database = getDatabase();- return database+ const user = database.select().from(schema.users)- .where(eq(schema.users.accessToken, accessToken))+ .where(eq(schema.users.accessToken, hashAccessToken(accessToken))).get();++ return withDecryptedApiKey(user);}+/**+ * Creates a user, storing the API key encrypted and the access token hashed.+ * The returned row carries the plaintext API key for immediate use; the caller+ * already holds the plaintext access token it passed in.+ */export function createUser(data: schema.NewUser) {const database = getDatabase();- return database.insert(schema.users).values(data).returning().get();+ const user = database+ .insert(schema.users)+ .values({+ ...data,+ apiKey: encryptSecret(data.apiKey),+ accessToken: hashAccessToken(data.accessToken),+ })+ .returning()+ .get();++ return withDecryptedApiKey(user);}export function updateUser(id: number, data: Partial<schema.User>) {const database = getDatabase();- return database++ const values: Partial<schema.User> = { ...data };+ if (typeof values.apiKey === 'string') {+ values.apiKey = encryptSecret(values.apiKey);+ }+ if (typeof values.accessToken === 'string') {+ values.accessToken = hashAccessToken(values.accessToken);+ }++ const user = database.update(schema.users)- .set(data)+ .set(values).where(eq(schema.users.id, id)).returning().get();++ return withDecryptedApiKey(user);}export function getRecordingById(id: number) {diff --git a/src/main/index.ts b/src/main/index.tsindex 40ba373..ab2c5ab 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -33,6 +33,7 @@ import {loadAuthConfig,deleteAuthConfig,saveAppConfig,+ secureUserDataDir,} from './lib/config';import { logger } from './lib/logger';import { applyVideoDBPatches } from './lib/videodb-patch';@@ -141,7 +142,9 @@ async function createWindow(): Promise<void> {preload: path.join(__dirname, '..', 'preload', 'index.js'),nodeIntegration: false,contextIsolation: true,- sandbox: false,+ // The preload only uses contextBridge/ipcRenderer, so the renderer can+ // run in the OS sandbox.+ sandbox: true,},});@@ -455,6 +458,9 @@ if (!gotTheLock) {app.whenReady().then(async () => {logger.info('App starting');+ // Lock down app data before anything opens the database or config files.+ secureUserDataDir();+// Setup protocol handler for OAuth callbackssetupProtocolHandler();diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.tsindex 43c8965..8285917 100644--- a/src/main/ipc/app.ts+++ b/src/main/ipc/app.ts@@ -1,8 +1,10 @@import { ipcMain, shell, Notification, BrowserWindow } from 'electron';-import { loadAppConfig, loadRuntimeConfig, clearAppConfig } from '../lib/config';+import { loadAppConfig, loadRuntimeConfig, clearAppConfig, saveAppConfig } from '../lib/config';import { VideoDBService } from '../services/videodb.service';import { getServerStatus } from '../server';import { createChildLogger } from '../lib/logger';+import { SaveSettingsInputSchema } from '../../shared/schemas/config.schema';+import { AUTO_LANGUAGE, isSupportedLanguage } from '../../shared/constants/languages';import os from 'os';import path from 'path';@@ -16,6 +18,7 @@ export function setupAppHandlers(): void {userName?: string;apiKey?: string;apiUrl?: string;+ transcriptionLanguage: string;}> => {const appConfig = loadAppConfig();const runtimeConfig = loadRuntimeConfig();@@ -25,10 +28,43 @@ export function setupAppHandlers(): void {userName: appConfig.userName,apiKey: appConfig.apiKey,apiUrl: runtimeConfig.apiUrl,+ transcriptionLanguage: appConfig.transcriptionLanguage || AUTO_LANGUAGE,};});+ /**+ * Persists settings to the encrypted app config.+ *+ * This is where credentials live: the renderer keeps them in memory only, so+ * the main process is the source of truth across restarts.+ */+ ipcMain.handle(+ 'save-settings',+ async (_event, settings: unknown): Promise<{ success: boolean; error?: string }> => {+ const parsed = SaveSettingsInputSchema.safeParse(settings);+ if (!parsed.success) {+ logger.warn({ error: parsed.error.message }, 'Rejected invalid settings payload');+ return { success: false, error: 'Invalid settings' };+ }++ const { transcriptionLanguage } = parsed.data;+ if (transcriptionLanguage !== undefined && !isSupportedLanguage(transcriptionLanguage)) {+ return { success: false, error: `Unsupported language "${transcriptionLanguage}"` };+ }++ try {+ // Merge so a partial update never clears the other fields.+ saveAppConfig({ ...loadAppConfig(), ...parsed.data });+ return { success: true };+ } catch (error) {+ const err = error as Error;+ logger.error({ error: err.message }, 'Failed to save settings');+ return { success: false, error: err.message };+ }+ }+ );+ipcMain.handle('get-server-port', async (): Promise<number> => {const status = getServerStatus();return status.port || 51731; // fallback to default@@ -79,6 +115,13 @@ export function setupAppHandlers(): void {);ipcMain.handle('open-player-window', async (_event, url: string): Promise<void> => {+ // Only ever used for VideoDB player URLs; refuse anything that could load+ // local files or a custom scheme into a privileged window.+ if (!/^https?:\/\//i.test(url)) {+ logger.warn({ url }, 'Refused to open player window for non-HTTP URL');+ return;+ }+const playerWindow = new BrowserWindow({width: 1024,height: 768,@@ -86,6 +129,7 @@ export function setupAppHandlers(): void {webPreferences: {nodeIntegration: false,contextIsolation: true,+ sandbox: true,},});diff --git a/src/main/ipc/capture.ts b/src/main/ipc/capture.tsindex bf32f75..43caa37 100644--- a/src/main/ipc/capture.ts+++ b/src/main/ipc/capture.ts@@ -49,6 +49,26 @@ let currentAccessToken: string | null = null;let currentApiUrl: string | undefined = undefined;let currentCollectionId: string | null = null;+/**+ * Whether the VideoDB capture engine can run on this OS.+ *+ * `@videodb/recorder` only ships binaries for darwin-x64 and darwin-arm64, so+ * on any other platform the recorder fails deep inside the native layer with+ * an unhelpful error. Say so up front instead.+ *+ * See https://github.com/video-db/call.md/issues/29.+ */+function getRecordingPlatformSupport(): { supported: boolean; reason?: string } {+ if (process.platform === 'darwin') return { supported: true };++ return {+ supported: false,+ reason:+ `Recording is not available on ${process.platform} yet. The VideoDB capture engine ` ++ 'currently ships macOS binaries only - see https://github.com/video-db/call.md/issues/29.',+ };+}+function ensureVideoDBPatched(): void {if (!app.isPackaged) return;try {@@ -492,6 +512,12 @@ export function setupCaptureHandlers(): void {logger.info({ sessionId: config.sessionId, enableTranscription }, 'Starting recording - IPC handler called');+ const platformSupport = getRecordingPlatformSupport();+ if (!platformSupport.supported) {+ logger.error({ platform: process.platform }, 'Recording is not supported on this platform');+ return { success: false, error: platformSupport.reason };+ }+try {// Set up session WebSocket for capture_session events (informational logging)const sessionWsId = await setupSessionWebSocket(sessionToken, apiUrl);diff --git a/src/main/ipc/workflows.ts b/src/main/ipc/workflows.tsindex b214ec5..bf16335 100644--- a/src/main/ipc/workflows.ts+++ b/src/main/ipc/workflows.ts@@ -7,6 +7,7 @@import { ipcMain, BrowserWindow } from 'electron';import { v4 as uuid } from 'uuid';import { createChildLogger } from '../lib/logger';+import { validateWebhookUrl } from '../lib/url-guard';import {getAllWorkflows,getWorkflowById,@@ -93,6 +94,12 @@ export function setupWorkflowHandlers(): void {error?: string;}> => {try {+ const validation = await validateWebhookUrl(request.webhookUrl);+ if (!validation.valid) {+ logger.warn({ error: validation.error }, 'Rejected workflow with unsafe webhook URL');+ return { success: false, error: validation.error };+ }+const workflow = createWorkflow({id: uuid(),name: request.name,@@ -132,6 +139,14 @@ export function setupWorkflowHandlers(): void {return { success: false, error: 'Workflow not found' };}+ if (request.webhookUrl !== undefined) {+ const validation = await validateWebhookUrl(request.webhookUrl);+ if (!validation.valid) {+ logger.warn({ workflowId: id, error: validation.error }, 'Rejected unsafe webhook URL');+ return { success: false, error: validation.error };+ }+ }+const workflow = updateWorkflow(id, {name: request.name,webhookUrl: request.webhookUrl,diff --git a/src/main/lib/config.ts b/src/main/lib/config.tsindex 8e78d7b..1784975 100644--- a/src/main/lib/config.ts+++ b/src/main/lib/config.ts@@ -4,6 +4,15 @@ import fs from 'fs';import type { AppConfig, RuntimeConfig } from '../../shared/schemas/config.schema';import type { GoogleTokens, GoogleOAuthConfig } from '../../shared/types/calendar.types';import { logger } from './logger';+import {+ encryptSecret,+ decryptSecret,+ isEncrypted,+ writeFileSecure,+ restrictPermissions,+ FILE_MODE,+ DIR_MODE,+} from './secure-store';const CONFIG_FILENAME = 'config.json';const RUNTIME_FILENAME = 'runtime.json';@@ -11,11 +20,51 @@ const AUTH_CONFIG_FILENAME = 'auth_config.json';const GOOGLE_OAUTH_FILENAME = 'google_oauth.json';const GOOGLE_TOKENS_FILENAME = 'google_tokens.enc';const GOOGLE_TOKENS_FALLBACK_FILENAME = 'google_tokens.json';+const ENCRYPTION_KEY_FILENAME = '.mcp-encryption-key';export function getConfigPath(): string {return path.join(app.getPath('userData'), CONFIG_FILENAME);}+/**+ * Tightens permissions on the app data directory and the files inside it that+ * hold recordings metadata, transcripts and tokens.+ *+ * Electron creates userData as 0755, which leaves everything readable by other+ * local accounts. Run once at startup, before any of it is opened.+ */+export function secureUserDataDir(): void {+ const userDataPath = app.getPath('userData');++ restrictPermissions(userDataPath, DIR_MODE);++ const sensitivePaths = [+ path.join(userDataPath, CONFIG_FILENAME),+ path.join(userDataPath, GOOGLE_TOKENS_FILENAME),+ path.join(userDataPath, GOOGLE_TOKENS_FALLBACK_FILENAME),+ path.join(userDataPath, ENCRYPTION_KEY_FILENAME),+ ];++ for (const sensitivePath of sensitivePaths) {+ restrictPermissions(sensitivePath, FILE_MODE);+ }++ for (const dirName of ['data', 'logs']) {+ const dirPath = path.join(userDataPath, dirName);+ restrictPermissions(dirPath, DIR_MODE);++ try {+ if (fs.existsSync(dirPath)) {+ for (const entry of fs.readdirSync(dirPath)) {+ restrictPermissions(path.join(dirPath, entry), FILE_MODE);+ }+ }+ } catch (error) {+ logger.warn({ error, dirPath }, 'Failed to restrict permissions on app data directory');+ }+ }+}+export function getRuntimeConfigPath(): string {// Runtime config is in the app directory (for development) or resources (for production)if (app.isPackaged) {@@ -32,12 +81,56 @@ export function getAuthConfigPath(): string {return path.join(app.getAppPath(), AUTH_CONFIG_FILENAME);}+/**+ * Fields in config.json that hold secrets and are encrypted at rest.+ */+const SECRET_CONFIG_KEYS = ['accessToken', 'apiKey'] as const;++function decryptConfigSecrets(config: AppConfig): { config: AppConfig; hadPlaintext: boolean } {+ let hadPlaintext = false;++ for (const key of SECRET_CONFIG_KEYS) {+ const value = config[key];+ if (typeof value !== 'string' || !value) continue;++ if (isEncrypted(value)) {+ config[key] = decryptSecret(value);+ } else {+ // Written by a build that stored secrets in the clear.+ hadPlaintext = true;+ }+ }++ return { config, hadPlaintext };+}++function encryptConfigSecrets(config: AppConfig): AppConfig {+ const encrypted: AppConfig = { ...config };++ for (const key of SECRET_CONFIG_KEYS) {+ const value = encrypted[key];+ if (typeof value === 'string' && value && !isEncrypted(value)) {+ encrypted[key] = encryptSecret(value);+ }+ }++ return encrypted;+}+export function loadAppConfig(): AppConfig {const configPath = getConfigPath();try {if (fs.existsSync(configPath)) {const data = fs.readFileSync(configPath, 'utf-8');- return JSON.parse(data) as AppConfig;+ const { config, hadPlaintext } = decryptConfigSecrets(JSON.parse(data) as AppConfig);++ // Upgrade legacy plaintext configs the first time they are read.+ if (hadPlaintext) {+ logger.info({ configPath }, 'Migrating plaintext app config to encrypted storage');+ saveAppConfig(config);+ }++ return config;}} catch (error) {logger.error({ error, configPath }, 'Failed to load app config');@@ -48,11 +141,7 @@ export function loadAppConfig(): AppConfig {export function saveAppConfig(config: AppConfig): void {const configPath = getConfigPath();try {- const dir = path.dirname(configPath);- if (!fs.existsSync(dir)) {- fs.mkdirSync(dir, { recursive: true });- }- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));+ writeFileSecure(configPath, JSON.stringify(encryptConfigSecrets(config), null, 2));logger.info({ configPath }, 'App config saved');} catch (error) {logger.error({ error, configPath }, 'Failed to save app config');@@ -162,15 +251,15 @@ export function saveGoogleTokens(tokens: GoogleTokens): void {if (safeStorage.isEncryptionAvailable()) {const encrypted = safeStorage.encryptString(json);- fs.writeFileSync(tokenPath, encrypted);+ writeFileSecure(tokenPath, encrypted);// Clean up fallback if it existsif (fs.existsSync(fallbackPath)) {fs.unlinkSync(fallbackPath);}logger.info('Google tokens saved (encrypted)');} else {- // Fallback to plain JSON (Linux without keyring)- fs.writeFileSync(fallbackPath, json, 'utf-8');+ // Fallback to plain JSON (Linux without keyring) - owner-readable only+ writeFileSecure(fallbackPath, json);logger.warn('Google tokens saved (unencrypted - no keyring available)');}} catch (error) {diff --git a/src/main/lib/logger.ts b/src/main/lib/logger.tsindex eb4bd6f..8f3e979 100644--- a/src/main/lib/logger.ts+++ b/src/main/lib/logger.ts@@ -9,7 +9,7 @@ function getLogsDir(): string {const logsDir = path.join(userDataPath, 'logs');if (!fs.existsSync(logsDir)) {- fs.mkdirSync(logsDir, { recursive: true });+ fs.mkdirSync(logsDir, { recursive: true, mode: 0o700 });}return logsDir;@@ -19,6 +19,34 @@ function getLogsDir(): string {}}+/**+ * Keys scrubbed from every log line.+ *+ * Logs go to disk unencrypted and are the first thing pasted into a bug+ * report, so credentials must never reach them. Each key is also matched one+ * and two levels down, which covers the common `logger.info({ config })` and+ * `logger.error({ error, server })` shapes.+ */+const REDACTED_KEYS = [+ 'apiKey',+ 'api_key',+ 'accessToken',+ 'access_token',+ 'refreshToken',+ 'refresh_token',+ 'sessionToken',+ 'session_token',+ 'uploadToken',+ 'token',+ 'password',+ 'secret',+ 'authorization',+ 'env',+ 'headers',+];++const REDACTED_PATHS = REDACTED_KEYS.flatMap((key) => [key, `*.${key}`, `*.*.${key}`]);+function getLogFilePath(): string {const logsDir = getLogsDir();const date = new Date().toISOString().split('T')[0];@@ -33,7 +61,8 @@ let fileStream: fs.WriteStream | null = null;function getFileStream(): fs.WriteStream {if (!fileStream) {const logPath = getLogFilePath();- fileStream = fs.createWriteStream(logPath, { flags: 'a' });+ // Owner-only: logs carry meeting content and error dumps.+ fileStream = fs.createWriteStream(logPath, { flags: 'a', mode: 0o600 });// Log the log file location at startupconsole.log(`[Logger] Writing logs to: ${logPath}`);@@ -74,6 +103,10 @@ export const logger = pino(base: {pid: process.pid,},+ redact: {+ paths: REDACTED_PATHS,+ censor: '[redacted]',+ },},// In production, use our multi-stream; in dev, let pino-pretty handle itisDev ? undefined : multiStreamdiff --git a/src/main/lib/secure-store.ts b/src/main/lib/secure-store.tsnew file mode 100644index 0000000..9b0ad1a--- /dev/null+++ b/src/main/lib/secure-store.ts@@ -0,0 +1,104 @@+/**+ * Secure Store+ *+ * Small helpers for keeping secrets out of plaintext on disk.+ *+ * Two layers, in order of preference:+ *+ * 1. `safeStorage` — Electron's OS-backed encryption (Keychain on macOS, DPAPI+ * on Windows, libsecret on Linux). The key never touches our disk.+ * 2. AES-256-GCM with a local key file (see `../utils/encryption`) — used only+ * when the OS keyring is unavailable, e.g. a headless Linux box.+ *+ * Values are tagged with a version prefix so plaintext written by older builds+ * can be recognised and migrated in place on first read.+ */++import { safeStorage } from 'electron';+import fs from 'fs';+import path from 'path';+import { createChildLogger } from './logger';++const logger = createChildLogger('secure-store');++/** Marks a value encrypted with `safeStorage`, base64-encoded. */+const SAFE_STORAGE_PREFIX = 'enc:v1:';++/** Owner-only file and directory modes. */+export const FILE_MODE = 0o600;+export const DIR_MODE = 0o700;++export function isEncrypted(value: string): boolean {+ return value.startsWith(SAFE_STORAGE_PREFIX);+}++/**+ * Encrypts a secret for storage on disk.+ *+ * Returns the value unchanged when no OS keyring is available — callers keep+ * working, and `decryptSecret` round-trips plaintext transparently.+ */+export function encryptSecret(plaintext: string): string {+ if (!plaintext) return plaintext;++ try {+ if (safeStorage.isEncryptionAvailable()) {+ return SAFE_STORAGE_PREFIX + safeStorage.encryptString(plaintext).toString('base64');+ }+ } catch (error) {+ logger.error({ error }, 'safeStorage encryption failed, storing value as-is');+ }++ return plaintext;+}++/**+ * Decrypts a value written by `encryptSecret`. Values without the version+ * prefix are assumed to be plaintext from an older build and returned as-is.+ */+export function decryptSecret(value: string): string {+ if (!value || !isEncrypted(value)) return value;++ try {+ const payload = Buffer.from(value.slice(SAFE_STORAGE_PREFIX.length), 'base64');+ return safeStorage.decryptString(payload);+ } catch (error) {+ logger.error({ error }, 'Failed to decrypt secret');+ return '';+ }+}++/**+ * Writes a file readable only by the current user.+ *+ * `fs.writeFileSync`'s mode is ignored when the file already exists, so an+ * explicit chmod follows the write to fix up files created by older builds.+ */+export function writeFileSecure(filePath: string, data: string | Buffer): void {+ const dir = path.dirname(filePath);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });+ }++ fs.writeFileSync(filePath, data, { mode: FILE_MODE });++ try {+ fs.chmodSync(filePath, FILE_MODE);+ } catch (error) {+ logger.warn({ error, filePath }, 'Failed to restrict file permissions');+ }+}++/**+ * Tightens permissions on a file or directory that already exists.+ * Best-effort: Windows ACLs do not map onto POSIX modes.+ */+export function restrictPermissions(targetPath: string, mode: number = FILE_MODE): void {+ try {+ if (fs.existsSync(targetPath)) {+ fs.chmodSync(targetPath, mode);+ }+ } catch (error) {+ logger.warn({ error, targetPath }, 'Failed to restrict permissions');+ }+}diff --git a/src/main/lib/url-guard.ts b/src/main/lib/url-guard.tsnew file mode 100644index 0000000..7b69c44--- /dev/null+++ b/src/main/lib/url-guard.ts@@ -0,0 +1,179 @@+/**+ * URL Guard+ *+ * Validation for user-supplied outbound URLs (workflow webhooks).+ *+ * Webhooks are fired from the main process, which sits behind the user's+ * firewall and next to this app's own loopback API. An unvalidated URL turns+ * that into a server-side request forgery primitive: `http://127.0.0.1:51731`+ * would replay meeting data into the local API, and `http://169.254.169.254`+ * reaches the cloud metadata service on a hosted runner.+ *+ * Names are resolved before the verdict, so `evil.test` pointing at 127.0.0.1+ * is rejected too.+ */++import dns from 'dns';+import net from 'net';++export interface UrlValidationResult {+ valid: boolean;+ error?: string;+}++const ALLOWED_PROTOCOLS = ['http:', 'https:'];++/** IPv4 CIDR blocks that must never be reachable from a webhook. */+const BLOCKED_V4_RANGES: Array<{ cidr: string; label: string }> = [+ { cidr: '0.0.0.0/8', label: 'unspecified' },+ { cidr: '10.0.0.0/8', label: 'private' },+ { cidr: '100.64.0.0/10', label: 'carrier-grade NAT' },+ { cidr: '127.0.0.0/8', label: 'loopback' },+ { cidr: '169.254.0.0/16', label: 'link-local / cloud metadata' },+ { cidr: '172.16.0.0/12', label: 'private' },+ { cidr: '192.0.0.0/24', label: 'IETF protocol assignments' },+ { cidr: '192.168.0.0/16', label: 'private' },+ { cidr: '198.18.0.0/15', label: 'benchmarking' },+ { cidr: '224.0.0.0/4', label: 'multicast' },+ { cidr: '240.0.0.0/4', label: 'reserved' },+];++function ipv4ToInt(ip: string): number | null {+ const parts = ip.split('.');+ if (parts.length !== 4) return null;++ let value = 0;+ for (const part of parts) {+ const octet = Number(part);+ if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;+ value = value * 256 + octet;+ }+ return value;+}++function isInV4Range(ip: string, cidr: string): boolean {+ const [range, bitsRaw] = cidr.split('/');+ const bits = Number(bitsRaw);++ const ipInt = ipv4ToInt(ip);+ const rangeInt = ipv4ToInt(range);+ if (ipInt === null || rangeInt === null) return false;++ // `<<` is a 32-bit signed op in JS; `>>> 0` keeps the mask unsigned.+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;+ return (ipInt & mask) === (rangeInt & mask);+}++/**+ * True when the address is loopback, private, link-local or otherwise+ * unroutable on the public internet.+ */+export function isBlockedAddress(address: string): { blocked: boolean; reason?: string } {+ const normalized = address.replace(/^\[|\]$/g, '');+ const version = net.isIP(normalized);++ if (version === 4) {+ for (const { cidr, label } of BLOCKED_V4_RANGES) {+ if (isInV4Range(normalized, cidr)) {+ return { blocked: true, reason: `${label} address (${normalized})` };+ }+ }+ return { blocked: false };+ }++ if (version === 6) {+ const lower = normalized.toLowerCase();++ // IPv4-mapped (::ffff:127.0.0.1) — judge on the embedded IPv4 address.+ const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);+ if (mapped) return isBlockedAddress(mapped[1]);++ if (lower === '::' || lower === '::1') {+ return { blocked: true, reason: `loopback address (${normalized})` };+ }+ // fc00::/7 unique-local, fe80::/10 link-local+ if (/^f[cd]/.test(lower) || /^fe[89ab]/.test(lower)) {+ return { blocked: true, reason: `private address (${normalized})` };+ }+ return { blocked: false };+ }++ return { blocked: false };+}++/**+ * Checks the shape of a webhook URL without touching the network.+ * Use before persisting a workflow; `validateWebhookUrl` adds DNS resolution.+ */+export function validateWebhookUrlSyntax(rawUrl: string): UrlValidationResult {+ if (!rawUrl || !rawUrl.trim()) {+ return { valid: false, error: 'Webhook URL is required' };+ }++ let url: URL;+ try {+ url = new URL(rawUrl.trim());+ } catch {+ return { valid: false, error: 'Webhook URL is not a valid URL' };+ }++ if (!ALLOWED_PROTOCOLS.includes(url.protocol)) {+ return {+ valid: false,+ error: `Webhook URL must use http or https (got "${url.protocol.replace(':', '')}")`,+ };+ }++ if (url.username || url.password) {+ return { valid: false, error: 'Webhook URL must not embed credentials' };+ }++ const hostname = url.hostname.replace(/^\[|\]$/g, '');+ if (!hostname) {+ return { valid: false, error: 'Webhook URL must include a host' };+ }++ // Catch literal IPs and obvious local names before any DNS lookup.+ const literal = isBlockedAddress(hostname);+ if (literal.blocked) {+ return { valid: false, error: `Webhook URL points at a ${literal.reason}` };+ }++ if (hostname === 'localhost' || hostname.endsWith('.localhost') || hostname.endsWith('.local')) {+ return { valid: false, error: 'Webhook URL must not point at the local machine' };+ }++ return { valid: true };+}++/**+ * Full validation: syntax, then every address the host resolves to.+ *+ * A hostname can resolve to several addresses; all of them must be public,+ * otherwise the request could still land internally.+ */+export async function validateWebhookUrl(rawUrl: string): Promise<UrlValidationResult> {+ const syntax = validateWebhookUrlSyntax(rawUrl);+ if (!syntax.valid) return syntax;++ const hostname = new URL(rawUrl.trim()).hostname.replace(/^\[|\]$/g, '');++ // Literal IPs were already checked and need no lookup.+ if (net.isIP(hostname)) return { valid: true };++ let addresses: dns.LookupAddress[];+ try {+ addresses = await dns.promises.lookup(hostname, { all: true });+ } catch {+ return { valid: false, error: `Could not resolve webhook host "${hostname}"` };+ }++ for (const { address } of addresses) {+ const { blocked, reason } = isBlockedAddress(address);+ if (blocked) {+ return { valid: false, error: `Webhook host "${hostname}" resolves to a ${reason}` };+ }+ }++ return { valid: true };+}diff --git a/src/main/server/index.ts b/src/main/server/index.tsindex 377eeeb..bf9e3cd 100644--- a/src/main/server/index.ts+++ b/src/main/server/index.ts@@ -10,14 +10,42 @@ const logger = createChildLogger('http-server');let server: ReturnType<typeof serve> | null = null;+/**+ * The API only ever serves this app's own renderer, so it listens on loopback+ * only. Binding the default (all interfaces) would expose meetings, transcripts+ * and the VideoDB API key to anything on the same network.+ */+const BIND_HOSTNAME = '127.0.0.1';++/**+ * Only the app's own renderer may call the API. Electron renderers load from+ * `file://` (origin `null`) in production and from the Vite dev server in+ * development, so accept those plus loopback origins on any port.+ */+function isAllowedOrigin(origin: string): string | null {+ if (!origin || origin === 'null') return origin || 'null';++ try {+ const { hostname, protocol } = new URL(origin);+ if (protocol !== 'http:' && protocol !== 'https:') return null;+ if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1') {+ return origin;+ }+ } catch {+ return null;+ }++ return null;+}+export function createServer(port: number) {const app = new Hono();- // CORS middleware+ // CORS middleware — loopback only (see isAllowedOrigin)app.use('*',cors({- origin: '*',+ origin: isAllowedOrigin,allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],allowHeaders: ['Content-Type', 'x-access-token'],})@@ -60,11 +88,12 @@ export async function startServer(port: number, maxRetries: number = 10): Promis{fetch: app.fetch,port: attemptPort,+ hostname: BIND_HOSTNAME,},(info) => {server = serverInstance;currentPort = info.port;- logger.info({ port: info.port }, 'HTTP server started');+ logger.info({ port: info.port, hostname: BIND_HOSTNAME }, 'HTTP server started');resolve(info.port);});diff --git a/src/main/server/trpc/procedures/auth.ts b/src/main/server/trpc/procedures/auth.tsindex 211de0c..febba04 100644--- a/src/main/server/trpc/procedures/auth.ts+++ b/src/main/server/trpc/procedures/auth.ts@@ -71,7 +71,8 @@ export const authRouter = router({return {success: true,- accessToken: user.accessToken,+ // The stored column holds a hash, so hand back the token we generated.+ accessToken,name: user.name,};} catch (error) {diff --git a/src/main/server/trpc/procedures/transcription.ts b/src/main/server/trpc/procedures/transcription.tsindex 9013d3b..1ac09e1 100644--- a/src/main/server/trpc/procedures/transcription.ts+++ b/src/main/server/trpc/procedures/transcription.ts@@ -4,7 +4,9 @@ import {StartTranscriptionOutputSchema,} from '../../../../shared/schemas/capture.schema';import { createChildLogger } from '../../../lib/logger';-import { loadRuntimeConfig } from '../../../lib/config';+import { loadRuntimeConfig, loadAppConfig } from '../../../lib/config';+import { toLanguageCode } from '../../../../shared/constants/languages';+import { startRtstreamTranscript } from '../../../services/rtstream-transcript.service';import { connect } from 'videodb';import type { CaptureSessionFull, RTStream } from 'videodb';@@ -34,11 +36,18 @@ async function startRealtimeTranscriptionWithWs(micWsConnectionId?: string,sysAudioWsConnectionId?: string,screenWsConnectionId?: string,- apiUrl?: string+ apiUrl?: string,+ languageCode?: string): Promise<void> {try {logger.info(- { sessionId: captureSessionId, micWsConnectionId, sysAudioWsConnectionId, screenWsConnectionId },+ {+ sessionId: captureSessionId,+ micWsConnectionId,+ sysAudioWsConnectionId,+ screenWsConnectionId,+ languageCode,+ },'[Transcript] Starting transcription for session');@@ -177,10 +186,15 @@ async function startRealtimeTranscriptionWithWs(if (mics.length > 0 && micWsConnectionId) {const micStream = mics[0];logger.info(- { rtstreamId: micStream.id, wsConnectionId: micWsConnectionId },+ { rtstreamId: micStream.id, wsConnectionId: micWsConnectionId, languageCode },'[Transcript] Starting transcript on mic');- await micStream.startTranscript(micWsConnectionId);+ await startRtstreamTranscript(micStream, {+ apiKey,+ apiUrl,+ wsConnectionId: micWsConnectionId,+ languageCode,+ });logger.info('[Transcript] Mic transcription started');} else if (mics.length > 0) {logger.info('[Transcript] Mic stream found but no ws_connection_id provided, skipping');@@ -190,10 +204,15 @@ async function startRealtimeTranscriptionWithWs(if (systemAudios.length > 0 && sysAudioWsConnectionId) {const sysStream = systemAudios[0];logger.info(- { rtstreamId: sysStream.id, wsConnectionId: sysAudioWsConnectionId },+ { rtstreamId: sysStream.id, wsConnectionId: sysAudioWsConnectionId, languageCode },'[Transcript] Starting transcript on sys_audio');- await sysStream.startTranscript(sysAudioWsConnectionId);+ await startRtstreamTranscript(sysStream, {+ apiKey,+ apiUrl,+ wsConnectionId: sysAudioWsConnectionId,+ languageCode,+ });logger.info('[Transcript] System audio transcription started');} else if (systemAudios.length > 0) {logger.info('[Transcript] System audio stream found but no ws_connection_id provided, skipping');@@ -220,10 +239,21 @@ export const transcriptionRouter = router({.input(StartTranscriptionInputSchema).output(StartTranscriptionOutputSchema).mutation(async ({ input, ctx }) => {- const { sessionId, micWsConnectionId, sysAudioWsConnectionId, screenWsConnectionId } = input;+ const {+ sessionId,+ micWsConnectionId,+ sysAudioWsConnectionId,+ screenWsConnectionId,+ languageCode: requestedLanguage,+ } = input;++ // The saved preference is the default; a request may override it per call.+ const languageCode = toLanguageCode(+ requestedLanguage ?? loadAppConfig().transcriptionLanguage+ );logger.info(- { sessionId, micWsConnectionId, sysAudioWsConnectionId, screenWsConnectionId },+ { sessionId, micWsConnectionId, sysAudioWsConnectionId, screenWsConnectionId, languageCode },'Starting transcription and visual indexing');@@ -260,7 +290,8 @@ export const transcriptionRouter = router({micWsConnectionId,sysAudioWsConnectionId,screenWsConnectionId,- apiUrl+ apiUrl,+ languageCode).catch((error) => {logger.error({ error, sessionId }, 'Background transcription task failed');});diff --git a/src/main/services/rtstream-transcript.service.ts b/src/main/services/rtstream-transcript.service.tsnew file mode 100644index 0000000..2c7addc--- /dev/null+++ b/src/main/services/rtstream-transcript.service.ts@@ -0,0 +1,109 @@+/**+ * RTStream Transcript Service+ *+ * Starts real-time transcription on an RTStream, optionally pinned to a+ * language.+ *+ * The JS SDK's `RTStream.startTranscript(socketId, engine)` posts only+ * `{action, engine, ws_connection_id}` — there is no way to pass a language+ * through it (checked in videodb 0.2.5 and 0.3.0). So when the user has picked+ * a language we make the same request ourselves and add `language_code`.+ *+ * See https://github.com/video-db/call.md/issues/25.+ */++import type { RTStream } from 'videodb';+import { createChildLogger } from '../lib/logger';++const logger = createChildLogger('rtstream-transcript');++const DEFAULT_API_URL = 'https://api.videodb.io';+const DEFAULT_ENGINE = 'assemblyai';+const REQUEST_TIMEOUT_MS = 15000;++export interface StartTranscriptOptions {+ /** VideoDB API key, sent as `x-access-token`. */+ apiKey: string;+ /** Overrides the API base URL (self-hosted / staging). */+ apiUrl?: string;+ /** WebSocket connection that receives transcript events. */+ wsConnectionId?: string;+ /** BCP-47 code, or undefined to let the engine decide. */+ languageCode?: string;+ /** Transcription engine; defaults to the SDK's own default. */+ engine?: string;+}++/**+ * Starts transcription, adding `language_code` when one is configured.+ *+ * Falls back to the SDK call if the direct request fails, so a rejected or+ * unrecognised language degrades to English rather than to no transcript.+ */+export async function startRtstreamTranscript(+ stream: RTStream,+ options: StartTranscriptOptions+): Promise<void> {+ const { apiKey, apiUrl, wsConnectionId, languageCode, engine = DEFAULT_ENGINE } = options;++ if (!languageCode) {+ await stream.startTranscript(wsConnectionId);+ return;+ }++ try {+ await postTranscriptStart(stream.id, { apiKey, apiUrl, wsConnectionId, languageCode, engine });+ logger.info({ rtstreamId: stream.id, languageCode }, 'Started transcript with language');+ } catch (error) {+ logger.warn(+ { rtstreamId: stream.id, languageCode, error: (error as Error).message },+ 'Language-specific transcript start failed; falling back to the default engine language'+ );+ await stream.startTranscript(wsConnectionId);+ }+}++/**+ * POST /rtstream/{id}/transcription — the request the SDK makes, plus+ * `language_code`. Body keys are snake_case, matching the VideoDB API.+ */+async function postTranscriptStart(+ rtstreamId: string,+ options: Required<Pick<StartTranscriptOptions, 'apiKey' | 'engine' | 'languageCode'>> &+ Pick<StartTranscriptOptions, 'apiUrl' | 'wsConnectionId'>+): Promise<void> {+ const baseUrl = (options.apiUrl || DEFAULT_API_URL).replace(/\/+$/, '');+ const url = `${baseUrl}/rtstream/${encodeURIComponent(rtstreamId)}/transcription`;++ const body: Record<string, unknown> = {+ action: 'start',+ engine: options.engine,+ language_code: options.languageCode,+ };++ if (options.wsConnectionId) {+ body.ws_connection_id = options.wsConnectionId;+ }++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);++ try {+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-access-token': options.apiKey,+ },+ body: JSON.stringify(body),+ signal: controller.signal,+ });++ if (!response.ok) {+ const detail = await response.text().catch(() => '');+ throw new Error(`HTTP ${response.status} ${response.statusText}${detail ? `: ${detail}` : ''}`);+ }+ } finally {+ clearTimeout(timeout);+ }+}diff --git a/src/main/services/workflow-webhook.service.ts b/src/main/services/workflow-webhook.service.tsindex cb006db..a88542e 100644--- a/src/main/services/workflow-webhook.service.ts+++ b/src/main/services/workflow-webhook.service.ts@@ -9,6 +9,7 @@import { v4 as uuid } from 'uuid';import { createChildLogger } from '../lib/logger';import { getEnabledWorkflows } from '../db';+import { validateWebhookUrl } from '../lib/url-guard';import type {WorkflowWebhookPayload,WorkflowWebhookResult,@@ -107,6 +108,23 @@ async function callWebhook(try {logger.debug({ workflowId, workflowName, url: webhookUrl }, 'Calling webhook');+ // Re-check at call time: a stored host can be re-pointed at an internal+ // address long after it was saved.+ const validation = await validateWebhookUrl(webhookUrl);+ if (!validation.valid) {+ logger.warn(+ { workflowId, workflowName, error: validation.error },+ 'Refusing to call webhook with an unsafe URL'+ );+ return {+ workflowId,+ workflowName,+ success: false,+ error: validation.error,+ responseTime: Date.now() - startTime,+ };+ }+const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), WEBHOOK_TIMEOUT_MS);@@ -119,6 +137,9 @@ async function callWebhook(},body: JSON.stringify(payload),signal: controller.signal,+ // Following a redirect would skip the checks above and could land on an+ // internal address.+ redirect: 'error',});clearTimeout(timeoutId);diff --git a/src/main/utils/encryption.ts b/src/main/utils/encryption.tsindex c8cada3..3a5aac4 100644--- a/src/main/utils/encryption.ts+++ b/src/main/utils/encryption.ts@@ -3,6 +3,12 @@ import { app } from 'electron';import path from 'path';import fs from 'fs';import { logger } from '../lib/logger';+import {+ encryptSecret,+ decryptSecret,+ isEncrypted,+ writeFileSecure,+} from '../lib/secure-store';const ALGORITHM = 'aes-256-gcm';const KEY_LENGTH = 32; // 256 bits@@ -20,15 +26,23 @@ function getKeyPath(): string {return path.join(userDataPath, KEY_FILE_NAME);}+/**+ * Persists the key, wrapped by the OS keyring when one is available.+ *+ * Without this the key sits in plaintext beside the data it protects, which+ * makes the encryption cosmetic against anyone who can read the app data dir.+ */+function writeKey(key: Buffer): void {+ writeFileSecure(getKeyPath(), encryptSecret(key.toString('hex')));+}+/*** Generates a new encryption key and saves it to disk*/function generateKey(): Buffer {const key = crypto.randomBytes(KEY_LENGTH);- const keyPath = getKeyPath();- // Write key with restricted permissions- fs.writeFileSync(keyPath, key.toString('hex'), { mode: 0o600 });+ writeKey(key);logger.info('Generated new MCP encryption key');return key;@@ -46,12 +60,19 @@ function loadKey(): Buffer {try {if (fs.existsSync(keyPath)) {- const keyHex = fs.readFileSync(keyPath, 'utf-8');+ const stored = fs.readFileSync(keyPath, 'utf-8').trim();+ const wasWrapped = isEncrypted(stored);+ const keyHex = wasWrapped ? decryptSecret(stored) : stored;encryptionKey = Buffer.from(keyHex, 'hex');if (encryptionKey.length !== KEY_LENGTH) {logger.warn('Invalid encryption key length, regenerating');encryptionKey = generateKey();+ } else if (!wasWrapped) {+ // Upgrade a key written in the clear by an older build. The key value+ // is unchanged, so anything already encrypted with it still decrypts.+ logger.info('Wrapping plaintext MCP encryption key with OS keyring');+ writeKey(encryptionKey);}} else {encryptionKey = generateKey();diff --git a/src/main/windows/widget.window.ts b/src/main/windows/widget.window.tsindex 3f57fe1..b36a562 100644--- a/src/main/windows/widget.window.ts+++ b/src/main/windows/widget.window.ts@@ -89,7 +89,8 @@ export function createWidgetWindow(): BrowserWindow {preload: path.join(__dirname, '..', '..', 'preload', 'widget.js'),nodeIntegration: false,contextIsolation: true,- sandbox: false,+ // The widget preload only uses contextBridge/ipcRenderer.+ sandbox: true,},});diff --git a/src/preload/index.ts b/src/preload/index.tsindex 1ac104e..49933d2 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -381,6 +381,12 @@ const api: IpcApi = {app: {getSettings: () => ipcRenderer.invoke('get-settings'),+ saveSettings: (settings: {+ accessToken?: string;+ userName?: string;+ apiKey?: string;+ transcriptionLanguage?: string;+ }) => ipcRenderer.invoke('save-settings', settings),getServerPort: () => ipcRenderer.invoke('get-server-port'),logout: () => ipcRenderer.invoke('logout'),openExternalLink: (url: string) => ipcRenderer.invoke('open-external-link', url),diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 0ee0ec1..109b655 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -493,7 +493,7 @@ export function App() {// Recording ID to navigate to after recording endsconst [pendingRecordingNavigation, setPendingRecordingNavigation] = useState<number | null>(null);// Settings tab to show when navigating to settings- const [initialSettingsTab, setInitialSettingsTab] = useState<'account' | 'notifications' | 'mcpServers' | 'workflows' | null>(null);+ const [initialSettingsTab, setInitialSettingsTab] = useState<'account' | 'notifications' | 'transcription' | 'mcpServers' | 'workflows' | null>(null);// Pending tab change when user needs to confirm discarding meeting setupconst [pendingTabChange, setPendingTabChange] = useState<Tab | null>(null);@@ -501,6 +501,13 @@ export function App() {const sessionStore = useSessionStore();const meetingSetupStore = useMeetingSetupStore();+ // The API key and language preference live in the main process, not in+ // localStorage, so pull them in once on startup.+ const hydrateConfig = useConfigStore((state) => state.hydrateFromMain);+ React.useEffect(() => {+ void hydrateConfig();+ }, [hydrateConfig]);+// Check if meeting setup has any user-entered dataconst hasMeetingSetupData = () => {return (diff --git a/src/renderer/components/settings/SettingsView.tsx b/src/renderer/components/settings/SettingsView.tsxindex 799ccb4..b1fa83f 100644--- a/src/renderer/components/settings/SettingsView.tsx+++ b/src/renderer/components/settings/SettingsView.tsx@@ -20,9 +20,10 @@ import {import { useConfigStore } from '../../stores/config.store';import { MCPServersPanel } from './MCPServersPanel';import { NotificationsPanel } from './NotificationsPanel';+import { TranscriptionPanel } from './TranscriptionPanel';import { WorkflowsPanel } from './WorkflowsPanel';-type SettingsTab = 'account' | 'notifications' | 'mcpServers' | 'workflows';+type SettingsTab = 'account' | 'notifications' | 'transcription' | 'mcpServers' | 'workflows';interface SettingsViewProps {initialTab?: SettingsTab | null;@@ -40,6 +41,7 @@ function SettingsTabs({const tabs: { id: SettingsTab; label: string }[] = [{ id: 'account', label: 'Account' },{ id: 'notifications', label: 'Notifications' },+ { id: 'transcription', label: 'Transcription' },{ id: 'mcpServers', label: 'MCP Servers' },{ id: 'workflows', label: 'Workflows' },];@@ -50,7 +52,7 @@ function SettingsTabs({<buttonkey={tab.id}onClick={() => onTabChange(tab.id)}- className={`flex-1 px-[16px] py-[12px] rounded-[12px] text-[14px] font-medium transition-all ${+ className={`flex-1 px-[12px] py-[12px] rounded-[12px] text-[14px] font-medium transition-all whitespace-nowrap ${activeTab === tab.id? 'bg-[#ff4000] text-white font-semibold shadow-[0px_1px_2px_0px_rgba(0,0,0,0.05)]': 'text-[#464646] hover:bg-[#efefef]'@@ -234,7 +236,15 @@ function AccountPanel() {if (!newApiKey.trim()) return;setIsSaving(true);try {- configStore.setConfig({ apiKey: newApiKey.trim() });+ const apiKey = newApiKey.trim();+ // Persist through the main process - the renderer no longer keeps the+ // key in localStorage.+ const result = await window.electronAPI.app.saveSettings({ apiKey });+ if (!result.success) {+ throw new Error(result.error || 'Failed to save API key');+ }++ configStore.setConfig({ apiKey });setIsEditingApiKey(false);setNewApiKey('');} catch (err) {@@ -405,6 +415,8 @@ export function SettingsView({ initialTab, onClearInitialTab }: SettingsViewPropreturn <AccountPanel />;case 'notifications':return <NotificationsPanel />;+ case 'transcription':+ return <TranscriptionPanel />;case 'mcpServers':return <MCPServersPanel />;case 'workflows':diff --git a/src/renderer/components/settings/TranscriptionPanel.tsx b/src/renderer/components/settings/TranscriptionPanel.tsxnew file mode 100644index 0000000..d09c7bb--- /dev/null+++ b/src/renderer/components/settings/TranscriptionPanel.tsx@@ -0,0 +1,122 @@+/**+ * Transcription Settings Panel+ *+ * Picks the language used for real-time transcription. The choice is stored in+ * the main process and sent to VideoDB as `language_code` when a meeting starts.+ */++import React, { useEffect, useState } from 'react';+import { Check, Loader2, AlertCircle } from 'lucide-react';+import {+ AUTO_LANGUAGE,+ TRANSCRIPTION_LANGUAGES,+} from '../../../shared/constants/languages';+import { useConfigStore } from '../../stores/config.store';++export function TranscriptionPanel() {+ const transcriptionLanguage = useConfigStore((state) => state.transcriptionLanguage);+ const setConfig = useConfigStore((state) => state.setConfig);++ const [isSaving, setIsSaving] = useState(false);+ const [savedAt, setSavedAt] = useState<number | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (savedAt === null) return;+ const timeout = setTimeout(() => setSavedAt(null), 2000);+ return () => clearTimeout(timeout);+ }, [savedAt]);++ const handleSelect = async (code: string) => {+ if (code === transcriptionLanguage) return;++ const previous = transcriptionLanguage;+ setConfig({ transcriptionLanguage: code });+ setIsSaving(true);+ setError(null);++ try {+ const result = await window.electronAPI.app.saveSettings({ transcriptionLanguage: code });+ if (!result.success) {+ throw new Error(result.error || 'Failed to save language');+ }+ setSavedAt(Date.now());+ } catch (err) {+ // Put the store back so the UI keeps matching what is stored on disk.+ setConfig({ transcriptionLanguage: previous });+ setError(err instanceof Error ? err.message : 'Failed to save language');+ } finally {+ setIsSaving(false);+ }+ };++ return (+ <div className="flex flex-col gap-[20px]">+ <div className="bg-white border border-[#e4e4ec] rounded-[14px] overflow-hidden">+ <div className="flex items-center justify-between px-[20px] py-[16px] border-b border-[#ededf3]">+ <div>+ <h3 className="text-[16px] font-semibold text-[#141420] leading-[22.5px]">+ Transcription Language+ </h3>+ <p className="text-[13px] text-[#969696] mt-[2px]">+ Applies to the next meeting you record+ </p>+ </div>+ {isSaving ? (+ <Loader2 className="w-[16px] h-[16px] text-[#ec5b16] animate-spin" />+ ) : savedAt ? (+ <span className="flex items-center gap-[4px] text-[13px] font-medium text-[#059669]">+ <Check className="w-[16px] h-[16px]" />+ Saved+ </span>+ ) : null}+ </div>++ <div className="max-h-[360px] overflow-auto">+ {TRANSCRIPTION_LANGUAGES.map((language, index) => {+ const isSelected = language.code === transcriptionLanguage;++ return (+ <button+ key={language.code}+ onClick={() => handleSelect(language.code)}+ disabled={isSaving}+ className={`flex items-center justify-between w-full px-[20px] py-[14px] text-left transition-colors disabled:opacity-60 ${+ index < TRANSCRIPTION_LANGUAGES.length - 1 ? 'border-b border-[#ededf3]' : ''+ } ${isSelected ? 'bg-[rgba(255,64,0,0.04)]' : 'hover:bg-[#f7f7f7]'}`}+ >+ <span className="flex flex-col">+ <span+ className={`text-[14px] font-medium ${+ isSelected ? 'text-[#ff4000]' : 'text-[#464646]'+ }`}+ >+ {language.label}+ </span>+ <span className="text-[13px] text-[#969696]">{language.nativeLabel}</span>+ </span>+ {isSelected && <Check className="w-[18px] h-[18px] text-[#ff4000]" />}+ </button>+ );+ })}+ </div>+ </div>++ {error && (+ <div className="flex items-start gap-[8px] p-[12px] bg-[rgba(209,36,47,0.06)] border border-[rgba(209,36,47,0.19)] rounded-[10px]">+ <AlertCircle className="w-[16px] h-[16px] text-[#d1242f] shrink-0 mt-[1px]" />+ <span className="text-[13px] text-[#d1242f]">{error}</span>+ </div>+ )}++ {transcriptionLanguage !== AUTO_LANGUAGE && (+ <p className="text-[13px] text-[#969696] leading-[18px]">+ Language support depends on the VideoDB transcription backend. If the selected language+ is unavailable, transcription falls back to the engine default instead of failing.+ </p>+ )}+ </div>+ );+}++export default TranscriptionPanel;diff --git a/src/renderer/stores/config.store.ts b/src/renderer/stores/config.store.tsindex 93cc68a..0ed95c9 100644--- a/src/renderer/stores/config.store.ts+++ b/src/renderer/stores/config.store.ts@@ -1,15 +1,18 @@import { create } from 'zustand';import { persist } from 'zustand/middleware';+import { AUTO_LANGUAGE } from '../../shared/constants/languages';interface ConfigState {accessToken: string | null;userName: string | null;apiKey: string | null;apiUrl: string | null;+ transcriptionLanguage: string;onboardingComplete: boolean;setAuth: (accessToken: string, userName: string, apiKey: string) => void;setConfig: (config: Partial<ConfigState>) => void;+ hydrateFromMain: () => Promise<void>;clearAuth: () => void;isAuthenticated: () => boolean;completeOnboarding: () => void;@@ -22,16 +25,42 @@ export const useConfigStore = create<ConfigState>()(userName: null,apiKey: null,apiUrl: null,+ transcriptionLanguage: AUTO_LANGUAGE,onboardingComplete: false,setAuth: (accessToken, userName, apiKey) => {set({ accessToken, userName, apiKey });+ // The main process owns credentials across restarts (encrypted at rest).+ void window.electronAPI?.app+ ?.saveSettings({ accessToken, userName, apiKey })+ .catch(() => undefined);},setConfig: (config) => {set(config);},+ /**+ * Loads settings the renderer does not persist itself - the API key lives+ * only in the main process - and the saved transcription language.+ */+ hydrateFromMain: async () => {+ try {+ const settings = await window.electronAPI?.app?.getSettings();+ if (!settings) return;++ set((state) => ({+ apiKey: settings.apiKey ?? state.apiKey,+ apiUrl: settings.apiUrl ?? state.apiUrl,+ userName: state.userName ?? settings.userName ?? null,+ accessToken: state.accessToken ?? settings.accessToken ?? null,+ transcriptionLanguage: settings.transcriptionLanguage || AUTO_LANGUAGE,+ }));+ } catch {+ // Settings are optional; the app still works without them.+ }+ },+clearAuth: () => {set({accessToken: null,@@ -51,10 +80,13 @@ export const useConfigStore = create<ConfigState>()(}),{name: 'call-md-config',+ // The API key is deliberately absent: localStorage is plaintext on disk+ // and any renderer script can read it. The main process holds the key+ // (encrypted via the OS keyring) and rehydrates it through `get-settings`+ // on startup.partialize: (state) => ({accessToken: state.accessToken,userName: state.userName,- apiKey: state.apiKey,onboardingComplete: state.onboardingComplete,}),}diff --git a/src/shared/constants/languages.ts b/src/shared/constants/languages.tsnew file mode 100644index 0000000..9e907dc--- /dev/null+++ b/src/shared/constants/languages.ts@@ -0,0 +1,60 @@+/**+ * Transcription Languages+ *+ * Language options offered for real-time transcription. The code is sent to+ * VideoDB as `language_code` when starting an RTStream transcript.+ *+ * `auto` means "send nothing" and lets the transcription engine pick, which is+ * the historical behaviour.+ */++export const AUTO_LANGUAGE = 'auto';++export interface TranscriptionLanguage {+ /** BCP-47 code sent to the API, or `auto`. */+ code: string;+ /** English name, for the settings list. */+ label: string;+ /** Endonym, shown alongside the label. */+ nativeLabel: string;+}++export const TRANSCRIPTION_LANGUAGES: TranscriptionLanguage[] = [+ { code: AUTO_LANGUAGE, label: 'Automatic', nativeLabel: 'Detect from audio' },+ { code: 'en', label: 'English', nativeLabel: 'English' },+ { code: 'es', label: 'Spanish', nativeLabel: 'Español' },+ { code: 'fr', label: 'French', nativeLabel: 'Français' },+ { code: 'de', label: 'German', nativeLabel: 'Deutsch' },+ { code: 'it', label: 'Italian', nativeLabel: 'Italiano' },+ { code: 'pt', label: 'Portuguese', nativeLabel: 'Português' },+ { code: 'nl', label: 'Dutch', nativeLabel: 'Nederlands' },+ { code: 'hi', label: 'Hindi', nativeLabel: 'हिन्दी' },+ { code: 'ja', label: 'Japanese', nativeLabel: '日本語' },+ { code: 'ko', label: 'Korean', nativeLabel: '한국어' },+ { code: 'zh', label: 'Chinese', nativeLabel: '中文' },+ { code: 'ru', label: 'Russian', nativeLabel: 'Русский' },+ { code: 'ar', label: 'Arabic', nativeLabel: 'العربية' },+ { code: 'tr', label: 'Turkish', nativeLabel: 'Türkçe' },+ { code: 'pl', label: 'Polish', nativeLabel: 'Polski' },+ { code: 'id', label: 'Indonesian', nativeLabel: 'Bahasa Indonesia' },+ { code: 'vi', label: 'Vietnamese', nativeLabel: 'Tiếng Việt' },+];++const LANGUAGE_CODES = new Set(TRANSCRIPTION_LANGUAGES.map((language) => language.code));++export function isSupportedLanguage(code: string): boolean {+ return LANGUAGE_CODES.has(code);+}++/**+ * Normalises a stored preference into the code to send to the API.+ * Returns `undefined` for `auto`, an unknown code, or nothing set.+ */+export function toLanguageCode(preference: string | undefined): string | undefined {+ if (!preference || preference === AUTO_LANGUAGE) return undefined;+ return isSupportedLanguage(preference) ? preference : undefined;+}++export function getLanguageLabel(code: string): string {+ return TRANSCRIPTION_LANGUAGES.find((language) => language.code === code)?.label ?? code;+}diff --git a/src/shared/schemas/capture.schema.ts b/src/shared/schemas/capture.schema.tsindex 59cdba8..610d921 100644--- a/src/shared/schemas/capture.schema.ts+++ b/src/shared/schemas/capture.schema.ts@@ -16,6 +16,12 @@ export const StartTranscriptionInputSchema = z.object({micWsConnectionId: z.string().optional(),sysAudioWsConnectionId: z.string().optional(),screenWsConnectionId: z.string().optional(),+ /**+ * Overrides the saved transcription language for this session.+ * 'auto' (or omitted) lets the engine decide.+ * See shared/constants/languages.+ */+ languageCode: z.string().optional(),});export const StartTranscriptionOutputSchema = z.object({diff --git a/src/shared/schemas/config.schema.ts b/src/shared/schemas/config.schema.tsindex 1ea935f..69645eb 100644--- a/src/shared/schemas/config.schema.ts+++ b/src/shared/schemas/config.schema.ts@@ -10,6 +10,16 @@ export const AppConfigSchema = z.object({userName: z.string().optional(),apiKey: z.string().optional(),widgetPosition: WidgetPositionSchema.optional(),+ /** BCP-47 code for real-time transcription, or 'auto'. See shared/constants/languages. */+ transcriptionLanguage: z.string().optional(),+});++/** Fields the renderer is allowed to write back through `app.saveSettings`. */+export const SaveSettingsInputSchema = z.object({+ accessToken: z.string().optional(),+ userName: z.string().optional(),+ apiKey: z.string().optional(),+ transcriptionLanguage: z.string().optional(),});export type WidgetPosition = z.infer<typeof WidgetPositionSchema>;@@ -25,5 +35,6 @@ export const ServerConfigOutputSchema = z.object({});export type AppConfig = z.infer<typeof AppConfigSchema>;+export type SaveSettingsInput = z.infer<typeof SaveSettingsInputSchema>;export type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;export type ServerConfigOutput = z.infer<typeof ServerConfigOutputSchema>;diff --git a/src/shared/types/ipc.types.ts b/src/shared/types/ipc.types.tsindex fa9503f..daee76b 100644--- a/src/shared/types/ipc.types.ts+++ b/src/shared/types/ipc.types.ts@@ -223,7 +223,14 @@ export interface IpcApi {userName?: string;apiKey?: string;apiUrl?: string;+ transcriptionLanguage?: string;}>;+ saveSettings: (settings: {+ accessToken?: string;+ userName?: string;+ apiKey?: string;+ transcriptionLanguage?: string;+ }) => Promise<{ success: boolean; error?: string }>;getServerPort: () => Promise<number>;logout: () => Promise<void>;openExternalLink: (url: string) => Promise<void>;diff --git a/tasks/todo.md b/tasks/todo.mdnew file mode 100644index 0000000..8c6e0e8--- /dev/null+++ b/tasks/todo.md@@ -0,0 +1,151 @@+# Open issues — implementation plan++Branch: `fix/security-hardening-and-issues`++Covers the three open issues on `video-db/call.md`:++- [#27](https://github.com/video-db/call.md/issues/27) — Security & Privacy Audit+- [#25](https://github.com/video-db/call.md/issues/25) — Non-English real-time transcription+- [#29](https://github.com/video-db/call.md/issues/29) — Where is the Windows installer?++---++## Findings (verified before writing code)++| Claim | Verdict | Evidence |+| --- | --- | --- |+| Plaintext credentials in app data JSON | **True** | `src/main/lib/config.ts` writes `config.json` with `apiKey` + `accessToken` via plain `fs.writeFileSync` |+| Plaintext credentials in SQLite `users` | **True** | `users.api_key` / `users.access_token` stored raw (`src/main/db/schema.ts:6`) |+| MCP env vars stored unencrypted | **False (already fixed)** | `connection-orchestrator.service.ts` calls `encryptCredentials()`; `mcp-client.service.ts` decrypts |+| MCP OAuth tokens unencrypted | **False (already fixed)** | `mcp-auth.service.ts` encrypts before `upsertMCPOauthToken` |+| ...but the AES key itself is plaintext on disk | **True** | `src/main/utils/encryption.ts:31` writes the raw key next to the data it protects |+| CORS accepts all origins | **True** | `src/main/server/index.ts:20` `origin: '*'` |+| API server reachable off-box | **True (not in report)** | `serve({fetch, port})` with no `hostname` → Node binds `0.0.0.0`/`::` |+| Webhook URLs unvalidated (SSRF) | **True** | `workflow-webhook.service.ts` `fetch(webhookUrl)` with zero validation |+| Electron sandbox disabled | **True** | `sandbox: false` in `src/main/index.ts:144` and `widget.window.ts:92`; both preloads only use `contextBridge`/`ipcRenderer`, so sandbox is safe to enable |+| SQLite world-readable | **True** | `new Database(dbPath)` → mode 0644 |+| Logs may contain secrets | **True** | no pino `redact` config |+| Renderer persists API key to localStorage | **True (not in report)** | `config.store.ts` `partialize` includes `apiKey` |++**#25** — `startTranscript()` in the JS SDK (checked 0.2.5 *and* 0.3.0) sends only+`{action, engine, ws_connection_id}`. There has never been a `language_code` param, so+patching `rtstream.js` could not have worked. The app must send `language_code` itself.++**#29** — There is no Windows installer. `@videodb/[email protected]` ships binaries for+`darwin-x64` and `darwin-arm64` only (`binaryConfig.checksums`), and every `.exe` path on+`artifacts.videodb.io/call.md/` returns 403 while the `.dmg` returns 200. The README's+"available for macOS and Windows" is inaccurate.++---++## Tasks++### Issue #27 — Security hardening+- [x] Bind the local HTTP server to `127.0.0.1` instead of all interfaces+- [x] Restrict CORS to loopback origins; drop the wildcard+- [x] Store `config.json` secrets with Electron `safeStorage` (OS keychain), with transparent migration of existing plaintext configs+- [x] Encrypt `users.api_key` at rest; store `users.access_token` as a SHA-256 hash+- [x] Wrap the AES key file with `safeStorage` so it is no longer plaintext-next-to-data+- [x] Validate webhook URLs (block non-HTTP(S), loopback, private/link-local/CGNAT ranges, cloud metadata IPs) at create, update, test and call time+- [x] Enable the Electron `sandbox` on both windows+- [x] Restrict file permissions: userData `0700`, SQLite DB + config + logs `0600`+- [x] Redact secrets from logs via pino `redact`+- [x] Stop persisting the API key in renderer localStorage++### Issue #25 — Non-English transcription+- [x] Add `transcriptionLanguage` to `AppConfig` + a language list shared with the renderer+- [x] Send `language_code` to `POST /rtstream/{id}/transcription` (the SDK omits the field)+- [x] Fall back to the SDK call when the language is `auto`+- [x] Add a **Transcription** settings tab with a language picker+- [x] Document the remaining server-side dependency++### Issue #29 — Windows installer+- [x] Replace the inaccurate platform claim in the README with a verified support table+- [x] Add build-from-source instructions + `dist:win` / `dist:linux` scripts+- [x] Fail with a clear message (not a cryptic crash) when recording on an unsupported OS++### Verification+- [x] `npm run typecheck` — no new errors (2 pre-existing failures in+ `LiveAssistPanel.tsx` are unchanged from `main`)+- [x] `npm test` — 23 unit tests+- [x] App launches, migrates and serves on an isolated `--user-data-dir`+- [ ] `npm run lint` — **cannot run**: the `lint` script calls `eslint`, which is+ not a dependency of this repo (pre-existing, unrelated to this branch)++---++## Review++### What changed++**#27 — security hardening**++| Fix | Where |+| --- | --- |+| Server binds `127.0.0.1` (was all interfaces) | `src/main/server/index.ts` |+| CORS restricted to loopback origins (was `*`) | `src/main/server/index.ts` |+| `config.json` secrets encrypted via OS keyring, migrated on read | `src/main/lib/config.ts`, `src/main/lib/secure-store.ts` |+| `users.api_key` encrypted, `users.access_token` hashed, both migrated on startup | `src/main/db/index.ts` |+| AES key file wrapped by the keyring instead of sitting in plaintext | `src/main/utils/encryption.ts` |+| Webhook URLs validated (scheme, credentials, DNS, private ranges, redirects) | `src/main/lib/url-guard.ts`, `ipc/workflows.ts`, `workflow-webhook.service.ts` |+| Chromium sandbox enabled on all three windows | `src/main/index.ts`, `windows/widget.window.ts`, `ipc/app.ts` |+| userData `0700`; DB, config, tokens, logs `0600` | `src/main/lib/config.ts`, `db/index.ts`, `lib/logger.ts` |+| Credential-shaped fields redacted from logs | `src/main/lib/logger.ts` |+| API key no longer written to renderer localStorage | `src/renderer/stores/config.store.ts` |++Two report items needed no code: MCP env vars and MCP OAuth tokens were already+encrypted. What was wrong there is that the *key* was plaintext on disk — fixed+above.++**#25 — non-English transcription.** The app now sends `language_code` on+`POST /rtstream/{id}/transcription`. It could not do this through the SDK:+`RTStream.startTranscript()` posts `{action, engine, ws_connection_id}` and has+no language parameter in any published version, which is why the reporter's+`rtstream.js` patch had no effect. `rtstream-transcript.service.ts` makes the+request directly when a language is set and falls back to the SDK call+otherwise, so an unsupported language degrades to the engine default instead of+killing the transcript. Settings → Transcription picks the language.++**#29 — Windows installer.** There is none, and the README claimed otherwise.+`@videodb/[email protected]` publishes `darwin-x64` and `darwin-arm64` binaries+only, and every `.exe` path under `artifacts.videodb.io/call.md/` 403s while the+`.dmg` 200s. Replaced the claim with a verified support table, documented+building on Windows/Linux, added `dist:win` / `dist:linux`, and made+`recorder-start-recording` return a clear message on unsupported platforms+instead of failing inside the native layer.++### Evidence++Run against a build on an isolated `--user-data-dir` (the machine's real+Call.md data was left untouched):++```+listening socket TCP 127.0.0.1:51799 (LISTEN) # unpatched build: TCP *:51731+GET loopback 200+GET LAN IP connection refused+Origin: evil.com no Access-Control-Allow-Origin+Origin: localhost access-control-allow-origin: http://localhost:51730+recordings.list 401 UNAUTHORIZED without a token+userData / db drwx------ / -rw------- # unpatched build: -rw-r--r--+```++22 integration assertions inside a real Electron process cover the upgrade path:+a pre-existing user with a plaintext key and token still resolves after+migration, new credentials never appear in the DB file, and a legacy plaintext+`config.json` is rewritten encrypted on first read.++### Deliberate limits++- **`language_code` still depends on the backend.** The client-side gap is+ closed, but the reporter also observed the parameter not reaching AssemblyAI.+ That is server-side and outside this repo; the UI says so rather than+ implying a language will definitely work.+- **Windows recording is not enabled.** It cannot be from this repo — it needs+ a Windows build of the capture engine in `@videodb/recorder`.+- **`auth_config.json` is still plaintext.** It is a bootstrap file that the app+ deletes immediately after use; encrypting it would break the external tooling+ that writes it.+- **Recording metadata is not encrypted at rest.** Report item #5. Encrypting+ transcripts in SQLite would break search and every existing query; the file is+ now `0600` inside a `0700` directory, which is the meaningful part of that+ finding. Full-database encryption (SQLCipher) is a separate piece of work.diff --git a/tests/languages.test.ts b/tests/languages.test.tsnew file mode 100644index 0000000..ec68fce--- /dev/null+++ b/tests/languages.test.ts@@ -0,0 +1,49 @@+/**+ * Tests for transcription language handling (issue #25).+ *+ * Run with: npm test+ */++import test from 'node:test';+import assert from 'node:assert/strict';+import {+ AUTO_LANGUAGE,+ TRANSCRIPTION_LANGUAGES,+ isSupportedLanguage,+ toLanguageCode,+ getLanguageLabel,+} from '../src/shared/constants/languages';++test('auto means "send no language_code"', () => {+ assert.equal(toLanguageCode(AUTO_LANGUAGE), undefined);+ assert.equal(toLanguageCode(undefined), undefined);+ assert.equal(toLanguageCode(''), undefined);+});++test('supported languages pass through unchanged', () => {+ assert.equal(toLanguageCode('ja'), 'ja');+ assert.equal(toLanguageCode('es'), 'es');+ assert.equal(toLanguageCode('en'), 'en');+});++test('unknown codes fall back to auto rather than being sent', () => {+ assert.equal(toLanguageCode('klingon'), undefined);+ assert.equal(toLanguageCode('xx-YY'), undefined);+});++test('the language list is well formed', () => {+ const codes = TRANSCRIPTION_LANGUAGES.map((language) => language.code);++ assert.equal(codes[0], AUTO_LANGUAGE, 'auto should be listed first');+ assert.equal(new Set(codes).size, codes.length, 'codes must be unique');++ for (const language of TRANSCRIPTION_LANGUAGES) {+ assert.ok(language.label.length > 0, `${language.code} needs a label`);+ assert.ok(language.nativeLabel.length > 0, `${language.code} needs a native label`);+ }+});++test('Japanese is selectable — the case from issue #25', () => {+ assert.equal(isSupportedLanguage('ja'), true);+ assert.equal(getLanguageLabel('ja'), 'Japanese');+});diff --git a/tests/secure-store.test.ts b/tests/secure-store.test.tsnew file mode 100644index 0000000..729ca63--- /dev/null+++ b/tests/secure-store.test.ts@@ -0,0 +1,132 @@+/**+ * Tests for secret-at-rest handling (issue #27).+ *+ * `secure-store` sits in front of the user's API key and access token, so a+ * round-trip bug locks people out of their account. Electron is stubbed via the+ * require cache so this runs under plain Node.+ *+ * Run with: npm test+ */++import test from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import Module from 'node:module';++const tempUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'call-md-secure-store-'));++/** Reversible stand-in for the OS keyring, so round-trips are observable. */+let encryptionAvailable = true;++const electronStub = {+ app: {+ getPath: (name: string) => (name === 'userData' ? tempUserData : os.tmpdir()),+ isPackaged: false,+ },+ safeStorage: {+ isEncryptionAvailable: () => encryptionAvailable,+ encryptString: (plaintext: string) => {+ if (!encryptionAvailable) throw new Error('encryption unavailable');+ return Buffer.from(`keyring:${plaintext}`, 'utf-8');+ },+ decryptString: (buffer: Buffer) => {+ const value = buffer.toString('utf-8');+ if (!value.startsWith('keyring:')) throw new Error('not keyring ciphertext');+ return value.slice('keyring:'.length);+ },+ },+};++// Resolve 'electron' to the stub before secure-store (or the logger) requires it.+const electronPath = require.resolve('electron');+require.cache[electronPath] = Object.assign(new Module(electronPath), {+ id: electronPath,+ filename: electronPath,+ loaded: true,+ exports: electronStub,+});++// eslint-disable-next-line @typescript-eslint/no-var-requires+const secureStore = require('../src/main/lib/secure-store') as typeof import('../src/main/lib/secure-store');+const { encryptSecret, decryptSecret, isEncrypted, writeFileSecure } = secureStore;++test('secrets round-trip through the keyring', () => {+ encryptionAvailable = true;++ const secret = 'vdb-api-key-0123456789';+ const stored = encryptSecret(secret);++ assert.notEqual(stored, secret, 'stored value must not be the plaintext');+ assert.equal(isEncrypted(stored), true);+ assert.equal(decryptSecret(stored), secret);+});++test('plaintext from older builds is read back unchanged', () => {+ const legacy = 'plaintext-api-key-from-v1.0.4';++ assert.equal(isEncrypted(legacy), false);+ assert.equal(decryptSecret(legacy), legacy);+});++test('encrypting twice does not double-wrap', () => {+ encryptionAvailable = true;++ const once = encryptSecret('token');+ assert.equal(decryptSecret(once), 'token');+ // Callers guard with isEncrypted(); confirm the guard is the thing that works.+ assert.equal(isEncrypted(once), true);+});++test('falls back to plaintext when no keyring is available', () => {+ encryptionAvailable = false;++ const stored = encryptSecret('no-keyring-here');+ assert.equal(stored, 'no-keyring-here', 'value stays usable without a keyring');+ assert.equal(decryptSecret(stored), 'no-keyring-here');++ encryptionAvailable = true;+});++test('empty values are left alone', () => {+ assert.equal(encryptSecret(''), '');+ assert.equal(decryptSecret(''), '');+});++test('secure writes are owner-only', { skip: process.platform === 'win32' }, () => {+ const target = path.join(tempUserData, 'nested', 'config.json');+ writeFileSecure(target, JSON.stringify({ apiKey: 'x' }));++ assert.equal(fs.statSync(target).mode & 0o777, 0o600);+ assert.equal(fs.statSync(path.dirname(target)).mode & 0o777, 0o700);+});++test('an existing world-readable file is tightened on rewrite', { skip: process.platform === 'win32' }, () => {+ const target = path.join(tempUserData, 'legacy.json');+ fs.writeFileSync(target, '{}', { mode: 0o644 });+ assert.equal(fs.statSync(target).mode & 0o777, 0o644);++ writeFileSecure(target, '{"migrated":true}');+ assert.equal(fs.statSync(target).mode & 0o777, 0o600);+});++test('access tokens hash to a stable 64-char digest', () => {+ // Mirrors hashAccessToken() in src/main/db/index.ts, which cannot be imported+ // here without pulling in better-sqlite3's native build.+ const hash = (token: string) => crypto.createHash('sha256').update(token).digest('hex');++ const token = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';+ assert.match(hash(token), /^[a-f0-9]{64}$/);+ assert.equal(hash(token), hash(token), 'lookups depend on the hash being deterministic');+ assert.notEqual(hash(token), hash(`${token}x`));++ // The migration detects already-hashed rows with this shape.+ assert.equal(/^[a-f0-9]{64}$/.test(hash(token)), true);+ assert.equal(/^[a-f0-9]{64}$/.test(token), false, 'a raw UUID must not look hashed');+});++process.on('exit', () => {+ fs.rmSync(tempUserData, { recursive: true, force: true });+});diff --git a/tests/url-guard.test.ts b/tests/url-guard.test.tsnew file mode 100644index 0000000..28d0e8d--- /dev/null+++ b/tests/url-guard.test.ts@@ -0,0 +1,97 @@+/**+ * Tests for the webhook URL guard (issue #27, SSRF).+ *+ * Run with: npm test+ */++import test from 'node:test';+import assert from 'node:assert/strict';+import {+ validateWebhookUrlSyntax,+ validateWebhookUrl,+ isBlockedAddress,+} from '../src/main/lib/url-guard';++test('accepts ordinary public webhook URLs', () => {+ for (const url of [+ 'https://hooks.zapier.com/hooks/catch/123/abc',+ 'https://n8n.example.com/webhook/meeting-done',+ 'http://example.com/hook',+ 'https://example.com:8443/hook?token=x',+ ]) {+ assert.equal(validateWebhookUrlSyntax(url).valid, true, url);+ }+});++test('rejects non-HTTP schemes', () => {+ for (const url of ['file:///etc/passwd', 'ftp://example.com/x', 'javascript:alert(1)']) {+ const result = validateWebhookUrlSyntax(url);+ assert.equal(result.valid, false, url);+ }+});++test('rejects loopback and local hostnames', () => {+ for (const url of [+ 'http://127.0.0.1:51731/api/trpc',+ 'http://localhost:51731/api',+ 'http://[::1]:51731/api',+ 'http://myapp.local/hook',+ 'http://0.0.0.0/hook',+ ]) {+ assert.equal(validateWebhookUrlSyntax(url).valid, false, url);+ }+});++test('rejects private and link-local ranges', () => {+ for (const url of [+ 'http://10.1.2.3/hook',+ 'http://172.16.5.4/hook',+ 'http://192.168.1.10/hook',+ 'http://169.254.169.254/latest/meta-data/', // cloud metadata+ 'http://100.64.0.1/hook', // carrier-grade NAT+ ]) {+ assert.equal(validateWebhookUrlSyntax(url).valid, false, url);+ }+});++test('rejects credentials embedded in the URL', () => {+ assert.equal(validateWebhookUrlSyntax('https://user:[email protected]/hook').valid, false);+});++test('rejects empty and malformed input', () => {+ assert.equal(validateWebhookUrlSyntax('').valid, false);+ assert.equal(validateWebhookUrlSyntax(' ').valid, false);+ assert.equal(validateWebhookUrlSyntax('not a url').valid, false);+});++test('classifies IPv6 forms', () => {+ assert.equal(isBlockedAddress('::1').blocked, true);+ assert.equal(isBlockedAddress('fe80::1').blocked, true);+ assert.equal(isBlockedAddress('fd00::1').blocked, true);+ assert.equal(isBlockedAddress('::ffff:127.0.0.1').blocked, true);+ assert.equal(isBlockedAddress('2606:4700:4700::1111').blocked, false);+});++test('keeps public IPv4 addresses next to blocked ranges usable', () => {+ // Boundary checks - one address either side of each blocked block.+ assert.equal(isBlockedAddress('9.255.255.255').blocked, false);+ assert.equal(isBlockedAddress('10.0.0.0').blocked, true);+ assert.equal(isBlockedAddress('11.0.0.0').blocked, false);+ assert.equal(isBlockedAddress('172.15.255.255').blocked, false);+ assert.equal(isBlockedAddress('172.32.0.0').blocked, false);+ assert.equal(isBlockedAddress('169.253.0.1').blocked, false);+ assert.equal(isBlockedAddress('8.8.8.8').blocked, false);+});++test('resolves hostnames before allowing them', async () => {+ // localhost.localtest.me and friends resolve to 127.0.0.1; use a name that is+ // guaranteed to fail resolution instead of depending on the network.+ const result = await validateWebhookUrl('https://this-host-does-not-exist.invalid/hook');+ assert.equal(result.valid, false);+ assert.match(result.error ?? '', /resolve/i);+});++test('literal public IPs skip the DNS lookup and pass', async () => {+ const result = await validateWebhookUrl('https://8.8.8.8/hook');+ assert.equal(result.valid, true);+});