diff --git a/.changeset/private-files.md b/.changeset/private-files.md new file mode 100644 index 00000000..5a309944 --- /dev/null +++ b/.changeset/private-files.md @@ -0,0 +1,5 @@ +--- +'lyra': patch +--- + +On macOS and Linux, Lyra's own files (session audio and documents, saved voices, the search index and API keys, and notes in the default `~/.lyra` folder) are now readable only by your account, and folders from earlier versions are tightened at startup; on a shared computer other accounts could read them before. Saved voices and API keys are now written durably, so a power cut right after saving can't empty them. Settings now says the built-in summary model is for non-commercial use only, with a link to its licence, and the README says when Lyra goes online (model downloads and the update check). diff --git a/README.md b/README.md index dc2fda00..b26cd474 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,17 @@ Grant microphone access when prompted. Models download on first use: - **Whisper `large-v3-turbo`** (~575 MB), on the first recording - **Speaker models** (~46 MB), on the first meeting -- **Local notes model** (~2 GB), only if you turn on local meeting notes +- **Local notes model** (~2 GB), only if you turn on local meeting notes. It's Qwen2.5 3B, licensed + for non-commercial use only (see [THIRD_PARTY.md](THIRD_PARTY.md)) +- **Search model** (~146 MB), only if you turn on search by meaning On macOS, capturing a call's audio needs Screen Recording permission. ## Privacy -Everything runs on this computer by default. The only exception is meeting notes **with a cloud model**, which you have to switch on yourself. It sends the meeting transcript (never audio or voiceprints) to the provider you pick, using your own key, which is stored in the system keychain. Recording other people usually requires their consent. +Everything runs on this computer by default. Your notes, transcripts and audio go to a cloud service only for meeting notes **with a cloud model**, which you have to switch on yourself. It sends the meeting transcript (never audio or voiceprints) to the provider you pick, using your own key, which is stored in the system keychain. Recording other people usually requires their consent. + +Lyra also goes online, without sending any of your content, to download the models above on first use (from Hugging Face and GitHub), and to check GitHub for a new release when it starts and every four hours after. The update check can't be turned off yet. On macOS and Linux, Lyra's own files (session audio and documents, voiceprints, the search index, keys, and notes in its default folder) can be read only by your account. ## Build diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index dc337576..6e3babda 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -18,12 +18,28 @@ upstream revision and checked against its sha256 before it is loaded (`src/main/ | Silero VAD v5.1.2, ggml build (`ggml-silero-v5.1.2.bin`) | Dropping non-speech inside each chunk, in whisper.cpp | MIT ([snakers4/silero-vad](https://github.com/snakers4/silero-vad)) | [ggml-org/whisper-vad @ 9ffd54a](https://huggingface.co/ggml-org/whisper-vad/tree/9ffd54a1e1ee413ddf265af9913beaf518d1639b) | | Silero VAD v5, ONNX (`silero_vad_v5.onnx`) | Where a recording's chunks start and end | MIT ([snakers4/silero-vad](https://github.com/snakers4/silero-vad)) | [k2-fsa/sherpa-onnx release `asr-models`](https://github.com/k2-fsa/sherpa-onnx/releases/tag/asr-models), pinned by sha256 | | NVIDIA Parakeet TDT 0.6B v3, int8 ONNX | Evals only (`--asr parakeet`); not downloaded by the app | CC BY 4.0 ([model card](https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3)); attribution: NVIDIA | [csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8 @ ed5d745](https://huggingface.co/csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8/tree/ed5d745623472f97cfc2e6c2916ee248798fc5a8) | +| nomic-embed-text-v1.5, Q8_0 GGUF (`nomic-embed-text-v1.5.Q8_0.gguf`) | Search by meaning (opt-in); downloaded only when it's turned on | Apache-2.0 ([model card](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5)) | [nomic-ai/nomic-embed-text-v1.5-GGUF @ 0188c9b](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/tree/0188c9bf409793f810680a5a431e7b899c46104c) | | Qwen2.5-3B-Instruct, Q4_K_M GGUF | Local meeting notes and titles (opt-in) | **Qwen Research License: non-commercial use only**; commercial use needs a licence from Alibaba Cloud | [Qwen/Qwen2.5-3B-Instruct-GGUF @ 7dabda4](https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF/tree/7dabda4d13d513e3e842b20f0d435c732f172cbe) | "Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved." Lyra is a non-commercial project, which the licence allows. Lyra's own code is MIT, but the model's terms bind whoever runs it: anyone using Lyra commercially must leave local -summaries off or get a licence from Alibaba Cloud. +summaries off or get a licence from Alibaba Cloud. Settings says so where local summaries are +offered. + +Each model's sha256 and size are in the source file that downloads it (`src/main/models.ts`, +`src/main/meeting/speakerModel.ts`, `src/main/meeting/notesLocal.ts`, +`src/main/searchIndex/service.ts`). + +## Fonts + +Bundled into the window from the `@fontsource` packages, under the +[SIL Open Font License 1.1](https://openfontlicense.org), which travels with each package's files. + +| Font | Licence | +| --- | --- | +| IBM Plex Sans, IBM Plex Mono (`@fontsource/ibm-plex-sans`, `@fontsource/ibm-plex-mono`) | SIL OFL 1.1, Copyright IBM Corp. | +| Literata (`@fontsource-variable/literata`) | SIL OFL 1.1, Copyright The Literata Project Authors | ## Word lists diff --git a/apps/lyra/src/main/atomicFile.test.ts b/apps/lyra/src/main/atomicFile.test.ts index fce768af..91d427fc 100644 --- a/apps/lyra/src/main/atomicFile.test.ts +++ b/apps/lyra/src/main/atomicFile.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { describe, expect, it } from 'vitest' @@ -18,6 +18,16 @@ describe('atomic writes', () => { expect(readdirSync(root).sort()).toEqual(['doc.json', 'note.txt']) }) + it.skipIf(process.platform === 'win32')('writes files only their owner can read', async () => { + const root = dir() + const path = join(root, 'voices.json') + writeFileSync(path, 'old', { mode: 0o644 }) + await writeFileAtomic(path, 'new') + writeFileAtomicSync(join(root, 'doc.json'), 'doc') + expect(statSync(path).mode & 0o777).toBe(0o600) + expect(statSync(join(root, 'doc.json')).mode & 0o777).toBe(0o600) + }) + it('never interleaves overlapping writes of one file', async () => { const root = dir() const path = join(root, 'settings.json') diff --git a/apps/lyra/src/main/atomicFile.ts b/apps/lyra/src/main/atomicFile.ts index 8f8c179a..8ced944d 100644 --- a/apps/lyra/src/main/atomicFile.ts +++ b/apps/lyra/src/main/atomicFile.ts @@ -3,6 +3,7 @@ import { closeSync, fsyncSync, openSync, renameSync, unlinkSync, writeSync } fro import { open, rename, unlink } from 'node:fs/promises' import { basename, dirname, join } from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' +import { PRIVATE_FILE_MODE } from './privateFiles' /** * Durable file replacement: write a temp file beside the target, fsync it, then rename it over @@ -67,7 +68,8 @@ function renameOverSync(temp: string, path: string): void { export async function writeFileAtomic(path: string, data: string | Uint8Array): Promise { const temp = tempPathFor(path) try { - const handle = await open(temp, 'wx') + // Owner-only (privateFiles.ts); the rename carries the mode over to the target. + const handle = await open(temp, 'wx', PRIVATE_FILE_MODE) try { await handle.writeFile(data) await handle.sync() @@ -84,7 +86,7 @@ export async function writeFileAtomic(path: string, data: string | Uint8Array): export function writeFileAtomicSync(path: string, data: string | Uint8Array): void { const temp = tempPathFor(path) try { - const fd = openSync(temp, 'wx') + const fd = openSync(temp, 'wx', PRIVATE_FILE_MODE) try { const bytes = typeof data === 'string' ? Buffer.from(data, 'utf8') : data let written = 0 diff --git a/apps/lyra/src/main/checkpoints.ts b/apps/lyra/src/main/checkpoints.ts index e859bebf..1720140a 100644 --- a/apps/lyra/src/main/checkpoints.ts +++ b/apps/lyra/src/main/checkpoints.ts @@ -3,6 +3,7 @@ import { join } from 'node:path' import type { z } from 'zod' import { writeFileAtomic } from './atomicFile' import { log } from './log' +import { PRIVATE_DIR_MODE } from './privateFiles' import { sessionCheckpointDir } from './sessionStore' /** @@ -46,7 +47,7 @@ export async function readCheckpoint( /** Replaces the checkpoint atomically; a failure is logged, never thrown (it only costs a redo). */ export async function writeCheckpoint(id: string, name: CheckpointName, value: unknown): Promise { try { - await mkdir(sessionCheckpointDir(id), { recursive: true }) + await mkdir(sessionCheckpointDir(id), { recursive: true, mode: PRIVATE_DIR_MODE }) await writeFileAtomic(pathOf(id, name), JSON.stringify(value)) } catch (error) { log('checkpoint', 'could not save a checkpoint', { id, name, error: errorMessage(error) }) diff --git a/apps/lyra/src/main/index.ts b/apps/lyra/src/main/index.ts index 0fe899fa..d289b601 100644 --- a/apps/lyra/src/main/index.ts +++ b/apps/lyra/src/main/index.ts @@ -10,11 +10,9 @@ import { powerMonitor, session, shell, - type IpcMainEvent, - type IpcMainInvokeEvent, type WebContents } from 'electron' -import { release } from 'node:os' +import { homedir, release } from 'node:os' import { join } from 'node:path' import { electronApp, optimizer, is } from '@electron-toolkit/utils' import { systemAudioSource } from './systemAudioSource' @@ -52,12 +50,14 @@ import { reexportDirtySessions, restoreSession, flushAllSessions, + sessionsRoot, getSessionPage as getPage, listSessions as listPages, openSessionFor, saveSessionPage as savePage } from './sessionStore' import { registerHotkeys, unregisterHotkeys } from './hotkey' +import { tightenDir } from './privateFiles' import { registerMicPrompt, stopMicPrompt } from './micprompt' import { exportIgnoredApps, importIgnoredApps } from './ignoredAppsFile' import { registerOverlay, watchMainWindow } from './overlay' @@ -65,8 +65,8 @@ import { registerPowerHandling, watchSessionEnd } from './power' import { startResourceLog } from './resources' import { getMainWindow, - isFromMainWindow, registerSessionIpc, + requireMainWindow, onSessionState, resetSessionState, setMainWindow, @@ -209,14 +209,6 @@ function isMainContents(contents: WebContents): boolean { return contents === getMainWindow()?.webContents } -/** - * Settings, keys and the notes folder are changed only from the main window. The overlay shares - * its preload, and its page has no use for them. - */ -function requireMainWindow(event: IpcMainEvent | IpcMainInvokeEvent): void { - if (!isFromMainWindow(event)) throw new Error('Not allowed from this window') -} - /** The app's top band (`--band` in styles.css), which the window controls share. */ const BAND_HEIGHT = 56 @@ -377,10 +369,20 @@ function registerIpc(): void { requireMainWindow(event) return revealNotesFolder() }) - ipcMain.handle('pages:save', (_event, page: unknown) => savePage(SavePageArg.parse(page))) - ipcMain.handle('pages:delete', (_event, id: unknown) => deletePage(PageIdArg.parse(id))) - ipcMain.handle('pages:restore', (_event, id: unknown) => restoreSession(PageIdArg.parse(id))) - ipcMain.handle('pages:reveal', (_event, id: unknown) => { + ipcMain.handle('pages:save', (event, page: unknown) => { + requireMainWindow(event) + return savePage(SavePageArg.parse(page)) + }) + ipcMain.handle('pages:delete', (event, id: unknown) => { + requireMainWindow(event) + return deletePage(PageIdArg.parse(id)) + }) + ipcMain.handle('pages:restore', (event, id: unknown) => { + requireMainWindow(event) + return restoreSession(PageIdArg.parse(id)) + }) + ipcMain.handle('pages:reveal', (event, id: unknown) => { + requireMainWindow(event) shell.showItemInFolder(resolveInNotes(PageIdArg.parse(id))) }) ipcMain.handle('sessions:open', (event, id: unknown) => @@ -654,6 +656,7 @@ void app.whenReady().then(() => { await repairInterruptedAudio().catch((error: unknown) => { log('app', 'could not repair interrupted audio', error instanceof Error ? error.message : String(error)) }) + await tightenFolders() // Sessions deleted before a crash were never emptied into the system trash. void emptySessionTrash() // A crash mid-export leaves a note file behind its document. @@ -688,6 +691,27 @@ void app.whenReady().then(() => { }) }) +/** + * Folders written before Lyra kept its files owner-only (privateFiles.ts): its data folder + * (voices, keys, the search index, settings), every session's audio and documents, and the notes + * folder only when it's Lyra's own default, never one the person chose. + */ +async function tightenFolders(): Promise { + const notes = getSettings().notesDir + const folders = { + userData: app.getPath('userData'), + sessions: sessionsRoot(), + ...(notes === join(homedir(), '.lyra') ? { notes } : {}) + } + for (const [name, folder] of Object.entries(folders)) { + const changed = await tightenDir(folder).catch((error: unknown) => { + log('app', 'could not make a folder owner-only', { folder: name, error: errorMessage(error) }) + return false + }) + if (changed) log('app', 'made a folder owner-only', { folder: name }) + } +} + /** Longest the app waits on all its own shutdown work before quitting anyway. */ const QUIT_FLUSH_MS = 12_000 /** Each step's own bound, so one slow step can't use up the others' time. */ diff --git a/apps/lyra/src/main/livePass.ts b/apps/lyra/src/main/livePass.ts index d25282f4..d6ffeb6e 100644 --- a/apps/lyra/src/main/livePass.ts +++ b/apps/lyra/src/main/livePass.ts @@ -4,6 +4,7 @@ import { join } from 'node:path' import { z } from 'zod' import type { AudioTrack } from '../shared/types' import type { TranscribedChunk } from './transcriber' +import { PRIVATE_DIR_MODE } from './privateFiles' /** * `raw/live.json`: every word transcribed while recording, across all of a session's takes. Each @@ -124,7 +125,7 @@ export async function readLiveFile(dir: string, now = new Date()): Promise/live.json` through a temporary file, so a crash mid-write leaves the old one. */ export async function writeLiveFile(dir: string, pass: Record): Promise { - await mkdir(dir, { recursive: true }) + await mkdir(dir, { recursive: true, mode: PRIVATE_DIR_MODE }) const path = join(dir, LIVE_FILE) const temp = `${path}.tmp` await writeFile(temp, JSON.stringify(pass), 'utf8') diff --git a/apps/lyra/src/main/meeting/notes.ts b/apps/lyra/src/main/meeting/notes.ts index 3f00daec..10cd076c 100644 --- a/apps/lyra/src/main/meeting/notes.ts +++ b/apps/lyra/src/main/meeting/notes.ts @@ -9,6 +9,7 @@ import type { } from '../../shared/types' import { clearCheckpoint, readCheckpoint, writeCheckpoint } from '../checkpoints' import { log } from '../log' +import { requireMainWindow } from '../session' import { settle } from '../pendingWork' import { changeSession, editSession, listSessions } from '../sessionStore' import { notesLinesOf } from './notesChunks' @@ -364,11 +365,18 @@ export function createMeetingNotes(deps: { onMeetingLabeled((pageId) => { void writeOwed(pageId) }) - ipcMain.handle('notes:generate', (_event, pageId: unknown) => generateNotes(z.string().parse(pageId), 'manual')) + // These two can send transcripts to a cloud model: the main window only. + ipcMain.handle('notes:generate', (event, pageId: unknown) => { + requireMainWindow(event) + return generateNotes(z.string().parse(pageId), 'manual') + }) ipcMain.handle('notes:summaryEdited', (_event, pageId: unknown) => edited(z.string().parse(pageId))) ipcMain.handle('notes:state', (_event, pageId: unknown) => stateOf(z.string().parse(pageId))) ipcMain.handle('notes:backfillStatus', () => backfillStatus()) - ipcMain.handle('notes:backfill', (_event, kind: unknown) => backfill(z.enum(['outdated', 'missing']).parse(kind))) + ipcMain.handle('notes:backfill', (event, kind: unknown) => { + requireMainWindow(event) + return backfill(z.enum(['outdated', 'missing']).parse(kind)) + }) ipcMain.handle('notes:stopBackfill', () => stopBackfill()) ipcMain.handle('notes:cancel', (_event, pageId: unknown) => jobs.cancel(z.string().parse(pageId), new Error(SUMMARY_STOPPED))) } diff --git a/apps/lyra/src/main/meeting/pipeline.ts b/apps/lyra/src/main/meeting/pipeline.ts index 767fee3d..c9abf8a3 100644 --- a/apps/lyra/src/main/meeting/pipeline.ts +++ b/apps/lyra/src/main/meeting/pipeline.ts @@ -18,6 +18,7 @@ import { type SpeakerMatch } from '../../shared/sessionDoc' import { log } from '../log' +import { requireMainWindow } from '../session' import { resolveInNotes } from '../pages' import { deleteSessionAudio, trackPath } from '../recorder' import { @@ -672,25 +673,30 @@ export async function similarLines(pageId: string, moved: readonly string[], fro */ export function registerMeetingPipeline(): void { ipcMain.handle('people:list', () => listPeople()) - ipcMain.handle('people:enroll', async (_event, name: unknown, pcm: unknown, self: unknown) => { + ipcMain.handle('people:enroll', async (event, name: unknown, pcm: unknown, self: unknown) => { + requireMainWindow(event) if (typeof name !== 'string') throw new Error('Invalid name') const models = await ensureSpeakerModels() const embedding = await embedVoice(pcmFrom(pcm), models) return addPerson(name, embedding, self === true) }) - ipcMain.handle('people:rename', (_event, id: unknown, name: unknown) => { + ipcMain.handle('people:rename', (event, id: unknown, name: unknown) => { + requireMainWindow(event) if (typeof id !== 'string' || typeof name !== 'string') throw new Error('Invalid input') return renamePerson(id, name) }) - ipcMain.handle('people:setSelf', (_event, id: unknown) => { + ipcMain.handle('people:setSelf', (event, id: unknown) => { + requireMainWindow(event) if (typeof id !== 'string' && id !== null) throw new Error('Invalid input') return setSelf(id) }) - ipcMain.handle('people:delete', (_event, id: unknown) => { + ipcMain.handle('people:delete', (event, id: unknown) => { + requireMainWindow(event) if (typeof id !== 'string') throw new Error('Invalid input') return deletePerson(id) }) - ipcMain.handle('people:restore', (_event, id: unknown) => { + ipcMain.handle('people:restore', (event, id: unknown) => { + requireMainWindow(event) if (typeof id !== 'string') throw new Error('Invalid input') return restorePerson(id) }) @@ -713,7 +719,8 @@ export function registerMeetingPipeline(): void { resolveInNotes(pageId) return similarLines(pageId, moved, from) }) - ipcMain.handle('sessions:audio', (_event, pageId: unknown, start: unknown, end: unknown) => { + ipcMain.handle('sessions:audio', (event, pageId: unknown, start: unknown, end: unknown) => { + requireMainWindow(event) if (typeof pageId !== 'string' || typeof start !== 'number' || typeof end !== 'number') { throw new Error('Invalid input') } diff --git a/apps/lyra/src/main/pages.ts b/apps/lyra/src/main/pages.ts index c6454b32..d186f566 100644 --- a/apps/lyra/src/main/pages.ts +++ b/apps/lyra/src/main/pages.ts @@ -11,6 +11,7 @@ import { extname, join, resolve } from 'node:path' import type { MoveNotesResult, NoteFormat, Page } from '../shared/types' import { log } from './log' import { checkSessionsDir, isNoteName, noteInRoot } from './notePath' +import { PRIVATE_DIR_MODE } from './privateFiles' import { moveSessionFiles } from './sessionStore' import { getSettings, onSettingsChanged } from './settings' @@ -108,7 +109,8 @@ export function parsePage(raw: string, id: string, mtime = new Date().toISOStrin } export async function ensurePagesDir(): Promise { - await mkdir(notesDir(), { recursive: true }) + // Owner-only when Lyra creates it; a folder the person chose keeps the modes they gave it. + await mkdir(notesDir(), { recursive: true, mode: PRIVATE_DIR_MODE }) } const pad = (value: number): string => String(value).padStart(2, '0') diff --git a/apps/lyra/src/main/privateFiles.test.ts b/apps/lyra/src/main/privateFiles.test.ts new file mode 100644 index 00000000..d5fc250e --- /dev/null +++ b/apps/lyra/src/main/privateFiles.test.ts @@ -0,0 +1,53 @@ +import { chmodSync, mkdirSync, mkdtempSync, statSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { makePrivateDir, makePrivateDirSync, tightenDir } from './privateFiles' + +const dir = (): string => mkdtempSync(join(tmpdir(), 'lyra-private-')) +const modeOf = (path: string): number => statSync(path).mode & 0o777 + +// POSIX modes; on Windows these calls do nothing, which the last case checks. +describe.skipIf(process.platform === 'win32')('owner-only folders', () => { + it('creates every missing folder 0700', async () => { + const root = dir() + await makePrivateDir(join(root, '.sessions', 'a.txt', 'audio')) + makePrivateDirSync(join(root, 'keys')) + expect(modeOf(join(root, '.sessions'))).toBe(0o700) + expect(modeOf(join(root, '.sessions', 'a.txt'))).toBe(0o700) + expect(modeOf(join(root, '.sessions', 'a.txt', 'audio'))).toBe(0o700) + expect(modeOf(join(root, 'keys'))).toBe(0o700) + }) + + it('makes an existing folder others can read owner-only, once', async () => { + const root = dir() + const sessions = join(root, '.sessions') + mkdirSync(sessions) + chmodSync(sessions, 0o755) + expect(await tightenDir(sessions)).toBe(true) + expect(modeOf(sessions)).toBe(0o700) + expect(await tightenDir(sessions)).toBe(false) + }) + + it('leaves a missing folder and a symlink alone', async () => { + const root = dir() + const target = join(root, 'elsewhere') + mkdirSync(target) + chmodSync(target, 0o755) + symlinkSync(target, join(root, 'link')) + expect(await tightenDir(join(root, 'link'))).toBe(false) + expect(modeOf(target)).toBe(0o755) + expect(await tightenDir(join(root, 'missing'))).toBe(false) + }) +}) + +describe('on Windows', () => { + it('changes nothing', async () => { + const root = dir() + const folder = join(root, 'shared') + mkdirSync(folder) + const before = statSync(folder).mode + expect(await tightenDir(folder, 'win32')).toBe(false) + expect(statSync(folder).mode).toBe(before) + }) +}) diff --git a/apps/lyra/src/main/privateFiles.ts b/apps/lyra/src/main/privateFiles.ts new file mode 100644 index 00000000..bec00610 --- /dev/null +++ b/apps/lyra/src/main/privateFiles.ts @@ -0,0 +1,51 @@ +import { chmodSync, mkdirSync } from 'node:fs' +import { chmod, lstat, mkdir } from 'node:fs/promises' + +/** + * Owner-only permissions for what Lyra keeps: transcripts, recordings of other people, + * voiceprints, the search index and API keys. With the usual umask, files come out 0644 and + * folders 0755, which on a shared machine with a traversable home folder lets every other + * account read them. Folders are made 0700 and files 0600; the user's own tools still read them. + * Windows has no POSIX modes (a folder's ACL comes from its parent), so this does nothing there. + */ + +export const PRIVATE_DIR_MODE = 0o700 +export const PRIVATE_FILE_MODE = 0o600 + +const posix = (platform: NodeJS.Platform): boolean => platform !== 'win32' + +/** + * `mkdir -p` with every folder it creates owner-only, and `path` itself made owner-only. Only for + * Lyra's own folders: never the notes folder itself, which the person may have chosen and shared. + */ +export async function makePrivateDir(path: string, platform: NodeJS.Platform = process.platform): Promise { + await mkdir(path, { recursive: true, mode: PRIVATE_DIR_MODE }) + if (posix(platform)) await chmod(path, PRIVATE_DIR_MODE) +} + +export function makePrivateDirSync(path: string, platform: NodeJS.Platform = process.platform): void { + mkdirSync(path, { recursive: true, mode: PRIVATE_DIR_MODE }) + if (posix(platform)) chmodSync(path, PRIVATE_DIR_MODE) +} + +type Stat = { isDirectory: () => boolean; uid: number; mode: number } + +function shouldTighten(info: Stat, uid: number | undefined): boolean { + // Never through a symlink (it could point anywhere), and only a folder this user owns. + if (!info.isDirectory()) return false + if (uid !== undefined && info.uid !== uid) return false + return (info.mode & 0o077) !== 0 +} + +/** + * Makes an existing folder of Lyra's owner-only, if others can reach it; true when it changed. + * A missing folder, a symlink, or one another account owns is left alone. Only the folder: what's + * inside can't be reached once it's 0700, and new files are written 0600 anyway. + */ +export async function tightenDir(path: string, platform: NodeJS.Platform = process.platform): Promise { + if (!posix(platform)) return false + const info = await lstat(path).catch(() => null) + if (!info || !shouldTighten(info, process.getuid?.())) return false + await chmod(path, PRIVATE_DIR_MODE) + return true +} diff --git a/apps/lyra/src/main/recorder.ts b/apps/lyra/src/main/recorder.ts index 6ffc1aae..3b883e67 100644 --- a/apps/lyra/src/main/recorder.ts +++ b/apps/lyra/src/main/recorder.ts @@ -15,8 +15,10 @@ import { type Untranscribed } from './livePass' import { log } from './log' +import { requireMainWindow } from './session' import { notifyLabeled } from './meeting/events' import { clearOwed, owe } from './pendingWork' +import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from './privateFiles' import { resolveInNotes } from './pages' import { sessionAudioDir, sessionRawDir, sessionsRoot, updateManifest, type TrackInfo } from './sessionStore' import { TakeWriter } from './takeWriter' @@ -176,7 +178,7 @@ async function openTrack(pageId: string, track: AudioTrack, padTo: number): Prom const path = trackPath(pageId, track) const exists = existsSync(path) && (await stat(path)).size >= HEADER_BYTES // The header goes in first, so the stream only ever appends audio and never touches it. - if (!exists) await writeFile(path, wavHeader(0)) + if (!exists) await writeFile(path, wavHeader(0), { mode: PRIVATE_FILE_MODE }) const existing = exists ? await dataBytes(path) : 0 const stream = createWriteStream(path, { flags: 'r+', start: HEADER_BYTES + existing }) const file: TrackFile = { track, path, stream, bytes: existing, base: existing, error: null } @@ -200,7 +202,7 @@ async function patchHeaders(recording: Recording): Promise { async function start(pageId: string, withSystem: boolean): Promise { resolveInNotes(pageId) if (active) await stop() - await mkdir(sessionAudioDir(pageId), { recursive: true }) + await mkdir(sessionAudioDir(pageId), { recursive: true, mode: PRIVATE_DIR_MODE }) const micBytes = await dataBytes(trackPath(pageId, 'mic')) const systemBytes = await dataBytes(trackPath(pageId, 'system')) // A take cut short by a crash can leave one track longer than the other: both carry on from the @@ -647,7 +649,8 @@ export const recorderFixture = { export function registerRecorderIpc(options: { identifySpeakers: boolean; transcribe: boolean }): void { identifySpeakers = options.identifySpeakers transcribeAudio = options.transcribe - ipcMain.handle('recorder:start', (_event, pageId: unknown, withSystem: unknown) => { + ipcMain.handle('recorder:start', (event, pageId: unknown, withSystem: unknown) => { + requireMainWindow(event) if (typeof pageId !== 'string') throw new Error('Invalid page id') return start(pageId, withSystem === true) }) diff --git a/apps/lyra/src/main/searchIndex/db.test.ts b/apps/lyra/src/main/searchIndex/db.test.ts index 49af611b..d14963c9 100644 --- a/apps/lyra/src/main/searchIndex/db.test.ts +++ b/apps/lyra/src/main/searchIndex/db.test.ts @@ -80,6 +80,12 @@ function session(id: string, options: { updatedAt?: string; passages?: Passage[] const query = (text: string): Parameters[1] => ({ text, people: [], tags: [], after: null, before: null }) describe('openIndex', () => { + it('zeroes deleted rows, so a removed voiceprint is not left in free pages', async () => { + const { client } = await opened() + const result = await client.execute('PRAGMA secure_delete') + expect(Object.values(result.rows[0] ?? {})).toContain(1) + }) + it('moves a file that is not a database aside and starts over', async () => { writeFileSync(join(dir, 'lyra.db'), 'not a database '.repeat(500)) const { client, fresh, recovered } = await opened() diff --git a/apps/lyra/src/main/searchIndex/db.ts b/apps/lyra/src/main/searchIndex/db.ts index 08deac96..8f9e1b32 100644 --- a/apps/lyra/src/main/searchIndex/db.ts +++ b/apps/lyra/src/main/searchIndex/db.ts @@ -90,6 +90,9 @@ export async function prepare(db: Client, notesDir: string): Promise { await db.execute('PRAGMA journal_mode = WAL') await db.execute('PRAGMA foreign_keys = ON') await db.execute('PRAGMA busy_timeout = 5000') + // Deleted rows (a removed person's voiceprints, a deleted session's text) are zeroed, not left + // in free pages for anyone with the file to read back. + await db.execute('PRAGMA secure_delete = ON') const version = await metaValue(db, 'meta', 'schema_version') const folder = await metaValue(db, 'meta', 'notes_dir') await prepareVectors(db) diff --git a/apps/lyra/src/main/searchIndex/openIndex.ts b/apps/lyra/src/main/searchIndex/openIndex.ts index 6a044c4b..f3a6d419 100644 --- a/apps/lyra/src/main/searchIndex/openIndex.ts +++ b/apps/lyra/src/main/searchIndex/openIndex.ts @@ -4,6 +4,7 @@ import { basename, dirname, join } from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import { pathToFileURL } from 'node:url' import { prepare, quickCheck } from './db' +import { PRIVATE_DIR_MODE } from '../privateFiles' /** * Opens the index database, and rebuilds it when it's damaged. It's derived data @@ -109,7 +110,7 @@ export async function openIndex( notesDir: string, onDamaged: (error: unknown) => void = () => undefined ): Promise { - mkdirSync(dirname(path), { recursive: true }) + mkdirSync(dirname(path), { recursive: true, mode: PRIVATE_DIR_MODE }) const marker = rebuildMarker(path) if (existsSync(marker) || !hasDatabaseHeader(path)) { if (!existsSync(marker)) onDamaged(new Error('not a database file')) diff --git a/apps/lyra/src/main/secrets.ts b/apps/lyra/src/main/secrets.ts index b80e3b13..2cad01d9 100644 --- a/apps/lyra/src/main/secrets.ts +++ b/apps/lyra/src/main/secrets.ts @@ -1,10 +1,12 @@ import { app, ipcMain, safeStorage } from 'electron' -import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises' +import { readFile, unlink } from 'node:fs/promises' import { join } from 'node:path' import { z } from 'zod' import { PROVIDERS, ProviderId, type KeySource } from '../shared/ai' +import { writeFileAtomic } from './atomicFile' import { config } from './config' import { log } from './log' +import { makePrivateDir } from './privateFiles' import { isFromMainWindow } from './session' /** @@ -81,9 +83,8 @@ export async function setApiKey(provider: ProviderId, key: string | null): Promi } const problem = cannotStoreKeys(provider) if (problem) throw new Error(problem) - await mkdir(join(path, '..'), { recursive: true }) - await writeFile(`${path}.tmp`, safeStorage.encryptString(trimmed)) - await rename(`${path}.tmp`, path) + await makePrivateDir(join(path, '..')) + await writeFileAtomic(path, safeStorage.encryptString(trimmed)) log('secrets', 'key saved', { provider }) } diff --git a/apps/lyra/src/main/session.ts b/apps/lyra/src/main/session.ts index 8f31ca97..c65e1153 100644 --- a/apps/lyra/src/main/session.ts +++ b/apps/lyra/src/main/session.ts @@ -33,6 +33,15 @@ export function isFromMainWindow(event: IpcMainEvent | IpcMainInvokeEvent): bool return win !== null && event.sender === win.webContents } +/** + * For channels only the main window uses: settings, keys, the notes folder, and anything that + * deletes data or sends a transcript to a cloud model. The overlay shares the preload, and its + * page has no use for them. + */ +export function requireMainWindow(event: IpcMainEvent | IpcMainInvokeEvent): void { + if (!isFromMainWindow(event)) throw new Error('Not allowed from this window') +} + export function showMainWindow(): void { const win = getMainWindow() if (!win) return diff --git a/apps/lyra/src/main/sessionStore.ts b/apps/lyra/src/main/sessionStore.ts index 5f710d96..f3a72e8d 100644 --- a/apps/lyra/src/main/sessionStore.ts +++ b/apps/lyra/src/main/sessionStore.ts @@ -14,6 +14,7 @@ import { type TrackInfo } from './sessionManifest' import { passesOnDisk, tracksOnDisk } from './sessionRecovery' +import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from './privateFiles' import type { Page, PageSummary } from '../shared/types' import { applyOp, @@ -265,7 +266,7 @@ const docFile = (doc: SessionDoc, raw: Record | undefined): str /** A new session's document. `wx`: one that appeared meanwhile (a sync client) is kept. */ function createDocFile(root: string, id: string, doc: SessionDoc): void { - writeFileSync(docPathIn(root, id), docFile(doc, undefined), { flag: 'wx' }) + writeFileSync(docPathIn(root, id), docFile(doc, undefined), { flag: 'wx', mode: PRIVATE_FILE_MODE }) } type DocRead = @@ -445,7 +446,7 @@ async function migrateLegacyMeeting(root: string, id: string, doc: SessionDoc, b if (hasDivider) editDoc(doc, { summary }) const raw = join(sessionDirIn(root, id), 'raw') - await mkdir(raw, { recursive: true }) + await mkdir(raw, { recursive: true, mode: PRIVATE_DIR_MODE }) const now = new Date().toISOString() const pass: RawPass = { id: 'legacy', @@ -471,7 +472,7 @@ async function migrateLegacyMeeting(root: string, id: string, doc: SessionDoc, b for (const name of ['mic', 'system'] as const) { const from = join(root, '.audio', `${stemOf(id)}.${name}.wav`) if (!existsSync(from)) continue - await mkdir(audioDir, { recursive: true }) + await mkdir(audioDir, { recursive: true, mode: PRIVATE_DIR_MODE }) const to = join(audioDir, `${name}.wav`) await copyFile(from, to) await unlink(from) @@ -494,7 +495,7 @@ async function migrateNote(id: string, root: string): Promise { const page = parsePage(raw, id, info.mtime.toISOString()) const doc = emptyDoc({ title: page.title === 'Untitled' ? '' : page.title, notes: '' }) const dir = sessionDirIn(root, id) - mkdirSync(dir, { recursive: true }) + mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE }) const legacy = await readLegacyMeta(root, id) const meeting = legacy ? await migrateLegacyMeeting(root, id, doc, page.body, legacy) : null editDoc(doc, { notes: meeting ? meeting.notes : page.body }) @@ -941,7 +942,7 @@ function sidecarOf(id: string, manifest: Manifest, snapshot: SessionSnapshot, bo /** Keeps a copy of an export that was changed outside Lyra, before it is overwritten. */ async function backUpExternalEdit(entry: Entry, current: string): Promise { const dir = join(sessionDirIn(entry.root, entry.id), 'external') - await mkdir(dir, { recursive: true }) + await mkdir(dir, { recursive: true, mode: PRIVATE_DIR_MODE }) const name = `${timestampStem(new Date())}${extname(entry.id)}` await writeFile(join(dir, name), current, 'utf8') log('sessions', 'kept a copy of an outside edit before re-exporting', { id: entry.id, name }) @@ -1116,7 +1117,7 @@ export async function createSession(options: CreateSessionOptions = {}): Promise try { markOwnWrite(id) // `wx` claims the name, so two sessions started in the same second can't collide. - await writeFile(resolveInNotes(id), text, { encoding: 'utf8', flag: 'wx' }) + await writeFile(resolveInNotes(id), text, { encoding: 'utf8', flag: 'wx', mode: PRIVATE_FILE_MODE }) } catch (error) { creating.delete(id) done() @@ -1127,7 +1128,7 @@ export async function createSession(options: CreateSessionOptions = {}): Promise const root = notesDir() const doc = emptyDoc({ title, notes: '' }) // Synchronous from here on, so the session is complete before anyone else runs. - mkdirSync(sessionDirIn(root, id), { recursive: true }) + mkdirSync(sessionDirIn(root, id), { recursive: true, mode: PRIVATE_DIR_MODE }) createDocFile(root, id, doc) const manifest: Manifest = { version: MANIFEST_VERSION, @@ -1178,7 +1179,7 @@ export async function deleteSession(id: string): Promise { // the system trash when Lyra quits (or on the next start, after a crash). const held = join(trashRoot(), id) await discard(held) - await mkdir(held, { recursive: true }) + await mkdir(held, { recursive: true, mode: PRIVATE_DIR_MODE }) const moves: TrashMove[] = [] const sidecar = sidecarName(id) const files: [string, string][] = [ @@ -1470,7 +1471,7 @@ export async function reexportDirtySessions(): Promise { export async function moveSessionFiles(fromDir: string, id: string): Promise { const fromSession = join(fromDir, '.sessions', id) if (existsSync(fromSession)) { - await mkdir(sessionsRoot(), { recursive: true }) + await mkdir(sessionsRoot(), { recursive: true, mode: PRIVATE_DIR_MODE }) await copyDir(fromSession, join(sessionsRoot(), id)) await rm(fromSession, { recursive: true, force: true }) } @@ -1484,7 +1485,7 @@ export async function moveSessionFiles(fromDir: string, id: string): Promise { - await mkdir(to, { recursive: true }) + await mkdir(to, { recursive: true, mode: PRIVATE_DIR_MODE }) for (const entry of await readdir(from, { withFileTypes: true })) { const source = join(from, entry.name) const target = join(to, entry.name) diff --git a/apps/lyra/src/main/voices.ts b/apps/lyra/src/main/voices.ts index c2fd1054..5d9e7d55 100644 --- a/apps/lyra/src/main/voices.ts +++ b/apps/lyra/src/main/voices.ts @@ -1,8 +1,9 @@ import { app, BrowserWindow } from 'electron' import { randomUUID } from 'node:crypto' -import { copyFile, readFile, rename, unlink, writeFile } from 'node:fs/promises' +import { copyFile, readFile } from 'node:fs/promises' import { join } from 'node:path' import type { Person } from '../shared/types' +import { writeFileAtomic } from './atomicFile' import { log } from './log' import { SPEAKER_EMBEDDING } from './meeting/speakerModel' import { @@ -77,17 +78,9 @@ function load(): Promise { return state } +/** Durable, so a power cut just after a voice is learned can't leave an empty file behind. */ async function write(next: VoicesState): Promise { - const path = storePath() - // Unique, so two writers (or a crashed earlier one) never share a half-written file. - const temp = `${path}.${randomUUID()}.tmp` - try { - await writeFile(temp, serializeVoices(next), 'utf8') - await rename(temp, path) - } catch (error) { - await unlink(temp).catch(() => undefined) - throw error - } + await writeFileAtomic(storePath(), serializeVoices(next)) } /** Mutations run one at a time, each on the state the previous one left. */ diff --git a/apps/lyra/src/renderer/src/components/Settings.tsx b/apps/lyra/src/renderer/src/components/Settings.tsx index 01233c87..ba3346e2 100644 --- a/apps/lyra/src/renderer/src/components/Settings.tsx +++ b/apps/lyra/src/renderer/src/components/Settings.tsx @@ -219,9 +219,12 @@ function StorageSection({ settings, update }: SectionProps) { */ type SummaryChoice = 'off' | 'local' | 'server' | 'cloud' +/** The local notes model's terms (THIRD_PARTY.md): non-commercial use only. */ +const QWEN_LICENSE_URL = 'https://huggingface.co/Qwen/Qwen2.5-3B-Instruct/blob/main/LICENSE' + const SUMMARY_CHOICES = [ { value: 'off', label: 'Off' }, - { value: 'local', label: 'On this computer', hint: 'A built-in model; nothing leaves this computer' }, + { value: 'local', label: 'On this computer', hint: 'A built-in model for non-commercial use; nothing leaves this computer' }, { value: 'server', label: 'Local server', hint: 'Ollama, LM Studio, llama.cpp…' }, { value: 'cloud', label: 'Cloud model', hint: 'Anthropic, OpenAI or Google, with your key' } ] as const @@ -699,7 +702,17 @@ function SummarySection({ settings, update }: SectionProps) { {choice === 'local' ? (

Runs a small model on this computer, so nothing leaves it. The first time downloads about - 2 GB; long sessions can take a few minutes. + 2 GB; long sessions can take a few minutes. The model, Qwen2.5 3B, is licensed for + non-commercial use only: for work, use a local server or a cloud model.{' '} + {/* A new window is handed to the OS browser (lockDownContents in main). */} + + Read the licence +

) : null} {choice === 'server' ? ( diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 566348ea..49ae8263 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -1,7 +1,7 @@ # Threat model One page, kept current with the code. Every threat has a control (and where it is checked), an -accepted risk, or an open item. Last reviewed 2026-11-25. +accepted risk, or an open item. Last reviewed 2026-11-28. ## What Lyra holds @@ -9,7 +9,9 @@ accepted risk, or an open item. Last reviewed 2026-11-25. | --- | --- | --- | | Notes and transcripts | The notes folder (`~/.lyra` by default) | Private speech, often about other people | | Session audio | `.sessions//` under the notes folder, deleted after the retention setting | Recordings of other people's voices | -| Voiceprints | `` (`voices.ts`) | Biometric data: identifies a person across recordings | +| Voiceprints | `/voices.json` (`voices.ts`), mirrored into the search index | Biometric data: identifies a person across recordings | +| The search index | `/index/lyra.db` (libSQL): session text, speakers and voiceprints, derived from the files above | Holds the same private data; deleted rows are zeroed (`secure_delete`) | +| Copies set aside | `*.corrupt-