From ade8928cf4c8713cc56b902d9304e14e48ee861a Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Wed, 25 Nov 2026 18:23:12 +0530 Subject: [PATCH 01/13] fix(macos): stop the "Electron" Local Network prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a network whose DNS server is a local address, macOS 15+ asked 'Allow "Electron" to find devices on local networks?' after the 1.5.0 update. Two causes: - Electron enables Chromium's built-in resolver on macOS, which sends DNS queries straight to that server. Chromium now resolves through the OS (app.configureHostResolver({ enableBuiltInResolver: false }), first thing after ready), which needs no Local Network permission and is already the default on Windows and Linux. - electron-builder brands the helper apps' file, executable, display name and id but leaves CFBundleName as "Electron Helper…", and the network service runs in a helper. afterPack now sets each helper's CFBundleName to its bundle name before signing, and fails the build if none is found or one still says Electron. The app's own DNSBL lookups still query the network's DNS server, so the macOS Info.plist now carries an NSLocalNetworkUsageDescription saying why. --- .gitignore | 1 + CHANGELOG.md | 10 ++ apps/desktop/build/afterPack.js | 7 + apps/desktop/build/mac-helper-names.js | 57 +++++++ apps/desktop/electron/main.ts | 6 + .../electron/services/host-resolver.ts | 42 +++++ apps/desktop/package.json | 3 + .../test/unit/electron/host-resolver.test.ts | 76 +++++++++ .../test/unit/mac-helper-names.test.ts | 155 ++++++++++++++++++ 9 files changed, 357 insertions(+) create mode 100644 apps/desktop/build/mac-helper-names.js create mode 100644 apps/desktop/electron/services/host-resolver.ts create mode 100644 apps/desktop/test/unit/electron/host-resolver.test.ts create mode 100644 apps/desktop/test/unit/mac-helper-names.test.ts diff --git a/.gitignore b/.gitignore index bf3d0ce7..14d48caf 100644 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,7 @@ apps/desktop/build/* # reconstructed; see its header. !apps/desktop/build/afterPack.js !apps/desktop/build/keychain-helper.js +!apps/desktop/build/mac-helper-names.js !apps/desktop/build/beforeBuild.js !apps/desktop/build/entitlements.mac.plist !apps/desktop/build/default-apps.nsh diff --git a/CHANGELOG.md b/CHANGELOG.md index 96774ff2..526b29ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **macOS no longer asks to let "Electron" find devices on your local + network.** On a network whose DNS server is a local device, such as an office + router, the app looked up names by asking that server directly, so macOS + asked for Local Network access, and named the request after a part of the app + that was still called "Electron". Names are now looked up through macOS + itself, which needs no such permission, and every part of the app carries the + Sarv Inbox name. If macOS does ask, for the app's own checks of senders + against spam blocklists, the request now says Sarv Inbox and why. + ## [1.5.0] - 2026-11-25 ### Added diff --git a/apps/desktop/build/afterPack.js b/apps/desktop/build/afterPack.js index 5dad1396..e2b223ba 100644 --- a/apps/desktop/build/afterPack.js +++ b/apps/desktop/build/afterPack.js @@ -17,6 +17,7 @@ const { rm, readdir, stat } = require('node:fs/promises') const { join } = require('node:path') const { buildKeychainHelper } = require('./keychain-helper.js') +const { brandMacHelperNames } = require('./mac-helper-names.js') // Directory names that node-gyp leaves behind and nothing loads at runtime. const DEAD_BUILD_DIRS = new Set(['obj.target', 'obj', '.deps']) @@ -63,6 +64,12 @@ exports.default = async (context) => { directory: join(appOutDir, `${appName}.app`, 'Contents', 'MacOS'), arch: context.arch, }) + // Helpers keep Electron's CFBundleName unless renamed here, and macOS shows + // it in prompts ("Allow "Electron" to find devices…"). Before signing. + await brandMacHelperNames({ + frameworksDir: join(appOutDir, `${appName}.app`, 'Contents', 'Frameworks'), + productFilename: appName, + }) } // Where the asarUnpack'd native modules land, per platform. diff --git a/apps/desktop/build/mac-helper-names.js b/apps/desktop/build/mac-helper-names.js new file mode 100644 index 00000000..cf912e34 --- /dev/null +++ b/apps/desktop/build/mac-helper-names.js @@ -0,0 +1,57 @@ +// Brands the macOS helper apps' CFBundleName. +// +// electron-builder renames each helper's file, executable, display name and +// bundle id ("Sarv Inbox Helper (GPU).app", com.sarv.sarvinbox.helper.GPU) but +// leaves CFBundleName as Electron shipped it: "Electron Helper", "Electron +// Helper (GPU)" and so on. macOS names a process by that key in some of its own +// prompts. The network service runs in "Sarv Inbox Helper", so 1.5.0 asked +// users to "Allow "Electron" to find devices on local networks?". +// +// Each helper's CFBundleName is set to its bundle's own name. Runs from +// afterPack, which comes before signing, so the signature covers the new +// value. Uses electron-builder's own plist reader and writer, the same one +// that wrote these files a moment earlier. Idempotent: the universal build +// runs it on each slice and again on the merged app, and the slices must stay +// identical for the merge. + +const { readdir } = require('node:fs/promises') +const { join } = require('node:path') + +const HELPER_SUFFIX = '.app' + +/** + * Set CFBundleName on every " Helper….app" in `frameworksDir`. + * Throws when none is found (a release must never ship with the step silently + * skipped) and when a helper still says "Electron" afterwards. + * + * @param {{ frameworksDir: string, productFilename: string, + * plist?: { parsePlistFile(file: string): Promise>, + * savePlistFile(file: string, data: unknown): Promise } }} options + * @returns {Promise} the names now set, sorted + */ +async function brandMacHelperNames({ frameworksDir, productFilename, plist = require('app-builder-lib/out/util/plist.js') }) { + const prefix = `${productFilename} Helper` + const entries = await readdir(frameworksDir, { withFileTypes: true }) + const helpers = entries + .filter((entry) => entry.isDirectory() && entry.name.startsWith(prefix) && entry.name.endsWith(HELPER_SUFFIX)) + .map((entry) => entry.name.slice(0, -HELPER_SUFFIX.length)) + .sort() + if (helpers.length === 0) { + throw new Error(`mac-helper-names: no "${prefix}*.app" in ${frameworksDir}`) + } + const names = [] + for (const name of helpers) { + const file = join(frameworksDir, `${name}${HELPER_SUFFIX}`, 'Contents', 'Info.plist') + const info = await plist.parsePlistFile(file) + if (info.CFBundleName !== name) { + await plist.savePlistFile(file, { ...info, CFBundleName: name }) + } + names.push(name) + } + for (const name of names) { + if (/electron/i.test(name)) throw new Error(`mac-helper-names: helper still named "${name}"`) + } + return names +} + +module.exports = { brandMacHelperNames } diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index cdb37c45..c6aac918 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -92,6 +92,7 @@ import { getExternalOpenService } from './services/external-open-service'; import { wireFolderCountBroadcast } from './services/folder-count-broadcast'; import { startFollowUpChecker, stopFollowUpChecker } from './services/follow-up-checker'; import { startHeaderBackfill, stopHeaderBackfill } from './services/header-backfill'; +import { useSystemHostResolver } from './services/host-resolver'; import { startLocalCalendarReminders, stopLocalCalendarReminders } from './services/local-calendar-reminders'; import { initializeLocalDataReset, isLocalDataResetRestarting } from './services/local-data-reset'; import { offerMoveToApplications } from './services/mac-install-location'; @@ -1042,6 +1043,11 @@ app.whenReady().then(async () => { // down, so this guard is what actually prevents the duplicate footprint. if (!gotSingleInstanceLock) return; try { + // First, before anything can make a request: Chromium resolves names + // through the OS, not by sending DNS packets to a server that may be on the + // local network (macOS would ask for Local Network access). See host-resolver.ts. + useSystemHostResolver(app, logger); + // PROD: now that we own the lock, publish our liveness heartbeat so the NEXT // launch can tell us apart from a wedged primary (see evaluateLockContention). // Stopped + removed on teardown. Dev has no lock, so no heartbeat. diff --git a/apps/desktop/electron/services/host-resolver.ts b/apps/desktop/electron/services/host-resolver.ts new file mode 100644 index 00000000..08727b64 --- /dev/null +++ b/apps/desktop/electron/services/host-resolver.ts @@ -0,0 +1,42 @@ +/** + * How Chromium (the window, `net.fetch`, the updater) turns a host name into an + * address: through the operating system's resolver, never by sending DNS + * packets itself. + * + * On macOS Electron enables Chromium's built-in resolver by default. It reads + * the system's DNS servers and queries them directly over UDP. On a network + * whose DNS server is a local address (an office router such as 10.x or + * 192.168.x), that is "local network" traffic, so macOS 15 and later stop the + * app with "Allow … to find devices on local networks?" — attributed to the + * network-service helper process, which is why it named "Electron" (see + * build/mac-helper-names.js). Declining it can break name lookups. + * + * Going through the system resolver (getaddrinfo, answered by mDNSResponder) + * needs no such permission and honours the same DNS settings, VPN and + * per-domain resolvers. Windows and Linux already default to it, so this + * changes nothing there; it is set on every platform so the behaviour is one + * fact, not three. + */ +import { errorDiagnostic } from '@sarvinbox/core'; + +type HostResolverApp = { configureHostResolver(options: { enableBuiltInResolver?: boolean }): void }; +type WarnLogger = { warn(message: string, ...details: unknown[]): void }; + +/** The options passed to `app.configureHostResolver`. */ +export const SYSTEM_HOST_RESOLVER = Object.freeze({ enableBuiltInResolver: false }); + +/** + * Switch Chromium to the system resolver. Must run after `ready` (Electron + * refuses it earlier) and before the first request. Never throws: if Electron + * refuses, the app still works, with the built-in resolver, and the log says so. + * Returns whether the setting took. + */ +export function useSystemHostResolver(app: HostResolverApp, log: WarnLogger): boolean { + try { + app.configureHostResolver({ ...SYSTEM_HOST_RESOLVER }); + return true; + } catch (error) { + log.warn('[Main] could not switch Chromium to the system DNS resolver', errorDiagnostic(error)); + return false; + } +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 92c4e2af..84b4130a 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -182,6 +182,9 @@ "entitlements": "build/entitlements.mac.plist", "entitlementsInherit": "build/entitlements.mac.plist", "notarize": false, + "extendInfo": { + "NSLocalNetworkUsageDescription": "Sarv Inbox checks the senders of your email, for example against spam blocklists, by asking your network's DNS server. On some networks that server is a device on your local network." + }, "protocols": [ { "name": "Sarv Inbox email", diff --git a/apps/desktop/test/unit/electron/host-resolver.test.ts b/apps/desktop/test/unit/electron/host-resolver.test.ts new file mode 100644 index 00000000..a9385534 --- /dev/null +++ b/apps/desktop/test/unit/electron/host-resolver.test.ts @@ -0,0 +1,76 @@ +import { readFileSync } from 'node:fs'; + +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { describe, expect, it, vi } from 'vitest'; + +import { captureLogs } from '../../../../../packages/core/src/test-support/log-capture'; +import { SYSTEM_HOST_RESOLVER, useSystemHostResolver } from '../../../electron/services/host-resolver'; + +// Chromium must resolve names through the OS. Its built-in resolver (on by +// default on macOS) queries the DNS server itself, and when that server is on +// the local network macOS asks "Allow "Electron" to find devices on local +// networks?" — the prompt 1.5.0 users saw on an office network. + +describe('useSystemHostResolver', () => { + // Breaks: the built-in resolver stays on, and macOS asks for Local Network + // access on any network whose DNS server is a local address. + it('turns off Chromium\'s built-in resolver and nothing else', () => { + const configureHostResolver = vi.fn(); + expect(useSystemHostResolver({ configureHostResolver }, { warn: vi.fn() })).toBe(true); + expect(configureHostResolver).toHaveBeenCalledTimes(1); + expect(configureHostResolver).toHaveBeenCalledWith({ enableBuiltInResolver: false }); + // DNS-over-HTTPS and the other options keep Electron's defaults. + expect(Object.keys(SYSTEM_HOST_RESOLVER)).toEqual(['enableBuiltInResolver']); + }); + + // Breaks: a caller mutates the shared options object and every later call + // passes the changed value. + it('passes a copy, never the shared constant', () => { + const configureHostResolver = vi.fn(); + useSystemHostResolver({ configureHostResolver }, { warn: vi.fn() }); + expect(configureHostResolver.mock.calls[0]![0]).not.toBe(SYSTEM_HOST_RESOLVER); + expect(Object.isFrozen(SYSTEM_HOST_RESOLVER)).toBe(true); + }); + + // Breaks: Electron refusing the call (called before ready, an API change) + // throws out of startup and the app never opens; or the log line quotes the + // error's message. + it('keeps starting when Electron refuses, logging only what failed', () => { + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const SENTINEL = 'SENTINEL-resolver-7c1d'; + const warn = vi.fn(); + const configureHostResolver = vi.fn(() => { throw Object.assign(new TypeError(`refused ${SENTINEL}`), { code: 'ERR_X' }); }); + expect(() => useSystemHostResolver({ configureHostResolver }, { warn })).not.toThrow(); + expect(useSystemHostResolver({ configureHostResolver }, { warn })).toBe(false); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('system DNS resolver'), expect.objectContaining({ name: 'TypeError', code: 'ERR_X' })); + expect(JSON.stringify(warn.mock.calls)).not.toContain(SENTINEL); + expect(logs.lines.join('\n')).not.toContain(SENTINEL); + } finally { + logs.stop(); + } + }); +}); + +describe('main.ts host resolver wiring', () => { + const source = readFileSync(new URL('../../../electron/main.ts', import.meta.url), 'utf8'); + const code = source + .replace(/\/\*[\s\S]*?\*\//g, '') + .split('\n') + .map((line) => line.replace(/(^|[^:])\/\/.*$/, '$1')) + .join('\n'); + + // Breaks: the switch runs before `ready` (Electron throws), after the first + // request (that request already used the built-in resolver), or not at all. + it('switches once, inside whenReady, before storage, windows or the updater start', () => { + const ready = code.indexOf('app.whenReady().then('); + const call = code.indexOf('useSystemHostResolver(app, logger);'); + expect(ready).toBeGreaterThan(-1); + expect(call).toBeGreaterThan(ready); + expect(code.match(/useSystemHostResolver\(/g)).toHaveLength(1); + for (const later of ['reclaimSingleDevInstance(', 'ensureNativeSqliteLoadable()', 'createWindow(']) { + const at = code.indexOf(later, ready); + if (at > -1) expect(call, later).toBeLessThan(at); + } + }); +}); diff --git a/apps/desktop/test/unit/mac-helper-names.test.ts b/apps/desktop/test/unit/mac-helper-names.test.ts new file mode 100644 index 00000000..5ad1e057 --- /dev/null +++ b/apps/desktop/test/unit/mac-helper-names.test.ts @@ -0,0 +1,155 @@ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +// The macOS helper apps keep Electron's CFBundleName ("Electron Helper") unless +// the build renames them, and macOS shows that name in its own prompts: 1.5.0 +// asked users to 'Allow "Electron" to find devices on local networks?'. + +const require = createRequire(import.meta.url); +const { brandMacHelperNames } = require('../../build/mac-helper-names.js') as { + brandMacHelperNames: (options: { frameworksDir: string; productFilename: string; plist?: unknown }) => Promise; +}; +// electron-builder's own plist reader and writer, the one the build step uses. +const plist = require('app-builder-lib/out/util/plist.js') as { + parsePlistFile: (file: string) => Promise>; + savePlistFile: (file: string, data: unknown) => Promise; +}; + +const roots: string[] = []; +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); + +/** A Frameworks folder laid out the way electron-builder leaves it before signing. */ +async function frameworks(): Promise { + const root = await mkdtemp(join(tmpdir(), 'inbox-helper-names-')); + roots.push(root); + const dir = join(root, 'Sarv Inbox.app', 'Contents', 'Frameworks'); + const helpers: Array<[string, string]> = [ + ['Sarv Inbox Helper', 'Electron Helper'], + ['Sarv Inbox Helper (GPU)', 'Electron Helper (GPU)'], + ['Sarv Inbox Helper (Plugin)', 'Electron Helper (Plugin)'], + ['Sarv Inbox Helper (Renderer)', 'Electron Helper (Renderer)'], + ]; + for (const [bundle, electronName] of helpers) { + await mkdir(join(dir, `${bundle}.app`, 'Contents'), { recursive: true }); + await plist.savePlistFile(join(dir, `${bundle}.app`, 'Contents', 'Info.plist'), { + CFBundleName: electronName, + CFBundleDisplayName: bundle, + CFBundleExecutable: bundle, + CFBundleIdentifier: 'com.sarv.sarvinbox.helper', + LSEnvironment: { MallocNanoZone: '0' }, + }); + } + // Not helpers: frameworks the builder must leave alone. + await mkdir(join(dir, 'Electron Framework.framework', 'Resources'), { recursive: true }); + await writeFile(join(dir, 'Electron Framework.framework', 'Resources', 'Info.plist'), 'untouched'); + await mkdir(join(dir, 'Squirrel.framework'), { recursive: true }); + return dir; +} +const infoOf = (dir: string, bundle: string) => plist.parsePlistFile(join(dir, `${bundle}.app`, 'Contents', 'Info.plist')); + +describe('brandMacHelperNames', () => { + // Breaks: a helper keeps "Electron Helper…" as its name, and a macOS prompt + // about it says "Electron" instead of Sarv Inbox. + it('names every helper after its own bundle', async () => { + const dir = await frameworks(); + expect(await brandMacHelperNames({ frameworksDir: dir, productFilename: 'Sarv Inbox' })).toEqual([ + 'Sarv Inbox Helper', 'Sarv Inbox Helper (GPU)', 'Sarv Inbox Helper (Plugin)', 'Sarv Inbox Helper (Renderer)', + ]); + for (const bundle of ['Sarv Inbox Helper', 'Sarv Inbox Helper (GPU)', 'Sarv Inbox Helper (Renderer)']) { + expect((await infoOf(dir, bundle)).CFBundleName).toBe(bundle); + } + }); + + // Breaks: rewriting the name drops another key (the executable or bundle id + // a helper is launched and signed by, or its environment), or touches the + // Electron framework's own plist. + it('changes only CFBundleName', async () => { + const dir = await frameworks(); + await brandMacHelperNames({ frameworksDir: dir, productFilename: 'Sarv Inbox' }); + expect(await infoOf(dir, 'Sarv Inbox Helper (GPU)')).toEqual({ + CFBundleName: 'Sarv Inbox Helper (GPU)', + CFBundleDisplayName: 'Sarv Inbox Helper (GPU)', + CFBundleExecutable: 'Sarv Inbox Helper (GPU)', + CFBundleIdentifier: 'com.sarv.sarvinbox.helper', + LSEnvironment: { MallocNanoZone: '0' }, + }); + expect(await readFile(join(dir, 'Electron Framework.framework', 'Resources', 'Info.plist'), 'utf8')).toBe('untouched'); + }); + + // Breaks: the universal build, which runs afterPack on each slice and again + // on the merged app, ends with different plists per slice (the merge fails) + // or rewrites an already-correct file. + it('is idempotent and byte-stable', async () => { + const dir = await frameworks(); + await brandMacHelperNames({ frameworksDir: dir, productFilename: 'Sarv Inbox' }); + const file = join(dir, 'Sarv Inbox Helper.app', 'Contents', 'Info.plist'); + const first = await readFile(file, 'utf8'); + const writes: string[] = []; + await brandMacHelperNames({ + frameworksDir: dir, + productFilename: 'Sarv Inbox', + plist: { parsePlistFile: plist.parsePlistFile, savePlistFile: async (path: string) => { writes.push(path); } }, + }); + expect(writes).toEqual([]); + expect(await readFile(file, 'utf8')).toBe(first); + }); + + // Breaks: the product is renamed or the builder's layout changes, the step + // finds nothing, and a release ships with "Electron" prompts again unnoticed. + it('fails the build when it finds no helper', async () => { + const dir = await frameworks(); + await expect(brandMacHelperNames({ frameworksDir: dir, productFilename: 'Other Name' })).rejects.toThrow(/no "Other Name Helper\*\.app"/); + }); + + // Breaks: a product or bundle named with "Electron" passes the check that + // exists to keep that word out of the prompts. + it('fails the build when a helper would still say Electron', async () => { + const dir = await frameworks(); + await mkdir(join(dir, 'Sarv Inbox Helper (Electron).app', 'Contents'), { recursive: true }); + await plist.savePlistFile(join(dir, 'Sarv Inbox Helper (Electron).app', 'Contents', 'Info.plist'), { CFBundleName: 'x' }); + await expect(brandMacHelperNames({ frameworksDir: dir, productFilename: 'Sarv Inbox' })).rejects.toThrow(/still named/); + }); +}); + +describe('afterPack wiring', () => { + // Breaks: the step is written but never runs, or runs after signing (the + // signature no longer matches the plist and Gatekeeper rejects the app), or + // is lost to the .gitignore rule that hides apps/desktop/build/*. + it('renames the helpers on macOS in afterPack, which runs before signing, and is tracked', async () => { + const hook = await readFile(new URL('../../build/afterPack.js', import.meta.url), 'utf8'); + const darwin = hook.indexOf("if (electronPlatformName === 'darwin') {"); + const call = hook.indexOf('await brandMacHelperNames({'); + expect(darwin).toBeGreaterThan(-1); + expect(call).toBeGreaterThan(darwin); + expect(call).toBeLessThan(hook.indexOf('if (dead.length === 0) return')); + expect(hook).toContain("frameworksDir: join(appOutDir, `${appName}.app`, 'Contents', 'Frameworks')"); + const macPackager = await readFile(require.resolve('app-builder-lib/out/macPackager.js'), 'utf8'); + expect(macPackager.indexOf('await this.info.emitAfterPack(')).toBeLessThan(macPackager.lastIndexOf('await this.doSignAfterPack(')); + const gitignore = await readFile(new URL('../../../../.gitignore', import.meta.url), 'utf8'); + expect(gitignore).toContain('!apps/desktop/build/mac-helper-names.js'); + }); + + // Breaks: electron-builder starts setting CFBundleName itself (this step + // becomes dead weight) or stops renaming the helper bundles this step keys on. + it('matches what electron-builder does to the helpers', async () => { + const electronMac = await readFile(require.resolve('app-builder-lib/out/electron/electronMac.js'), 'utf8'); + expect(electronMac).toContain('helperPlist.CFBundleDisplayName = `${appInfo.productName} Helper`;'); + expect(electronMac).not.toMatch(/helper\w*\.CFBundleName\s*=/i); + }); +}); + +describe('Local Network usage description', () => { + // Breaks: a Local Network prompt the app itself raises (its own DNS lookups + // for spam blocklists go straight to the network's DNS server) gives the + // user no reason, or the key ends up outside the macOS Info.plist. + it('explains in the macOS Info.plist why the app may reach the local network', () => { + const desktop = require('../../package.json') as { build: { mac: { extendInfo?: Record } } }; + const reason = desktop.build.mac.extendInfo?.NSLocalNetworkUsageDescription ?? ''; + expect(reason).toMatch(/^Sarv Inbox /); + expect(reason).toMatch(/DNS server/); + }); +}); From e29edb1961e1a9e5e6ccea67620ff200d85992fd Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Sat, 28 Nov 2026 18:11:21 +0530 Subject: [PATCH 02/13] feat(filters): "Filter messages like this" and a "Skip AI checks" option "Filter messages like this" on an email's menu said the feature was coming. It now opens Settings > Filters with a new filter for that sender (From contains the address), ready to save. Filters gain a "Skip AI checks" option (a new skipAI action, kept in the actions JSON, so no migration). It is ticked for every new filter and can be unticked; existing filters are unchanged. A filter may do only this. Mail it matches is kept from every background AI path: the per-email pipeline (marked done, so it is not retried), the bulk categorizer, and category propagation to linked accounts. When the rule table cannot be read, the email is neither sent nor marked done, so it is retried. Inbox Agent can create such a filter. Test fakes for the categorizer gain an empty getEnabledFilterRules, the store method the new gate reads. --- CHANGELOG.md | 12 ++ CLAUDE.md | 9 + .../services/ai-categorization-service.ts | 6 + .../electron/services/filter-ai-skip.ts | 28 ++++ .../inbox-assistant-agent-setting-tools.ts | 6 +- .../inbox-assistant-setting-changes.ts | 1 + .../services/unified-pipeline-service.ts | 23 ++- .../src/components/AdvancedSearchPanel.tsx | 5 +- .../email-detail/hooks/useEmailDetail.ts | 7 +- .../src/components/settings/FiltersTab.tsx | 45 ++++- apps/desktop/src/utils/filter-draft-bridge.ts | 42 ++++- .../ai-categorization-authority.test.ts | 38 ++++- .../services/ai-categorization-log.test.ts | 2 + .../ai-categorization-prompts.test.ts | 2 + .../ai-categorization-transport.test.ts | 2 + .../electron/services/filter-ai-skip.test.ts | 43 +++++ .../inbox-assistant-agent-changes.test.ts | 14 ++ .../unified-pipeline-ai-assist.test.ts | 114 +++++++++++++ .../settings/FiltersTab.skip-ai.test.tsx | 157 ++++++++++++++++++ .../src/utils/filter-draft-bridge.test.ts | 42 ++++- packages/core/src/types/filters.ts | 9 +- packages/core/src/utils/filters.ts | 12 ++ packages/core/test/unit/utils/filters.test.ts | 39 ++++- 23 files changed, 632 insertions(+), 26 deletions(-) create mode 100644 apps/desktop/electron/services/filter-ai-skip.ts create mode 100644 apps/desktop/test/unit/electron/services/filter-ai-skip.test.ts create mode 100644 apps/desktop/test/unit/src/components/settings/FiltersTab.skip-ai.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 96774ff2..21191fc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **"Filter messages like this" works.** On an email's menu it used to say the + feature was coming; it now opens Settings → Filters with a new filter for + that sender, ready to save. +- **Filters can keep the AI away from the mail they match.** A new **Skip AI + checks** option on each filter stops the AI from sorting matching emails + into categories, scoring their priority, judging them as spam, acting on them + or drafting replies to them. It is ticked for every new filter, including + one made with "Filter messages like this", and can be unticked. Filters you + already have are unchanged until you tick it. A filter can do only this, and + Inbox Agent can set it up when you ask. + ## [1.5.0] - 2026-11-25 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 9c9ac800..bd5984e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -383,6 +383,15 @@ Established shared helpers (extend this list as you add more): the email's own flags and content, then its sender (VIP) and conversation (the user's recent reply, a colleague). A failed lookup protects. Use both for any new path that changes mail on the agent's behalf. +- `filterAiVerdict(storage, email)` — `apps/desktop/electron/services/filter-ai-skip.ts` + (built on core `filterSkipsAI(email, rules)`). Whether a user filter's "Skip AI + checks" keeps the background AI away from an email: `skip`, `run`, or `unknown` + when the rules could not be read (neither send nor mark handled). Every path + that sends an email to the AI or copies an AI verdict onto one asks it first. +- `openFilterEditor(draft)` / `filterDraftFromSender(address)` — + `apps/desktop/src/utils/filter-draft-bridge.ts`. Open Settings → Filters with a + pre-filled filter, and the draft for one sender. Use them for any new + "create a filter from here" entry point. - `isAllowedArchiveEntry(path, entry)` — `apps/desktop/electron/services/extension-archive-rules.mjs`. What may come out of an extension archive (allowlisted paths, plain files and the expected folders, diff --git a/apps/desktop/electron/services/ai-categorization-service.ts b/apps/desktop/electron/services/ai-categorization-service.ts index 1a633e79..39fc46a4 100644 --- a/apps/desktop/electron/services/ai-categorization-service.ts +++ b/apps/desktop/electron/services/ai-categorization-service.ts @@ -13,6 +13,7 @@ import type { EmailRecord , AIErrorInfo, EmailSecurityContext, SenderSignals } f import { getMainWindow, requireStorage } from '../shared'; import { ensureBundledAgentPrompts } from './agent-prompt-defaults'; +import { filterAiVerdict } from './filter-ai-skip'; import { chromiumFetch } from './net-fetch'; import { readCategorizationSenderHistory } from './sender-history-context'; const logger = createLogger('ai-categorization-service'); @@ -774,6 +775,11 @@ export class AICategorizationService { } if (existingCategoryClassification(email) || automaticCategorizationDeferred(email) || isSpamProtectedEmail(email, await storage.getFolder?.(email.folderId), await storage.getFolders?.())) continue; + // A filter with "Skip AI checks": never sent, and marked handled so the + // run does not pick it again. Unreadable rules: left pending, not sent. + const filterVerdict = await filterAiVerdict(storage, email); + if (filterVerdict === 'skip') storage.getRepositories?.()?.agent?.markAgentGaveUp?.(email.id, {}); + if (filterVerdict !== 'run') continue; // Body for the LLM prompt — see categorizationBodyOf. const body = categorizationBodyOf(email); const fromAddr = (email.fromAddress || '').toLowerCase(); diff --git a/apps/desktop/electron/services/filter-ai-skip.ts b/apps/desktop/electron/services/filter-ai-skip.ts new file mode 100644 index 00000000..90572da2 --- /dev/null +++ b/apps/desktop/electron/services/filter-ai-skip.ts @@ -0,0 +1,28 @@ +/** + * Whether a user filter keeps the background AI away from an email (the + * filter's "Skip AI checks" option). The one check both AI paths run — the + * per-email pipeline (categorizing, priority, the AI's spam verdict, automatic + * actions and drafted replies) and the bulk categorizer — read from the + * email's own account, so a filter on one account never affects another. + * + * Three answers, because an unreadable store and an empty one are opposite + * facts: `unknown` (the rules could not be read) must neither send the email + * to the AI nor mark it handled. The caller leaves it pending and the next + * pass asks again. + */ +import { errorDiagnostic, filterSkipsAI, logger, type EmailRecord, type FilterRule } from '@sarvinbox/core'; + +export type FilterAiVerdict = 'skip' | 'run' | 'unknown'; + +interface FilterRuleSource { getEnabledFilterRules(): Promise } + +export async function filterAiVerdict(storage: FilterRuleSource, email: EmailRecord): Promise { + let rules: FilterRule[]; + try { + rules = await storage.getEnabledFilterRules(); + } catch (error) { + logger.warn('[Filters] could not read filter rules before AI processing; will retry', errorDiagnostic(error)); + return 'unknown'; + } + return filterSkipsAI(email, rules) ? 'skip' : 'run'; +} diff --git a/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts b/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts index f5b053f5..79b8684f 100644 --- a/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts +++ b/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts @@ -24,7 +24,7 @@ import { const FIELDS: readonly FilterCondition['field'][] = ['from', 'to', 'cc', 'subject', 'body', 'domain']; const OPERATORS: readonly FilterCondition['operator'][] = ['contains', 'notContains', 'equals', 'startsWith', 'endsWith']; -const ACTION_TYPES: readonly FilterAction['type'][] = ['markRead', 'star', 'archive', 'delete', 'moveToSpam', 'moveToFolder', 'applyLabel']; +const ACTION_TYPES: readonly FilterAction['type'][] = ['markRead', 'star', 'archive', 'delete', 'moveToSpam', 'moveToFolder', 'applyLabel', 'skipAI']; /** At most one of these per filter: a message can only end up in one place. */ const PLACING = new Set(['archive', 'delete', 'moveToSpam', 'moveToFolder']); /** Existing mail a filter or block never touches: the user's own mail, and mail already gone. */ @@ -38,7 +38,7 @@ const CONDITION_SCHEMA = { type: 'object', additionalProperties: false, required field: { type: 'string', enum: [...FIELDS] }, operator: { type: 'string', enum: [...OPERATORS] }, value: { type: 'string' }, } }; const ACTION_SCHEMA = { type: 'object', additionalProperties: false, required: ['type'], properties: { - type: { type: 'string', enum: [...ACTION_TYPES], description: 'delete moves to Trash.' }, + type: { type: 'string', enum: [...ACTION_TYPES], description: 'delete moves to Trash. skipAI keeps the background AI (categorizing, priority, automatic actions, drafted replies) away from matching mail.' }, value: { type: 'string', description: 'moveToFolder: a folder from list_folders. applyLabel: the label name (created if missing).' }, } }; const RULE_PROPERTIES = { @@ -127,6 +127,8 @@ function mailActionFor(action: FilterAction, folders: FolderRecord[], checked: C case 'delete': return { action: 'trash' }; case 'applyLabel': return { action: 'add_label', labelName: action.value! }; case 'moveToFolder': return { action: 'move', folder: checked.folders.get(action.value!)! }; + // Nothing to change on existing mail: the AI checks the filter when it would run. + case 'skipAI': return undefined; case 'moveToSpam': { const spam = roleFolders(folders, 'spam')[0]; return spam ? { action: 'move', folder: spam } : undefined; diff --git a/apps/desktop/electron/services/inbox-assistant-setting-changes.ts b/apps/desktop/electron/services/inbox-assistant-setting-changes.ts index 018c5c48..b092e513 100644 --- a/apps/desktop/electron/services/inbox-assistant-setting-changes.ts +++ b/apps/desktop/electron/services/inbox-assistant-setting-changes.ts @@ -107,6 +107,7 @@ export function describeAction(action: FilterAction): string { case 'moveToSpam': return 'Move to Spam'; case 'moveToFolder': return `Move to ${action.value}`; case 'applyLabel': return `Label "${action.value}"`; + case 'skipAI': return 'Skip AI checks'; } } diff --git a/apps/desktop/electron/services/unified-pipeline-service.ts b/apps/desktop/electron/services/unified-pipeline-service.ts index dbfb0799..113a60f4 100644 --- a/apps/desktop/electron/services/unified-pipeline-service.ts +++ b/apps/desktop/electron/services/unified-pipeline-service.ts @@ -69,6 +69,7 @@ import { isAIEndpointRefusedError, prepareAIProviderConfig, reportAIConfigRefuse import { runClassificationMutation } from './classification-actions'; import { refreshContactClassifications, startContactClassificationRefresh, stopContactClassificationRefresh } from './contact-classification-service'; import { getMeta, setMeta } from './core-db'; +import { filterAiVerdict } from './filter-ai-skip'; import { ensureGmailLabelColor, renameGmailLabel, deleteGmailLabelsUnder } from './gmail-label-api'; import { chromiumFetch } from './net-fetch'; import { notifyNewMail } from './notification-service'; @@ -336,7 +337,7 @@ async function isStoredSpam(storage: any, email: any): Promise { return isSpamProtectedEmail(email, folder, await storage.getFolders?.()); } -function propagateCategoriesToLinkedAccounts(messageId: string | undefined, categories: string[], sourceStorage: any, priority?: PropagatePriority): void { +async function propagateCategoriesToLinkedAccounts(messageId: string | undefined, categories: string[], sourceStorage: any, priority?: PropagatePriority): Promise { if (!messageId || categories.length === 0) return; const now = Math.floor(Date.now() / 1000); const cats = categories.map((slug) => ({ slug, confidence: 0.9 })); @@ -357,6 +358,11 @@ function propagateCategoriesToLinkedAccounts(messageId: string | undefined, cate // let a propagation clobber categories that copy already had. const ownCategorySlugs = extractCategorySlugs(row.tags || '', getCategorySlugSet(rt.storage)); if (ownCategorySlugs.length > 0) continue; + // A filter in THIS copy's account with "Skip AI checks" keeps the AI's + // verdict off it too, even one reached in another account. Unreadable + // rules: leave the copy to its own pipeline, which asks again. + const linkedEmail = await (rt.storage as any).getEmail?.(row.id); + if (!linkedEmail || await filterAiVerdict(rt.storage as any, linkedEmail) !== 'run') continue; const oRepos = (rt.storage as any).getRepositories(); // Back-fill this copy AND mark it done — even if it's still unread + pending. // A dual-delivered message is identical content, so it must be categorized @@ -1018,6 +1024,17 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi return; } + // A filter with "Skip AI checks" keeps every AI step below away from this + // email: categorizing, priority, the AI's spam verdict, automatic actions + // and drafted replies. Marked handled so neither trigger returns to it; + // unreadable rules leave it pending for the next pass. + const filterVerdict = await filterAiVerdict(storage, email); + if (filterVerdict === 'unknown') return; + if (filterVerdict === 'skip') { + (storage as any).getRepositories()?.agent?.markAgentGaveUp?.(emailId, {}); + return; + } + // Skip emails without body — can't categorize or score content without it const hasBody = (email.cleanBody && email.cleanBody.length > 0) || (email.rawBody && email.rawBody.length > 0); if (!hasBody) { @@ -1260,7 +1277,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // Copy this categorization to the same message in other accounts, so a // dual-delivered mail shows the same badge everywhere — free. if (categories.length > 0) { - propagateCategoriesToLinkedAccounts((email as any).messageId, categories, storage, { + await propagateCategoriesToLinkedAccounts((email as any).messageId, categories, storage, { priorityScore, priorityTier, priorityReasoning, recommendedAction, }); } @@ -2989,7 +3006,7 @@ function startPollingTrigger(): void { )?.all() as Array<{ mid: string; aiCategories: string | null }> | undefined; for (const r of rows || []) { const cats = mirrorableCategories(r.aiCategories, slugs); - if (cats?.length) propagateCategoriesToLinkedAccounts(r.mid, cats, storage); + if (cats?.length) await propagateCategoriesToLinkedAccounts(r.mid, cats, storage); // Yield to the event loop periodically — a large sweep is up to // accounts×500 propagations, each a synchronous scan of every // account's DB, so without this it blocks the main thread in one diff --git a/apps/desktop/src/components/AdvancedSearchPanel.tsx b/apps/desktop/src/components/AdvancedSearchPanel.tsx index 8e5bfd9d..b26718b9 100644 --- a/apps/desktop/src/components/AdvancedSearchPanel.tsx +++ b/apps/desktop/src/components/AdvancedSearchPanel.tsx @@ -3,7 +3,7 @@ import { Filter as FilterIcon, Paperclip, X } from 'lucide-react'; import { useState, useEffect, useRef, useCallback } from 'react'; import { useEmailStore } from '../store/email-store'; -import { setPendingFilterDraft } from '../utils/filter-draft-bridge'; +import { openFilterEditor } from '../utils/filter-draft-bridge'; interface Contact { id: string; @@ -316,8 +316,7 @@ export function AdvancedSearchPanel({ isOpen, onClose, onSearch, initialQuery = // Turn the current criteria into a new filter: stash a pre-filled draft and // deep-link to Settings → Filters, where the user picks the actions and saves. const handleCreateFilter = () => { - setPendingFilterDraft({ name: '', matchType: 'all', conditions: buildFilterConditions() }); - document.dispatchEvent(new CustomEvent('sarvinbox:open-settings', { detail: { tab: 'filters' } })); + openFilterEditor({ name: '', matchType: 'all', conditions: buildFilterConditions() }); onClose(); }; diff --git a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts index e7a0d4b0..39a151d7 100644 --- a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts +++ b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts @@ -26,6 +26,7 @@ import { useEmailStore } from '../../../store/email-store'; import type { LocalCalendarAvailability } from '../../../types/local-calendar'; import { needsAttachmentMetadata } from '../../../utils/attachment-metadata'; import { collapseDuplicateMessages } from '../../../utils/duplicate-messages'; +import { filterDraftFromSender, openFilterEditor } from '../../../utils/filter-draft-bridge'; import { toForwardSource } from '../../../utils/forward-quote'; import { paneAccountOf } from '../../../utils/pane-account'; import { savedDraftContent } from '../../../utils/saved-draft-content'; @@ -1560,9 +1561,11 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon } }; + // Open Settings → Filters with a new filter for this sender, "Skip AI + // checks" ticked; the user picks any other action and saves. const handleFilterLikeThis = (email: any) => { - if (!email) return; - alert(`Create filter for emails from: ${email.fromAddress}\n\nThis feature will be available in a future update.`); + const draft = filterDraftFromSender(email?.fromAddress); + if (draft) openFilterEditor(draft); }; const handleTranslate = (email: any) => { diff --git a/apps/desktop/src/components/settings/FiltersTab.tsx b/apps/desktop/src/components/settings/FiltersTab.tsx index 06e3db93..4c49d612 100644 --- a/apps/desktop/src/components/settings/FiltersTab.tsx +++ b/apps/desktop/src/components/settings/FiltersTab.tsx @@ -18,7 +18,10 @@ const OPERATOR_LABELS: Record = { const ACTION_LABELS: Record = { markRead: 'Mark as read', star: 'Star', archive: 'Archive', delete: 'Delete (move to Trash)', moveToSpam: 'Move to Spam', moveToFolder: 'Move to folder', applyLabel: 'Apply label', + skipAI: 'Skip AI checks', }; +/** The actions offered in the "Then" rows. "Skip AI checks" is its own tickbox. */ +const ROW_ACTION_TYPES = (Object.keys(ACTION_LABELS) as FilterActionType[]).filter(t => t !== 'skipAI'); const emptyCondition = (): FilterCondition => ({ field: 'from', operator: 'contains', value: '' }); const emptyAction = (): FilterAction => ({ type: 'markRead' }); @@ -31,12 +34,23 @@ interface DraftRule { actions: FilterAction[]; stopProcessing: boolean; applyToExisting: boolean; + /** Keep the background AI away from matching mail (a `skipAI` action when saved). */ + skipAI: boolean; } const emptyDraft = (): DraftRule => ({ name: '', matchType: 'all', conditions: [emptyCondition()], actions: [emptyAction()], stopProcessing: false, applyToExisting: false, + // On by default for every new filter: mail the user set a filter for is + // mail they have decided about, and the AI leaves it alone. + skipAI: true, }); +/** The actions a draft saves: its rows, plus `skipAI` when ticked. */ +const draftActions = (draft: Pick): FilterAction[] => [ + ...draft.actions.filter(a => a.type !== 'skipAI'), + ...(draft.skipAI ? [{ type: 'skipAI' as const }] : []), +]; + const summarize = (rule: FilterRule): string => { const conds = rule.conditions .map(c => `${FIELD_LABELS[c.field]} ${OPERATOR_LABELS[c.operator]} "${c.value}"`) @@ -84,6 +98,7 @@ export function FiltersTab() { name: seed.name, matchType: seed.matchType, conditions: seed.conditions.length ? seed.conditions : [emptyCondition()], + ...(seed.actions ? { actions: seed.actions } : {}), }); }, []); @@ -111,7 +126,8 @@ export function FiltersTab() { const saveDraft = async () => { if (!draft) return; const cleanConditions = draft.conditions.filter(c => c.value.trim()); - if (!draft.name.trim() || cleanConditions.length === 0 || draft.actions.length === 0) return; + const actions = draftActions(draft); + if (!draft.name.trim() || cleanConditions.length === 0 || actions.length === 0) return; setSaving(true); const wantApply = draft.applyToExisting; try { @@ -119,7 +135,7 @@ export function FiltersTab() { name: draft.name.trim(), matchType: draft.matchType, conditions: cleanConditions, - actions: draft.actions, + actions, stopProcessing: draft.stopProcessing, }; const res = draft.id @@ -167,9 +183,11 @@ export function FiltersTab() { name: rule.name, matchType: rule.matchType, conditions: rule.conditions.length ? rule.conditions : [emptyCondition()], - actions: rule.actions.length ? rule.actions : [emptyAction()], + // A filter that only skips the AI opens with no action rows. + actions: rule.actions.filter(a => a.type !== 'skipAI'), stopProcessing: rule.stopProcessing, applyToExisting: false, + skipAI: rule.actions.some(a => a.type === 'skipAI'), }); }; @@ -322,7 +340,7 @@ export function FiltersTab() {
{a.type === 'moveToFolder' && ( setDraft({ ...draft, skipAI: e.target.checked })} + /> + + Skip AI checks + + The AI won't categorize, prioritize, act on or draft replies to matching emails. + + +
@@ -382,7 +415,7 @@ export function FiltersTab() {
+ {error &&

{error}

} + + ); +} + +/** "Your key is locked", fixed guidance, and the passphrase form — the reader's prompt and the composer's. */ +export function PgpUnlockPrompt({ detail, ...form }: PgpUnlockFormProps & { detail: string }) { + return ( + + + + ); +} + +/** + * The composer's unlock prompt, for a composer reopened because main refused + * its send: the send asked to be signed with a key still locked this session + * (the `locked` code — the only cause main names). It closes once main says + * the key for `fromEmail` — the address this composer sends as — is open; + * then the user presses Send again. + */ +export function PgpSendUnlockPrompt({ fromEmail, onUnlocked }: { fromEmail: string | undefined; onUnlocked: () => void }) { + const recheck = async () => { + const locked = await window.electronAPI.pgp.signingKeyLocked(fromEmail ?? ''); + return locked.success && locked.data === false; + }; + return ( +
+ +
+ ); +} diff --git a/apps/desktop/src/components/email-detail/PgpMessageView.tsx b/apps/desktop/src/components/email-detail/PgpMessageView.tsx index 8d27949b..1eda3c8d 100644 --- a/apps/desktop/src/components/email-detail/PgpMessageView.tsx +++ b/apps/desktop/src/components/email-detail/PgpMessageView.tsx @@ -1,20 +1,16 @@ -import { Download, Loader2, Lock, LockKeyhole, RotateCw, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'; -import { useEffect, useState, type FormEvent, type ReactNode } from 'react'; +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; +import { Download, Loader2, Lock, RotateCw, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'; +import { useEffect, useState, type ReactNode } from 'react'; import { messageAccountOf } from '../../utils/pane-account'; import { remoteImageFactsOf } from '../../utils/remote-images'; import { UnscannedAttachmentNotice } from '../attachment-viewer/AttachmentDownloadStatus'; import { formatSize } from '../attachment-viewer/AttachmentViewer'; +import { PgpNotice, PgpUnlockForm } from '../PgpUnlockPrompt'; import { SandboxedEmailBody } from '../SandboxedEmailBody'; import { Tooltip } from '../Tooltip'; -import { - pgpBadge, - pgpFailureView, - unlockLockedKeys, - type PgpBadge, - type PgpViewResult, -} from './pgp-view-model'; +import { pgpBadge, pgpFailureView, type PgpBadge, type PgpViewResult } from './pgp-view-model'; export interface PgpMessageViewProps { email: { @@ -56,54 +52,6 @@ function PgpBadgeChip({ badge, encrypted }: { badge: PgpBadge; encrypted: boolea ); } -function UnlockForm({ onUnlocked }: { onUnlocked: () => void }) { - const [passphrase, setPassphrase] = useState(''); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - - const submit = async (event: FormEvent) => { - event.preventDefault(); - if (!passphrase || busy) return; - setBusy(true); - setError(null); - try { - const unlocked = await unlockLockedKeys(window.electronAPI.pgp, passphrase); - if (unlocked > 0) { - setPassphrase(''); - onUnlocked(); - } else { - setError('That passphrase did not unlock any of your keys.'); - } - } catch (caught) { - setError((caught as Error).message); - } finally { - setBusy(false); - } - }; - - return ( -
- setPassphrase(event.target.value)} - placeholder="Key passphrase" - aria-label="Key passphrase" - className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm" - /> - - {error &&

{error}

} -
- ); -} - /** * The reader for OpenPGP mail. An encrypted message's stored body is only a * placeholder, so this opens it from the message source (in the main process) @@ -125,7 +73,8 @@ export function PgpMessageView({ email, paneAccountId, children }: PgpMessageVie window.electronAPI.pgp .open(email.id, accountId) .then((view) => current && setState({ phase: 'done', view })) - .catch((error: Error) => current && setState({ phase: 'done', view: { ok: false, code: 'unavailable', error: error.message } })); + // A rejected bridge reads like any other failure to open — never the rejection's own text. + .catch(() => current && setState({ phase: 'done', view: { ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE } })); return () => { current = false; }; @@ -161,26 +110,28 @@ export function PgpMessageView({ email, paneAccountId, children }: PgpMessageVie if (!view.ok) { const failure = pgpFailureView(view.code, view.error); + // After the passphrase was tried: open the message again. Still locked → + // the form says so (the one sentence) and stays for another try; anything + // else is what the reader shows now. Never a count of keys unlocked. + const recheckOpen = async () => { + const reopened = await window.electronAPI.pgp.open(email.id, accountId); + if (!reopened.ok && reopened.code === 'locked') return false; + setState({ phase: 'done', view: reopened }); + return true; + }; return ( -
-
- -
-
{failure.title}
-

{failure.detail}

- {failure.canUnlock && setAttempt((n) => n + 1)} />} - {failure.canRetry && ( - - )} -
-
-
+ + {failure.canUnlock && } + {failure.canRetry && ( + + )} + ); } diff --git a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts index e7a0d4b0..10a32233 100644 --- a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts +++ b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts @@ -1,5 +1,5 @@ import { hasGlobalDomParser } from '@sarv-in/email-chat-view/transform'; -import type { EmailRecord } from '@sarvinbox/core'; +import type { EmailRecord, SendPgpRequest } from '@sarvinbox/core'; import { compareConversationOrder, conversationFoldersOf, @@ -209,13 +209,13 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon // written for. Composers get it only on that message (see inlineReplyDraft // below); moving the composer elsewhere does NOT drop it, so coming back to // that message brings the draft (and its stored Message-ID) back with it. - const [inlineReplySeed, setInlineReplySeed] = useState | undefined>(undefined); + const [inlineReplySeed, setInlineReplySeed] = useState | undefined>(undefined); const inlineReplyHandlerRef = useRef<(mode: 'reply' | 'replyAll') => void>(() => { }); const consumedReplyRequestRef = useRef(null); const [showInlineForward, setShowInlineForward] = useState(false); const [forwardingEmail, setForwardingEmail] = useState(null); // The forward's seed (what Undo send restored), on the same terms as the reply's. - const [inlineForwardSeed, setInlineForwardSeed] = useState | undefined>(undefined); + const [inlineForwardSeed, setInlineForwardSeed] = useState | undefined>(undefined); const inlineForwardHandlerRef = useRef<() => void>(() => { }); // What each open composer is handed: its seed, only when the seed was written // for the message that composer is open on — never another message's. @@ -1125,6 +1125,8 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon draftMessageId: restoreDraft.draftMessageId, unsaved: restoreDraft.unsaved, ...(restoreDraft.calendarAvailability ? { calendarAvailability: restoreDraft.calendarAvailability } : {}), + // A send refused for a locked signing key reopens with the unlock prompt. + ...(restoreDraft.pgpUnlock ? { pgpUnlock: restoreDraft.pgpUnlock } : {}), }); setShowInlineReply(true); setShowInlineForward(false); @@ -1140,6 +1142,7 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon draftMessageId: restoreDraft.draftMessageId, unsaved: restoreDraft.unsaved, ...(restoreDraft.calendarAvailability ? { calendarAvailability: restoreDraft.calendarAvailability } : {}), + ...(restoreDraft.pgpUnlock ? { pgpUnlock: restoreDraft.pgpUnlock } : {}), }); setShowInlineForward(true); setShowInlineReply(false); diff --git a/apps/desktop/src/components/email-detail/pgp-view-model.ts b/apps/desktop/src/components/email-detail/pgp-view-model.ts index 4def9ebc..8aa1c761 100644 --- a/apps/desktop/src/components/email-detail/pgp-view-model.ts +++ b/apps/desktop/src/components/email-detail/pgp-view-model.ts @@ -56,35 +56,43 @@ export function pgpBadge(wasEncrypted: boolean, signature: PgpSignatureView): Pg export type PgpOpenFailureCode = Extract['code']; +/** + * The unlock prompt's fixed words — the reader's (a message encrypted to a + * locked key) and the composer's (a send that must be signed with one). They + * never vary with why an unlock failed: that is always PGP_FAILURE_MESSAGE. + */ +export const PGP_LOCKED_TITLE = 'Your key is locked'; +export const PGP_UNLOCK_TO_READ = 'Enter the passphrase of your OpenPGP key to read this message. It stays unlocked until you quit.'; +export const PGP_UNLOCK_TO_SIGN = 'Enter the passphrase of your OpenPGP key to sign this message, then send it again. It stays unlocked until you quit.'; + +/** + * The one line of guidance under EVERY failure to open, whatever the cause — + * so the user is still pointed at the fix for a key they have not added, + * without the screen telling that cause apart from the others. + */ +export const PGP_FAILURE_HINT = "If it was encrypted to a key you haven't added, import that key in Settings → Encryption."; + export interface PgpFailureView { title: string; detail: string; + /** Fixed guidance under the sentence, the same for every failure. */ + hint?: string; /** Unlock with a passphrase. */ canUnlock: boolean; canRetry: boolean; } +/** + * What the reader shows for a message that did not open. A locked key is a + * prompt, with fixed guidance; every other failure looks exactly the same — + * the same title, main's one sentence (PGP_FAILURE_MESSAGE), the same line of + * guidance and a retry — whether the key was missing, the ciphertext damaged + * or tampered with, or the source unreachable (CASA 4.1.4: what the user sees + * must not tell causes apart). + */ export function pgpFailureView(code: PgpOpenFailureCode, error: string): PgpFailureView { - switch (code) { - case 'locked': - return { - title: 'Your key is locked', - detail: 'Enter the passphrase of your OpenPGP key to read this message. It stays unlocked until you quit.', - canUnlock: true, - canRetry: false, - }; - case 'no-key': - return { - title: 'None of your keys can open this message', - detail: 'It was encrypted to a key you do not have here. Import that key in Settings → Encryption.', - canUnlock: false, - canRetry: false, - }; - case 'bad-data': - return { title: 'This encrypted message is damaged', detail: error, canUnlock: false, canRetry: false }; - case 'unavailable': - return { title: 'The encrypted message could not be loaded', detail: error, canUnlock: false, canRetry: true }; - } + if (code === 'locked') return { title: PGP_LOCKED_TITLE, detail: PGP_UNLOCK_TO_READ, canUnlock: true, canRetry: false }; + return { title: 'Encrypted message', detail: error, hint: PGP_FAILURE_HINT, canUnlock: false, canRetry: true }; } /** The two bridge calls unlocking needs — injected so the loop is tested without Electron. */ @@ -97,11 +105,15 @@ export interface PgpUnlockApi { * Try the passphrase on every locked own key. The reader does not know which * key a message was encrypted to until one opens it, and asking the user to * pick a fingerprint is asking them a question they cannot answer. - * Resolves to how many keys it unlocked. + * + * Says nothing about success: whether the key a message or a send NEEDS is + * open now is for the caller to check afterwards. Counting keys got both + * wrong — a key unlocked elsewhere left nothing locked (read as failure: a + * dead end), and the passphrase of some other key read as success (the + * prompt closed, and the send was refused again). */ -export async function unlockLockedKeys(api: PgpUnlockApi, passphrase: string): Promise { +export async function unlockLockedKeys(api: PgpUnlockApi, passphrase: string): Promise { const listed = await api.listOwnKeys(); const locked = (listed.data ?? []).filter((key) => !key.unlocked); - const results = await Promise.all(locked.map((key) => api.unlock(key.fingerprint, passphrase))); - return results.filter((result) => result.success).length; + await Promise.allSettled(locked.map((key) => api.unlock(key.fingerprint, passphrase))); } diff --git a/apps/desktop/src/components/email-detail/types.ts b/apps/desktop/src/components/email-detail/types.ts index a1df5789..552f1be9 100644 --- a/apps/desktop/src/components/email-detail/types.ts +++ b/apps/desktop/src/components/email-detail/types.ts @@ -1,5 +1,5 @@ import type { ChatMessage } from '@sarv-in/email-chat-view'; -import type { EmailRecord } from '@sarvinbox/core'; +import type { EmailRecord, SendPgpRequest } from '@sarvinbox/core'; import type { SignatureDetectionResult } from '../../services/ai-service'; @@ -65,6 +65,8 @@ export interface EmailDetailContext { isAIDraft?: boolean; aiReasoning?: string; agentDecisionId?: string; + /** Reopened because main refused its send for a locked signing key (RestoreDraft.pgpUnlock). */ + pgpUnlock?: SendPgpRequest; }; showInlineForward: boolean; forwardingEmail: any | null; @@ -76,6 +78,7 @@ export interface EmailDetailContext { attachments: any[]; draftMessageId?: string; unsaved?: boolean; + pgpUnlock?: SendPgpRequest; }; /** The reader's chat-view setting for this email (auto setting, or the toggle). */ chatViewEnabled: boolean; diff --git a/apps/desktop/src/components/settings/EncryptionTab.tsx b/apps/desktop/src/components/settings/EncryptionTab.tsx index 905a2ca8..fcc8509b 100644 --- a/apps/desktop/src/components/settings/EncryptionTab.tsx +++ b/apps/desktop/src/components/settings/EncryptionTab.tsx @@ -1,3 +1,4 @@ +import { PGP_FAILURE_MESSAGE, type PgpFlowCode } from '@sarvinbox/core/pgp-failure'; import { KeyRound, Loader2 } from 'lucide-react'; import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'; @@ -8,6 +9,8 @@ import { credentialStoreProtection } from '../../utils/secure-storage-status'; import { useConfirm } from '../ConfirmDialog'; import { + IMPORT_PASSPHRASE_HINT, + UNLOCK_HINT, keyAddressChoices, keySourceLabel, keyWarnings, @@ -48,6 +51,11 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { const [notice, setNotice] = useState(null); const [busy, setBusy] = useState(false); const [keyAction, setKeyAction] = useState(null); + // Set when main answered `passphrase-required`: the create form then asks + // for one even if the keychain check said none was needed, and the import + // form says a passphrase is needed. + const [createNeedsPassphrase, setCreateNeedsPassphrase] = useState(false); + const [importNeedsPassphrase, setImportNeedsPassphrase] = useState(false); const reload = useCallback(async () => { try { @@ -57,10 +65,11 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { setContactKeys(contacts.success ? contacts.data : []); const failed = [own, contacts].find((result) => !result.success); if (failed && !failed.success) setNotice({ text: failed.error, tone: 'error' }); - } catch (error) { + } catch { + // A rejected bridge: the one OpenPGP sentence, never the rejection's text. setOwnKeys([]); setContactKeys([]); - setNotice({ text: errorText(error), tone: 'error' }); + setNotice({ text: PGP_FAILURE_MESSAGE, tone: 'error' }); } }, [pgp]); @@ -68,22 +77,32 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { void reload(); }, [reload]); - /** Run one bridge call: busy while it runs, its error or success on the notice line, then refresh. */ - const run = async (task: () => Promise>, success: (data: T) => string | null): Promise => { + /** + * Run one bridge call: busy while it runs, its error or success on the + * notice line, then refresh. A failure shows main's sentence as it came + * (PGP_FAILURE_MESSAGE for every OpenPGP cause), and a prompt code goes to + * `onPrompt` so the caller can open what it asks for. + */ + const run = async ( + task: () => Promise>, + success: (data: T) => string | null, + onPrompt?: (code: PgpFlowCode) => void, + ): Promise => { setBusy(true); setNotice(null); try { const result = await task(); if (!result.success) { setNotice({ text: result.error, tone: 'error' }); + if (result.code) onPrompt?.(result.code); return false; } const text = success(result.data); if (text) setNotice({ text, tone: 'success' }); await Promise.all([reload(), retryStorageStatus()]); return true; - } catch (error) { - setNotice({ text: errorText(error), tone: 'error' }); + } catch { + setNotice({ text: PGP_FAILURE_MESSAGE, tone: 'error' }); return false; } finally { setBusy(false); @@ -108,10 +127,14 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { }; const submitKeyAction = async ({ fingerprint, kind }: NonNullable, passphrase: string) => { + // A failed unlock keeps its form open for another try; a backup of a key + // that is locked this session swaps to the unlock form. const done = kind === 'unlock' ? await run(() => pgp.unlock(fingerprint, passphrase), () => 'Key unlocked until you quit') - : await run(() => pgp.exportOwnKey(fingerprint, passphrase), savedText('Backup')); + : await run(() => pgp.exportOwnKey(fingerprint, passphrase), savedText('Backup'), (code) => { + if (code === 'locked') setKeyAction({ fingerprint, kind: 'unlock' }); + }); if (done) setKeyAction(null); }; @@ -181,8 +204,10 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { {keyAction?.fingerprint === key.fingerprint && ( submitKeyAction(keyAction, passphrase)} @@ -198,9 +223,17 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) {
run(() => pgp.generateKey(input), (key) => `Created a key for ${key.email}`)} + onCreate={(input) => + run( + () => pgp.generateKey(input), + (key) => `Created a key for ${key.email}`, + (code) => { + if (code === 'passphrase-required') setCreateNeedsPassphrase(true); + }, + ) + } />
@@ -208,9 +241,19 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { - run(() => pgp.importOwnKey(armored, passphrase), (keys) => `Imported ${keys.length === 1 ? 'your key' : `${keys.length} keys`}`) + run( + () => pgp.importOwnKey(armored, passphrase), + (keys) => { + setImportNeedsPassphrase(false); + return `Imported ${keys.length === 1 ? 'your key' : `${keys.length} keys`}`; + }, + (code) => { + if (code === 'passphrase-required') setImportNeedsPassphrase(true); + }, + ) } /> @@ -380,6 +423,8 @@ function CreateKeyForm(props: { function ArmoredImportForm(props: { what: string; withPassphrase?: boolean; + /** Fixed guidance under the passphrase field, shown once main asked for a passphrase. */ + passphraseHint?: string; busy: boolean; onImport: (armored: string, passphrase?: string) => Promise; }) { @@ -420,6 +465,11 @@ function ArmoredImportForm(props: { {props.withPassphrase && ( setPassphrase(event.target.value)} className={INPUT} /> )} + {props.withPassphrase && props.passphraseHint && ( +

+ {props.passphraseHint} +

+ )} diff --git a/apps/desktop/src/components/settings/encryption-view.ts b/apps/desktop/src/components/settings/encryption-view.ts index 404881eb..53af7899 100644 --- a/apps/desktop/src/components/settings/encryption-view.ts +++ b/apps/desktop/src/components/settings/encryption-view.ts @@ -15,6 +15,16 @@ export { shortFingerprint }; type KeyState = Pick & { unlocked?: boolean }; +/** + * The two prompts main may ask for (its `code`), worded once and the same + * whatever led to them. A failure itself always reads main's one sentence + * (PGP_FAILURE_MESSAGE); these only say what to do next (CASA 4.1.4). + */ +/** Under the unlock field, also when a backup of a locked key opened it. */ +export const UNLOCK_HINT = 'Enter the passphrase of this key. It stays unlocked until you quit.'; +/** Under an import's passphrase field once main answered `passphrase-required`. */ +export const IMPORT_PASSPHRASE_HINT = 'A passphrase is needed for this key. Enter it, then import again.'; + /** Short warnings for a key row, most serious first. Empty for a key that is fine to use. */ export function keyWarnings(key: KeyState): string[] { return [ diff --git a/apps/desktop/src/components/useCompose.ts b/apps/desktop/src/components/useCompose.ts index 5febf7f3..2393bd0f 100644 --- a/apps/desktop/src/components/useCompose.ts +++ b/apps/desktop/src/components/useCompose.ts @@ -1,3 +1,4 @@ +import type { SendPgpRequest } from '@sarvinbox/core'; import { useState, useRef, useCallback, type MouseEvent as ReactMouseEvent } from 'react'; import { useClickAway } from '../hooks/useClickAway'; @@ -40,6 +41,9 @@ export interface ComposeDraft { /** The draft was saved encrypted, so it reopens with encryption on. */ pgpEncrypted?: boolean; calendarAvailability?: LocalCalendarAvailability; + /** Reopened because main refused the send for a locked signing key: show + * the unlock prompt, with encrypt/sign as that send asked. */ + pgpUnlock?: SendPgpRequest; } export interface UseComposeProps { diff --git a/apps/desktop/src/hooks/usePgpCompose.ts b/apps/desktop/src/hooks/usePgpCompose.ts index c0fe4a18..5a67746d 100644 --- a/apps/desktop/src/hooks/usePgpCompose.ts +++ b/apps/desktop/src/hooks/usePgpCompose.ts @@ -1,3 +1,4 @@ +import type { SendPgpRequest } from '@sarvinbox/core'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { @@ -29,12 +30,20 @@ export interface PgpComposeControls { * their own. A lookup can ask the recipient's mail domain for a key (WKD), * which tells that domain someone is writing to the address — not something * to do on behalf of a user who has never set up encryption. + * + * `restored` is what a send refused for a locked key asked for: the reopened + * composer starts with exactly those toggles, as the user's own choice. */ -export function usePgpCompose(fromEmail: string | undefined, recipients: string[], replyToEncrypted: boolean): PgpComposeControls { +export function usePgpCompose( + fromEmail: string | undefined, + recipients: string[], + replyToEncrypted: boolean, + restored?: SendPgpRequest, +): PgpComposeControls { const [defaults, setDefaults] = useState(null); const [resolved, setResolved] = useState<{ forList: string; keys: RecipientKeyStatus[] } | null>(null); - const [encryptOverride, setEncryptOverride] = useState(null); - const [signOverride, setSignOverride] = useState(null); + const [encryptOverride, setEncryptOverride] = useState(restored ? restored.encrypt : null); + const [signOverride, setSignOverride] = useState(restored ? restored.sign : null); useEffect(() => { let cancelled = false; diff --git a/apps/desktop/src/store/slices/compose-slice.ts b/apps/desktop/src/store/slices/compose-slice.ts index 430fa67b..f5f2d8b1 100644 --- a/apps/desktop/src/store/slices/compose-slice.ts +++ b/apps/desktop/src/store/slices/compose-slice.ts @@ -2,7 +2,7 @@ import type { EmailRecord, SendAttachment } from '@sarvinbox/core'; import { readUndoSendDelayMs } from '../../utils/app-settings'; import { effectiveSmtpConfig } from '../helpers'; -import type { ComposeSlice, SliceCreator } from '../types'; +import type { ComposeSlice, RestoreDraft, SliceCreator } from '../types'; /** A Message-ID is `<...>`; a row id is `-` (see core's generateId). */ export function looksLikeMessageId(value: string): boolean { @@ -72,6 +72,16 @@ function attachmentByteLength(file: SendAttachment): number { // undoSend (intentional cancel) and when the timeout fires naturally. let pendingFlush: ((early?: boolean) => Promise) | null = null; +/** + * What reopens the composer a send came from, holding what it held: the inline + * reply or forward through `restoreDraft` (the thread view seeds itself from + * it), the popup by reopening the compose window too (App hands it the draft). + */ +const reopenComposer = (draft: RestoreDraft) => ({ + restoreDraft: draft, + ...(draft.isInline === false ? { compose: { isOpen: true, mode: draft.mode, replyToEmail: draft.replyToEmail } } : {}), +}); + export const createComposeSlice: SliceCreator = (set, get) => ({ compose: { isOpen: false, @@ -160,20 +170,9 @@ export const createComposeSlice: SliceCreator = (set, get) => ({ threadEmails: filtered, pendingSend: null, sendingStatus: 'idle', - restoreDraft: pendingSend.draft, + ...reopenComposer(pendingSend.draft), }); - // For popup compose (not inline), reopen the compose window - if (pendingSend.draft.isInline === false) { - set({ - compose: { - isOpen: true, - mode: pendingSend.draft.mode, - replyToEmail: pendingSend.draft.replyToEmail, - }, - }); - } - console.log('[Store] Undo send — cancelled held outbox send, restoring draft'); }, @@ -319,6 +318,18 @@ export const createComposeSlice: SliceCreator = (set, get) => ({ // Store draft info and schedule actual send after delay const { draft, draftCleanup, ...sendOptions } = options; + // Main refused the send because it must be signed with a key still locked + // this session (`code: 'locked'`, the only cause it names; nothing was + // queued). The composer closed when Send was pressed, so it is reopened + // with what it held — the draft row was never deleted — and the unlock + // prompt; after unlocking, the user sends again. Without a draft there is + // no composer to reopen, and it is an ordinary failure. + const refusedLocked = (result: { code?: 'locked' } | undefined): boolean => { + if (result?.code !== 'locked' || !draft) return false; + set({ sendingStatus: 'idle', ...reopenComposer({ ...draft, pgpUnlock: { encrypt: sendOptions.pgp?.encrypt === true, sign: true } }) }); + return true; + }; + const payload = { to: sendOptions.to, cc: sendOptions.cc, @@ -343,6 +354,7 @@ export const createComposeSlice: SliceCreator = (set, get) => ({ if (scheduledAt !== null) { try { const res = await window.electronAPI.smtp.scheduleSend(payload, scheduledAt); + if (refusedLocked(res)) return; if (!res?.success) throw new Error(res?.error || 'Failed to schedule send'); } catch (error) { // Nothing was persisted: keep the draft and surface the failure rather @@ -374,6 +386,10 @@ export const createComposeSlice: SliceCreator = (set, get) => ({ let sendId: number | null = null; try { const enq = await window.electronAPI.smtp.sendWithUndo(payload, undoDelayMs); + if (refusedLocked(enq)) { + set({ threadEmails: get().threadEmails.filter(e => e.id !== optimisticId) }); + return; + } if (enq?.success && typeof enq.id === 'number') { sendId = enq.id; } else { diff --git a/apps/desktop/src/store/types.ts b/apps/desktop/src/store/types.ts index f6fa27aa..0ba9b8f2 100644 --- a/apps/desktop/src/store/types.ts +++ b/apps/desktop/src/store/types.ts @@ -1,4 +1,4 @@ -import type { AiAction, EmailRecord, FolderRecord, Label, SyncStatus, RealtimeEvent, SMTPConfig, SendEmailOptions, ViewFilter } from '@sarvinbox/core'; +import type { AiAction, EmailRecord, FolderRecord, Label, SyncStatus, RealtimeEvent, SMTPConfig, SendEmailOptions, SendPgpRequest, ViewFilter } from '@sarvinbox/core'; import type { StateCreator } from 'zustand'; import type { AccountRevocation } from '../../electron/services/account-revocation'; @@ -38,6 +38,8 @@ export interface ComposeState { /** Saved encrypted — reopens with encryption on. */ pgpEncrypted?: boolean; calendarAvailability?: LocalCalendarAvailability; + /** A send refused for a locked signing key — see RestoreDraft.pgpUnlock. */ + pgpUnlock?: SendPgpRequest; }; } @@ -563,6 +565,16 @@ export interface RestoreDraft { * 10s), so closing the reopened composer unedited must still save it. */ unsaved?: boolean; calendarAvailability?: LocalCalendarAvailability; + /** The send-as alias the composer had chosen (undefined = the account's own + * address). Reopened without it, the composer would send — sign, and encrypt + * or not — as the primary address instead. */ + from?: string; + /** + * Set when main refused the send because it asked to be signed with a key + * still locked this session (its `locked` code): the reopened composer shows + * the unlock prompt, with encrypt/sign as this send asked. + */ + pgpUnlock?: SendPgpRequest; } export interface ComposeSlice { diff --git a/apps/desktop/src/utils/pgp-compose.ts b/apps/desktop/src/utils/pgp-compose.ts index 7521be70..54216d1a 100644 --- a/apps/desktop/src/utils/pgp-compose.ts +++ b/apps/desktop/src/utils/pgp-compose.ts @@ -41,6 +41,14 @@ export interface PgpComposeState { resolving: boolean; /** What the send carries; undefined when OpenPGP is not in play. */ request: SendPgpRequest | undefined; + /** + * Encryption was asked for — the user's toggle, or the request a send + * refused for a locked key restored — but nothing can carry it now: the From + * address has no key (an alias swapped for the primary), or its defaults + * have not loaded. The composer must not send: the request would be + * undefined, and the mail would go out in plaintext. + */ + downgrade: boolean; } export function pgpComposeState(input: PgpComposeInput): PgpComposeState { @@ -58,6 +66,7 @@ export function pgpComposeState(input: PgpComposeInput): PgpComposeState { missing, resolving: available && input.keys === null, request: available ? { encrypt, sign } : undefined, + downgrade: !available && input.encryptOverride === true, }; } diff --git a/apps/desktop/src/utils/saved-draft-content.ts b/apps/desktop/src/utils/saved-draft-content.ts index 0add43d2..4214daad 100644 --- a/apps/desktop/src/utils/saved-draft-content.ts +++ b/apps/desktop/src/utils/saved-draft-content.ts @@ -1,8 +1,12 @@ +import { createLogger } from '@sarvinbox/core/logger'; + import type { AttachmentFile } from '../components/useCompose'; import type { LocalCalendarAvailability } from '../types/local-calendar'; import { loadEmailAttachments, type AttachmentSource } from './compose-attachments'; +const logger = createLogger('Draft'); + /** Plain text as editor paragraphs, one per line — an empty line keeps its height. */ export const textToParagraphsHtml = (text: string): string => text @@ -34,7 +38,8 @@ export interface SavedDraftContent { async function openEncryptedDraft(draft: SavedDraftRow): Promise { const opened = await window.electronAPI.pgp.openDraft(draft.id, draft.accountId); if (!opened.ok) { - console.warn('[Draft] Encrypted draft could not be opened:', opened.code, opened.error); + // The code only ('locked' or 'failed'): main already logged the cause. + logger.warn('Encrypted draft could not be opened', { code: opened.code }); return null; } return { diff --git a/apps/desktop/src/utils/send-failure.ts b/apps/desktop/src/utils/send-failure.ts index 46e260a8..20bb7ae0 100644 --- a/apps/desktop/src/utils/send-failure.ts +++ b/apps/desktop/src/utils/send-failure.ts @@ -9,7 +9,7 @@ const log = createLogger('Compose'); * message and logging stay consistent. * * The log line names the KIND of failure only: a send's error text (the mail - * server's reply, "No encryption key for ") can quote the + * server's reply, such as "550 : no such user") can quote the * recipients, and the renderer's errors reach app.log. The user still sees the * full text in the dialog. */ diff --git a/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts b/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts index ecdec412..78f71741 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts @@ -1,4 +1,5 @@ -import { generateKeyPair, openStoredPgp, readAnyKey, readOpenedContent, readUnlockedPrivateKey } from '@sarvinbox/core/pgp'; +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { PGP_FAILURE_MESSAGE, generateKeyPair, openStoredPgp, readAnyKey, readOpenedContent, readUnlockedPrivateKey } from '@sarvinbox/core/pgp'; import type * as openpgp from 'openpgp'; import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -31,6 +32,7 @@ vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountT vi.mock('../../../../electron/services/attachment-cache', () => ({ seedAttachmentCache: vi.fn() })); vi.mock('../../../../electron/services/pgp-service', () => ({ getPgpKeyring: () => h.keyring })); +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; // eslint-disable-next-line import/order -- see local-mirror-content-hash.test.ts import { newMigratedDb } from '../../../../../../packages/storage-node/src/test-support/test-db'; @@ -102,10 +104,11 @@ describe('encryptDraftMime', () => { expect((await decrypt(encrypted)).body).toContain(SECRET); }); + // Changed deliberately (CASA 4.1.4): the refusal used to say "No OpenPGP key for
…". // Breaks: an account with no key gets its "encrypted" draft saved as plaintext. it('refuses when the address has no key of its own', async () => { - await expect(encryptDraftMime(Buffer.from('x'), 'other@x.com', h.keyring as any)).rejects.toThrow('No OpenPGP key for other@x.com'); - await expect(encryptDraftMime(Buffer.from('x'), '', h.keyring as any)).rejects.toThrow('this account'); + await expect(encryptDraftMime(Buffer.from('x'), 'other@x.com', h.keyring as any)).rejects.toMatchObject({ code: 'not-found', message: PGP_FAILURE_MESSAGE }); + await expect(encryptDraftMime(Buffer.from('x'), '', h.keyring as any)).rejects.toMatchObject({ code: 'not-found', message: PGP_FAILURE_MESSAGE }); }); }); @@ -165,16 +168,37 @@ describe('saveDraftToIMAP, encrypted', () => { const append = target(db); const before = (db.prepare('SELECT COUNT(*) AS n FROM emails').get() as { n: number }).n; + // Changed deliberately (CASA 4.1.4): the answer used to be "The draft could not be encrypted, so it + // was not saved: "; it is now the one OpenPGP sentence, whatever failed. h.keyring = { ownPublicKeyFor: vi.fn(async () => null) }; - expect(await saveDraftToIMAP(encryptedDraft)).toMatchObject({ success: false, error: expect.stringContaining('was not saved') }); + expect(await saveDraftToIMAP(encryptedDraft)).toEqual({ success: false, error: PGP_FAILURE_MESSAGE }); h.keyring = { ownPublicKeyFor: vi.fn(async () => { throw new Error('keyring unreadable'); }) }; - expect(await saveDraftToIMAP(encryptedDraft)).toMatchObject({ success: false, error: expect.stringContaining('keyring unreadable') }); + expect(await saveDraftToIMAP(encryptedDraft)).toEqual({ success: false, error: PGP_FAILURE_MESSAGE }); expect(append).not.toHaveBeenCalled(); expect((db.prepare('SELECT COUNT(*) AS n FROM emails').get() as { n: number }).n).toBe(before); }); + // Breaks (CASA 4.1.4): why a draft could not be encrypted — a library + // message, the keyring's text, the account's address — reaches app.log. + it('logs a draft it could not encrypt by class and code only', async () => { + const SENTINEL = 'sentinel-draft@example.org'; + target(draftsDb()); + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + h.keyring = { ownPublicKeyFor: vi.fn(async () => { throw Object.assign(new Error(`no key packet for ${SENTINEL}`), { code: 'ERR_CRAFTED' }); }) }; + expect(await saveDraftToIMAP({ ...encryptedDraft, accountEmail: SENTINEL })).toEqual({ success: false, error: PGP_FAILURE_MESSAGE }); + h.keyring = { ownPublicKeyFor: vi.fn(async () => null) }; + expect(await saveDraftToIMAP({ ...encryptedDraft, accountEmail: SENTINEL })).toEqual({ success: false, error: PGP_FAILURE_MESSAGE }); + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.containing("Encrypted draft not saved { name: 'Error', code: 'ERR_CRAFTED' }")).toHaveLength(1); + expect(logs.containing("Encrypted draft not saved { name: 'PgpKeyringError', code: 'not-found' }")).toHaveLength(1); + } finally { + logs.stop(); + } + }); + // Breaks: every ordinary draft now needs a key, or is marked encrypted. it('leaves an unencrypted draft exactly as before', async () => { const db = draftsDb(); diff --git a/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts index 6af1d277..7c739d2c 100644 --- a/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts @@ -1,4 +1,7 @@ -import { PGP_UNREADABLE_KEY_MESSAGE, PgpKeyError, readAllKeys } from '@sarvinbox/core/pgp'; +import { inspect } from 'node:util'; + +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { PGP_FAILURE_MESSAGE, PgpKeyError, PgpOpenError, readAllKeys } from '@sarvinbox/core/pgp'; import * as openpgp from 'openpgp'; import { describe, expect, it, vi } from 'vitest'; @@ -26,11 +29,11 @@ const h = vi.hoisted(() => ({ window: null as unknown, })); +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; import { createPgpHandlers, getPgpReader, PGP_FILE_WRITE_FAILED_MESSAGE, - PGP_REQUEST_FAILED_MESSAGE, registerPgpHandlers, safeDefaultName, storedSourceFor, @@ -39,15 +42,21 @@ import { import { AttachmentOperationProtection, setAttachmentOperationProtection } from '../../../../electron/services/attachment-download-protection'; import { PgpKeyringError, type PgpKeyring } from '../../../../electron/services/pgp-keyring'; import type { PgpReader } from '../../../../electron/services/pgp-reader'; -import { KEYCHAIN_REFUSED_MESSAGE, SealError } from '../../../../electron/services/pgp-secret-seal'; +import { SealError } from '../../../../electron/services/pgp-secret-seal'; /** * OpenPGP IPC. What this protects: a private-key backup or a decrypted * attachment written somewhere the user did not choose; plaintext kept in - * memory after the key that opened it is deleted; a keyring refusal ("locked", - * "needs a passphrase") reaching the renderer as an opaque crash; and compose - * offering to sign from an address with no key. + * memory after the key that opened it is deleted; a prompt ("locked", "needs a + * passphrase") reaching the renderer without its code; any OpenPGP failure + * reaching it in words that vary with the cause, or the library's text + * reaching the log (CASA 4.1.4); and compose offering to sign from an address + * with no key. */ +const FAILED = { success: false, error: PGP_FAILURE_MESSAGE } as const; +/** Log lines as app.log prints them: objects through util.inspect. */ +const warnLines = (warn: { mock: { calls: unknown[][] } }) => + warn.mock.calls.map((call) => call.map((arg) => (typeof arg === 'string' ? arg : inspect(arg))).join(' ')); const keyringStub = (over: Partial> = {}) => ({ keychainAvailable: vi.fn(() => true), @@ -104,68 +113,108 @@ describe('key management', () => { const { handlers, keyring } = setup(); await handlers['pgp:generateKey']({ name: ' Rita ', email: ' rita@example.com ', passphrase: '' }); expect(keyring.generateOwnKey).toHaveBeenCalledWith({ name: 'Rita', email: 'rita@example.com', passphrase: undefined }); - expect(await handlers['pgp:generateKey']({ email: ' ' })).toMatchObject({ success: false, error: 'An email address is required' }); - expect(await handlers['pgp:generateKey'](undefined as never)).toMatchObject({ success: false }); - }); - - // Breaks: a keyring refusal arrives without its code, so the UI cannot ask for the passphrase. - it('passes keyring and key errors through with their codes', async () => { + // Changed deliberately (CASA 4.1.4): a missing argument used to answer "An email address is required". + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await handlers['pgp:generateKey']({ email: ' ' })).toEqual(FAILED); + expect(await handlers['pgp:generateKey'](undefined as never)).toEqual(FAILED); + vi.restoreAllMocks(); + }); + + // Changed deliberately (CASA 4.1.4): keyring and key refusals used to arrive in their own words, + // with their codes ('bad-passphrase', 'bad-key', …) passed through. + // Breaks: a prompt ('passphrase-required', 'locked') arrives without its + // code, so the UI cannot ask for the passphrase or offer to unlock — or a + // failure that is not a prompt ("wrong passphrase") is told apart. + it('passes only the prompt codes through, every answer the one sentence', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const keyring = keyringStub({ importOwnKey: vi.fn(async () => { - throw new PgpKeyringError('This key needs its passphrase', 'passphrase-required'); + throw new PgpKeyringError('passphrase-required'); + }), + exportOwnKey: vi.fn(async () => { + throw new PgpKeyringError('locked'); }), unlockOwnKey: vi.fn(async () => { - throw new PgpKeyError('Wrong passphrase', 'bad-passphrase'); + throw new PgpKeyError('bad-passphrase'); }), listOwnKeys: vi.fn(async () => { throw new Error('db closed'); }), }); const { handlers } = setup({ keyring }); - expect(await handlers['pgp:importOwnKey']('ARMOR')).toEqual({ - success: false, - error: 'This key needs its passphrase', - code: 'passphrase-required', + expect(await handlers['pgp:importOwnKey']('ARMOR')).toEqual({ ...FAILED, code: 'passphrase-required' }); + expect(await handlers['pgp:exportOwnKey']('F'.repeat(40), 'backup pass')).toEqual({ ...FAILED, code: 'locked' }); + expect(await handlers['pgp:unlock']('FP', 'nope')).toEqual(FAILED); + expect(await handlers['pgp:listOwnKeys']()).toEqual(FAILED); + // Argument validation reads the same. + expect(await handlers['pgp:unlock']('FP', '')).toEqual(FAILED); + expect(await handlers['pgp:importOwnKey']('')).toEqual(FAILED); + vi.restoreAllMocks(); + }); + + // Breaks (CASA 4.1.4): a key operation's answer varies with the cause — the + // checklist the assessor named: an unreadable key, a wrong passphrase, a + // public key imported as private, a keychain that is missing or refuses, an + // unknown envelope, a missing key, a decryption failure, a missing argument, + // a non-Error throw. Every one must read the same, with no code. + it.each([ + ['an unreadable key', () => new PgpKeyError('bad-key')], + ['a wrong passphrase', () => new PgpKeyError('bad-passphrase')], + ['a public key imported as private', () => new PgpKeyError('not-private')], + ['no keychain', () => new SealError('keychain-unavailable')], + ['an unknown envelope', () => new SealError('unknown-format')], + ['a key that is not there', () => new PgpKeyringError('not-found')], + ['a decryption failure', () => new PgpOpenError('bad-data')], + ['no matching key', () => new PgpOpenError('no-key')], + ['a plain Error', () => new Error('db closed')], + ['a non-Error throw', () => 'boom'], + ])('answers %s with the one sentence and no code', async (_name, failure) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const f = setup({ + keyring: keyringStub({ + importOwnKey: vi.fn(async () => { throw failure(); }), + unlockOwnKey: vi.fn(async () => { throw failure(); }), + exportOwnKey: vi.fn(async () => { throw failure(); }), + generateOwnKey: vi.fn(async () => { throw failure(); }), + deleteOwnKey: vi.fn(() => { throw failure(); }), + importContactKeys: vi.fn(async () => { throw failure(); }), + }), }); - expect(await handlers['pgp:unlock']('FP', 'nope')).toMatchObject({ success: false, code: 'bad-passphrase' }); - // Changed deliberately (CASA 4.1.4): an error that is not one of ours no longer reaches the renderer in its own words. - expect(await handlers['pgp:listOwnKeys']()).toEqual({ success: false, error: PGP_REQUEST_FAILED_MESSAGE }); - expect(await handlers['pgp:unlock']('FP', '')).toMatchObject({ success: false, error: 'A passphrase is required' }); - expect(await handlers['pgp:importOwnKey']('')).toMatchObject({ success: false, error: 'A key is required' }); + expect(await f.handlers['pgp:importOwnKey']('ARMOR', 'pw')).toEqual(FAILED); + expect(await f.handlers['pgp:unlock']('FP', 'pw')).toEqual(FAILED); + expect(await f.handlers['pgp:exportOwnKey']('F'.repeat(40), 'backup pass')).toEqual(FAILED); + expect(await f.handlers['pgp:generateKey']({ email: 'rita@example.com' })).toEqual(FAILED); + expect(await f.handlers['pgp:deleteOwnKey']('FP')).toEqual(FAILED); + expect(await f.handlers['pgp:importContactKeys']('ARMOR')).toEqual(FAILED); + expect(f.writeFile).not.toHaveBeenCalled(); + vi.restoreAllMocks(); }); - // Breaks (CASA 4.1.4): importing a broken key file shows openpgp.js's own - // reason, which varies with how the file is broken — the dialog must show - // one sentence, and the reason must still reach the local log. - it('answers an unreadable key import in our words and logs the library reason', async () => { + // Changed deliberately (CASA 4.1.4): an unreadable import used to answer its own sentence with code + // 'bad-key', and the log carried the library's reason. + // Breaks: importing a broken key file shows openpgp.js's own reason, which + // varies with how the file is broken, or writes it to app.log. + it('answers an unreadable key import with the one sentence and logs only class and code', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { const keyring = keyringStub({ importContactKeys: vi.fn((armored: string) => readAllKeys(armored)) }); const { handlers } = setup({ keyring }); - expect(await handlers['pgp:importContactKeys']('-----BEGIN PGP PUBLIC KEY BLOCK-----\njunk')).toEqual({ - success: false, - error: PGP_UNREADABLE_KEY_MESSAGE, - code: 'bad-key', - }); - expect(warn.mock.calls.map((call) => call.join(' '))).toEqual([expect.stringMatching(/OpenPGP request failed: .+/)]); - // A refusal of our own with no library reason writes nothing. - warn.mockClear(); - const refusing = setup({ keyring: keyringStub({ unlockOwnKey: vi.fn(async () => { throw new PgpKeyError('Wrong passphrase', 'bad-passphrase'); }) }) }); - await refusing.handlers['pgp:unlock']('FP', 'nope'); - expect(warn).not.toHaveBeenCalled(); + expect(await handlers['pgp:importContactKeys']('-----BEGIN PGP PUBLIC KEY BLOCK-----\njunk')).toEqual(FAILED); + expect(warnLines(warn)).toEqual([expect.stringMatching(/OpenPGP request failed \{ name: 'PgpKeyError', code: 'bad-key' \}$/)]); } finally { warn.mockRestore(); } }); - // Breaks (CASA 4.1.4): openpgp.js's own text — which differs with how a - // user-supplied key, a generation or a backup re-protection failed — reaches - // the settings dialog. The renderer reads one sentence; the log the reason. + // Changed deliberately (CASA 4.1.4): the log used to carry openpgp.js's text. + // Breaks: openpgp.js's own text — which differs with how a user-supplied + // key, a generation or a backup re-protection failed — reaches the settings + // dialog or app.log. The renderer reads one sentence; the log the class. it.each([ ['pgp:importOwnKey', ['-----BEGIN PGP PRIVATE KEY BLOCK-----'], 'importOwnKey'], ['pgp:generateKey', [{ name: 'Rita', email: 'rita@example.com' }], 'generateOwnKey'], ['pgp:exportOwnKey', ['F'.repeat(40), 'backup pass'], 'exportOwnKey'], - ] as const)('%s answers a library failure with one sentence and logs the library reason', async (channel, args, method) => { + ] as const)('%s answers a library failure with one sentence and logs no library text', async (channel, args, method) => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { // A real openpgp.js error, as a broken key file produces it. @@ -173,27 +222,46 @@ describe('key management', () => { expect(libraryError).toBeInstanceOf(Error); const f = setup({ keyring: keyringStub({ [method]: vi.fn(async () => { throw libraryError; }) }) }); - expect(await (f.handlers[channel] as (...a: unknown[]) => Promise)(...args)).toEqual({ - success: false, - error: PGP_REQUEST_FAILED_MESSAGE, - }); + expect(await (f.handlers[channel] as (...a: unknown[]) => Promise)(...args)).toEqual(FAILED); expect(f.writeFile).not.toHaveBeenCalled(); - expect(warn.mock.calls.map((call) => call.join(' '))).toEqual([ - expect.stringContaining(`OpenPGP request failed: ${(libraryError as Error).message}`), - ]); + expect(warnLines(warn)).toEqual([expect.stringMatching(/OpenPGP request failed \{ name: 'Error' \}$/)]); + expect(warnLines(warn).join('\n')).not.toContain((libraryError as Error).message); } finally { warn.mockRestore(); } }); - // Breaks: "unlock the keychain" — the one failure the user can fix — is - // flattened into the vague OpenPGP sentence when a backup or an import - // reaches a key the OS keychain will not open. - it('keeps a keychain refusal in its own words', async () => { - const refusal = new SealError(KEYCHAIN_REFUSED_MESSAGE, 'keychain-unavailable'); - const f = setup({ keyring: keyringStub({ exportOwnKey: vi.fn(async () => { throw refusal; }), unlockOwnKey: vi.fn(async () => { throw refusal; }) }) }); - expect(await f.handlers['pgp:exportOwnKey']('F'.repeat(40), 'backup pass')).toEqual({ success: false, error: KEYCHAIN_REFUSED_MESSAGE }); - expect(await f.handlers['pgp:unlock']('FP', 'pass')).toEqual({ success: false, error: KEYCHAIN_REFUSED_MESSAGE }); + // Breaks (CASA 4.1.4): a failure's message reaches app.log — a crafted + // library message, an address in a keyring error (one used to say "The key + // for
is locked"), a path in a write error. The sentinel never may. + it('writes no failure message to the log', async () => { + const SENTINEL = 'sentinel-handlers@example.org'; + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const crafted = Object.assign(new Error(`Error decrypting private key: ${SENTINEL}`), { code: 'ERR_CRAFTED' }); + const withAddress = Object.assign(new PgpKeyringError('locked'), { message: `The key for ${SENTINEL} is locked` }); + const f = setup({ + attachment: { name: 'plan.pdf', content: Buffer.from('pdf') }, + keyring: keyringStub({ + importOwnKey: vi.fn(async () => { throw crafted; }), + exportOwnKey: vi.fn(async () => { throw withAddress; }), + }), + }); + f.writeFile.mockRejectedValueOnce(Object.assign(new Error(`EACCES: permission denied, open '/Users/${SENTINEL}/plan.pdf'`), { code: 'EACCES' })); + + expect(await f.handlers['pgp:importOwnKey']('ARMOR')).toEqual(FAILED); + expect(await f.handlers['pgp:exportOwnKey']('F'.repeat(40), 'backup pass')).toEqual({ ...FAILED, code: 'locked' }); + expect(await f.handlers['pgp:saveAttachment']('e1', 'acct', 0)).toMatchObject({ success: false }); + + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.lines).toEqual([ + expect.stringContaining("OpenPGP request failed { name: 'Error', code: 'ERR_CRAFTED' }"), + expect.stringContaining("OpenPGP request failed { name: 'PgpKeyringError', code: 'locked' }"), + expect.stringContaining("OpenPGP attachment save failed { name: 'Error', code: 'EACCES' }"), + ]); + } finally { + logs.stop(); + } }); // Breaks: a backup to a folder the user cannot write to reads as an OpenPGP @@ -274,6 +342,27 @@ describe('key management', () => { }); describe('compose', () => { + // Breaks: the composer's unlock prompt closes because SOME key opened while + // the one its From address needs is still locked (the send is refused again, + // in a loop) — or stays up after that key was unlocked elsewhere. And (CASA + // 4.1.4) only `locked` is answered: every other cause reads as not locked. + it('says whether the key for the From address is still locked, and nothing else', async () => { + const signingKeyFor = vi.fn(async (_email: string): Promise => ({})); + const { handlers } = setup({ keyring: keyringStub({ signingKeyFor }) }); + expect(await handlers['pgp:signingKeyLocked']('Me ')).toEqual({ success: true, data: false }); + expect(signingKeyFor).toHaveBeenLastCalledWith('me@example.org'); + signingKeyFor.mockRejectedValueOnce(new PgpKeyringError('locked')); + expect(await handlers['pgp:signingKeyLocked']('me@example.org')).toEqual({ success: true, data: true }); + for (const cause of [new PgpKeyringError('not-found'), new SealError('keychain-unavailable'), new PgpKeyError('bad-key'), new Error('db closed')]) { + signingKeyFor.mockRejectedValueOnce(cause); + expect(await handlers['pgp:signingKeyLocked']('me@example.org')).toEqual({ success: true, data: false }); + } + // Nothing to ask about without an address. + signingKeyFor.mockClear(); + expect(await handlers['pgp:signingKeyLocked'](undefined as never)).toEqual({ success: true, data: false }); + expect(signingKeyFor).not.toHaveBeenCalled(); + }); + // Breaks: compose looks up nothing, or chokes on a non-address from the renderer. it('resolves only string recipients, discovering as the settings allow', async () => { const { handlers, keyring } = setup(); @@ -305,7 +394,8 @@ describe('reading', () => { const { handlers, reader } = setup(); expect(await handlers['pgp:open']('e1', 'acct')).toEqual({ ok: true }); expect(reader.open).toHaveBeenCalledWith('e1', 'acct'); - expect(await handlers['pgp:open']('')).toMatchObject({ ok: false, code: 'unavailable' }); + // Changed deliberately (CASA 4.1.4): a missing id used to answer `unavailable` with "No message". + expect(await handlers['pgp:open']('')).toEqual({ ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE }); }); // Breaks: an encrypted draft cannot be reopened into the composer, or is asked for with no id. @@ -313,7 +403,7 @@ describe('reading', () => { const { handlers, reader } = setup(); expect(await handlers['pgp:openDraft']('d1', 'acct')).toEqual({ ok: true, attachments: [] }); expect(reader.openDraft).toHaveBeenCalledWith('d1', 'acct'); - expect(await handlers['pgp:openDraft'](undefined as unknown as string)).toMatchObject({ ok: false, code: 'unavailable' }); + expect(await handlers['pgp:openDraft'](undefined as unknown as string)).toEqual({ ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE }); expect(reader.openDraft).toHaveBeenCalledTimes(1); }); @@ -538,8 +628,9 @@ describe('registerPgpHandlers', () => { h.keyring = keyringStub({ ownPublicKeyFor: vi.fn(async () => null) }); registerPgpHandlers(); const invoke = (channel: string, ...args: unknown[]) => h.channels.get(channel)!(null, ...args); - expect([...h.channels.keys()]).toEqual(expect.arrayContaining(['pgp:open', 'pgp:openDraft', 'pgp:saveAttachment', 'pgp:exportOwnKey'])); - expect(h.channels.size).toBe(17); + expect([...h.channels.keys()]).toEqual(expect.arrayContaining(['pgp:open', 'pgp:openDraft', 'pgp:saveAttachment', 'pgp:exportOwnKey', 'pgp:signingKeyLocked'])); + // One more than before: pgp:signingKeyLocked, the composer's unlock re-check. + expect(h.channels.size).toBe(18); // No window: the dialog is shown unparented. Cancelling writes nothing. h.showSaveDialog.mockResolvedValueOnce({ canceled: true }); diff --git a/apps/desktop/test/unit/electron/ipc/smtp-pgp-locked-send.test.ts b/apps/desktop/test/unit/electron/ipc/smtp-pgp-locked-send.test.ts new file mode 100644 index 00000000..eea95ad3 --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/smtp-pgp-locked-send.test.ts @@ -0,0 +1,129 @@ +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: a send that must be signed with a key still +// locked this session is queued anyway, and fails only after the undo window, +// when the composer that could ask for the passphrase is gone. Or (CASA 4.1.4) +// the composer is handed a code for a cause other than a locked key. +// +// The handlers and the locked-key check (pgp-failure) are REAL; the keyring, +// the outbox and the module's other edges are faked. + +const h = vi.hoisted(() => ({ + handlers: new Map unknown>(), + signingKeyFor: vi.fn(async (_email: string): Promise => ({})), + enqueueHeld: vi.fn(async () => ({ id: 41 })), + scheduleSend: vi.fn(async () => ({ id: 42 })), + smtpClient: null as unknown, + smtpClientFor: null as unknown, +})); + +vi.mock('electron', () => ({ + ipcMain: { handle: (name: string, fn: (...a: unknown[]) => unknown) => h.handlers.set(name, fn) }, + dialog: {}, + app: { getPath: () => '/tmp', getName: () => 'Sarv Inbox Test', isPackaged: false }, + safeStorage: {}, +})); +vi.mock('@sarvinbox/core', async (orig) => ({ + ...(await orig()), + createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }), +})); +vi.mock('../../../../electron/services/core-db', async () => await import('../../../../electron/services/__testing__/fake-core-db')); +vi.mock('../../../../electron/services/accounts-registry', () => ({ + readRegistryAccounts: () => [], + registryAccountEmail: (id: string | null | undefined) => ({ 'acct-1': 'me@example.org', 'acct-2': 'sales@example.org' })[id ?? ''] ?? '', +})); +vi.mock('../../../../electron/shared', () => ({ + getStorage: vi.fn(() => null), + getStorageFor: vi.fn(), + getSyncEngine: vi.fn(() => null), + getSyncEngineFor: vi.fn(), + getSmtpClient: () => h.smtpClient, + getSmtpClientFor: () => h.smtpClientFor, + setSmtpClient: vi.fn(), + setSmtpClientFor: vi.fn(), + getMainWindow: vi.fn(), + getCurrentAccountId: vi.fn(() => 'acct-1'), +})); +vi.mock('../../../../electron/services/oauth-service', () => ({ getValidAccessToken: vi.fn(async () => 'tok') })); +vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ getPipelineUserName: vi.fn(() => 'Me') })); +vi.mock('../../../../electron/services/outbox-service', () => { + const queue = { enqueueHeld: h.enqueueHeld, scheduleSend: h.scheduleSend }; + return { + getOutboxQueue: vi.fn(() => queue), + drainOutbox: vi.fn(async () => {}), + getOutboxQueueForAccount: vi.fn(() => queue), + drainOutboxForAccount: vi.fn(async () => {}), + notifyOutboxChanged: vi.fn(), + }; +}); +vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(async () => {}) })); +vi.mock('../../../../electron/services/pgp-service', () => ({ sendTransformFor: vi.fn(), getPgpKeyring: () => ({ signingKeyFor: h.signingKeyFor }) })); +vi.mock('../../../../electron/ipc/follow-up-handlers', () => ({ recordFollowUpForSend: vi.fn() })); + +import { registerSmtpHandlers } from '../../../../electron/ipc/smtp-handlers'; +import { PgpKeyringError } from '../../../../electron/services/pgp-keyring'; + +const SIGNED = { to: ['bob@example.org'], subject: 'Hi', body: 'hello', pgp: { encrypt: true, sign: true } }; +const LOCKED = { success: false, error: PGP_FAILURE_MESSAGE, code: 'locked' }; + +beforeEach(() => { + vi.clearAllMocks(); + h.handlers.clear(); + h.signingKeyFor.mockResolvedValue({}); + h.smtpClient = { getConfig: () => ({ username: 'me@example.org', from: 'Me ' }) }; + h.smtpClientFor = { getConfig: () => ({ username: 'sales@example.org' }) }; + registerSmtpHandlers(); +}); + +describe('a send that must be signed with a locked key', () => { + // Breaks: the send is queued and fails after the undo window instead of the composer asking for the passphrase. + it('is refused with the locked code before anything is queued, by undo-send and by send-later', async () => { + h.signingKeyFor.mockRejectedValue(new PgpKeyringError('locked')); + expect(await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000)).toEqual(LOCKED); + expect(await h.handlers.get('smtp:scheduleSend')!(null, SIGNED, 1_800_000_000)).toEqual(LOCKED); + expect(h.enqueueHeld).not.toHaveBeenCalled(); + expect(h.scheduleSend).not.toHaveBeenCalled(); + }); + + // Breaks: the check asks about another address than the one the send will + // write — the alias, then the account's SMTP identity — or, before that + // client is connected (no config yet, a failed verify, a swallowed connect + // error), asks about nothing and lets the locked send be queued. + it('asks about the From address the send will write, falling back to the account\'s', async () => { + await h.handlers.get('smtp:sendWithUndo')!(null, { ...SIGNED, from: 'Alias ' }, 5000); + await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000); + await h.handlers.get('smtp:scheduleSend')!(null, { ...SIGNED, accountId: 'acct-2' }, 1_800_000_000); + h.smtpClient = null; + h.smtpClientFor = { getConfig: () => null }; + await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000); + await h.handlers.get('smtp:sendWithUndo')!(null, { ...SIGNED, accountId: 'acct-2' }, 5000); + expect(h.signingKeyFor.mock.calls).toEqual([ + ['alias@example.org'], + ['me@example.org'], + ['sales@example.org'], + ['me@example.org'], + ['sales@example.org'], + ]); + }); + + // Breaks: with no SMTP config yet, a locked send is queued (and dead-lettered later) instead of refused. + it('refuses a locked send before the SMTP client has a config', async () => { + h.smtpClient = { getConfig: () => null }; + h.signingKeyFor.mockRejectedValue(new PgpKeyringError('locked')); + expect(await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000)).toEqual(LOCKED); + expect(h.enqueueHeld).not.toHaveBeenCalled(); + }); + + // Breaks (CASA 4.1.4): an unlocked (or unsigned) send is held back, or a + // cause other than a locked key reaches the composer as a code. + it('queues every other send as before, with no code', async () => { + h.signingKeyFor.mockRejectedValueOnce(new PgpKeyringError('not-found')); + expect(await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000)).toEqual({ success: true, id: 41 }); + h.enqueueHeld.mockClear(); + expect(await h.handlers.get('smtp:sendWithUndo')!(null, SIGNED, 5000)).toEqual({ success: true, id: 41 }); + expect(await h.handlers.get('smtp:scheduleSend')!(null, SIGNED, 1_800_000_000)).toEqual({ success: true, id: 42 }); + expect(h.enqueueHeld).toHaveBeenCalledOnce(); + expect(h.scheduleSend).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/pgp-failure.test.ts b/apps/desktop/test/unit/electron/services/pgp-failure.test.ts new file mode 100644 index 00000000..4fb8e270 --- /dev/null +++ b/apps/desktop/test/unit/electron/services/pgp-failure.test.ts @@ -0,0 +1,106 @@ +import { createLogger, getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { PgpKeyError, PgpOpenError } from '@sarvinbox/core/pgp'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('electron', () => ({ safeStorage: {} })); + +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { lockedSigningKeyFor, logPgpFailure, pgpFlowCode } from '../../../../electron/services/pgp-failure'; +import { PgpKeyringError, type PgpKeyring } from '../../../../electron/services/pgp-keyring'; +import { SealError } from '../../../../electron/services/pgp-secret-seal'; + +/** + * How main handles an OpenPGP failure (CASA 4.1.4). What this protects: an + * error's message reaching app.log; a cause other than the two prompts + * becoming a code the renderer can tell apart; and the locked-signing-key + * check that lets the composer ask for a passphrase before a send is queued. + */ + +describe('logPgpFailure', () => { + // Breaks: a library message, an address or a path in an error reaches app.log. + it('writes the context, then class and code, and never the message', () => { + const SENTINEL = 'sentinel-failure@example.org'; + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const logger = createLogger('pgp-test'); + logPgpFailure(logger, 'Could not open', Object.assign(new PgpKeyringError('locked'), { message: `The key for ${SENTINEL} is locked` })); + logPgpFailure(logger, 'Could not sign', new TypeError(`Session key decryption failed for ${SENTINEL}`)); + expect(logs.lines).toEqual([ + "[WARN] [pgp-test] Could not open { name: 'PgpKeyringError', code: 'locked' }", + "[WARN] [pgp-test] Could not sign { name: 'TypeError' }", + ]); + expect(logs.containing(SENTINEL)).toEqual([]); + } finally { + logs.stop(); + } + }); +}); + +describe('pgpFlowCode', () => { + // Breaks: the renderer can no longer offer the unlock or passphrase prompt — or can tell any other cause apart. + it('names only the two prompts', () => { + expect(pgpFlowCode(new PgpOpenError('locked'))).toBe('locked'); + expect(pgpFlowCode(new PgpKeyringError('locked'))).toBe('locked'); + expect(pgpFlowCode(new PgpKeyringError('passphrase-required'))).toBe('passphrase-required'); + for (const error of [ + new PgpOpenError('no-key'), + new PgpOpenError('bad-data'), + new PgpKeyringError('not-found'), + new PgpKeyError('bad-passphrase'), + new SealError('keychain-unavailable'), + Object.assign(new Error('x'), { code: 'locked' }), + 'locked', + ]) { + expect(pgpFlowCode(error)).toBeUndefined(); + } + }); +}); + +describe('lockedSigningKeyFor', () => { + const SIGN = { encrypt: false, sign: true }; + const ringThat = (signingKeyFor: (email: string) => Promise) => { + const spy = vi.fn(signingKeyFor); + return { spy, keyring: () => ({ signingKeyFor: spy }) as unknown as PgpKeyring }; + }; + + // Breaks: a send signed with a key locked this session is queued anyway and + // fails after the undo window, when the composer is gone and cannot offer + // the passphrase prompt. + it('answers locked for a signed send whose key is locked, asking about the From address', async () => { + const ring = ringThat(async () => { throw new PgpKeyringError('locked'); }); + expect(await lockedSigningKeyFor({ encrypt: true, sign: true }, 'Me ', ring.keyring)).toBe('locked'); + // The address as the send writes it; the keyring normalizes it (as for the send itself). + expect(ring.spy).toHaveBeenCalledWith('Me@Example.org'); + }); + + // Breaks: an unsigned send asks the keyring for a private key it does not + // need — unsealing it through the keychain for nothing. (The send handler + // always supplies an address — the alias, the SMTP identity or the + // account's — so an empty one is only a guard here.) + it('does not ask about a send that is not signed, or an empty address', async () => { + const ring = ringThat(async () => { throw new PgpKeyringError('locked'); }); + expect(await lockedSigningKeyFor(undefined, 'me@example.org', ring.keyring)).toBeNull(); + expect(await lockedSigningKeyFor({ encrypt: true, sign: false }, 'me@example.org', ring.keyring)).toBeNull(); + expect(await lockedSigningKeyFor(SIGN, '', ring.keyring)).toBeNull(); + expect(ring.spy).not.toHaveBeenCalled(); + }); + + // Breaks (CASA 4.1.4): a cause other than a locked key becomes a code the + // composer can tell apart, or blocks the send here with nothing to act on. + // Those are the send's to fail, with the one sentence. + it.each([ + ['a usable key', async () => ({})], + ['no key for the address', async () => null], + ['a missing key', async () => { throw new PgpKeyringError('not-found'); }], + ['a keychain that will not open', async () => { throw new SealError('keychain-unavailable'); }], + ['an unreadable key', async () => { throw new PgpKeyError('bad-key'); }], + ['an unreadable keyring', async () => { throw new Error('db closed'); }], + ])('answers null for %s', async (_name, signingKeyFor) => { + expect(await lockedSigningKeyFor(SIGN, 'me@example.org', ringThat(signingKeyFor).keyring)).toBeNull(); + }); + + // Breaks: a keyring that cannot even be built throws into the send handler instead of letting the send decide. + it('answers null when the keyring cannot be opened', async () => { + expect(await lockedSigningKeyFor(SIGN, 'me@example.org', () => { throw new Error('core DB not open'); })).toBeNull(); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/pgp-keyring.test.ts b/apps/desktop/test/unit/electron/services/pgp-keyring.test.ts index 75fe7c37..5587da18 100644 --- a/apps/desktop/test/unit/electron/services/pgp-keyring.test.ts +++ b/apps/desktop/test/unit/electron/services/pgp-keyring.test.ts @@ -1,8 +1,12 @@ -import { OutgoingMimeError } from '@sarvinbox/core'; +import { inspect } from 'node:util'; + +import { OutgoingMimeError, getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; import { buildAutocryptHeader, encryptOutgoingMime, generateKeyPair, + PGP_FAILURE_MESSAGE, + PGP_UNLOCK_THEN_RETRY_MESSAGE, inspectKey, protectPrivateKey, readAnyKey, @@ -19,6 +23,7 @@ vi.mock('../../../../electron/services/core-db', () => ({ }, })); +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; import type { KeyLookupResult } from '../../../../electron/services/pgp-key-lookup'; import { PgpKeyStore } from '../../../../electron/services/pgp-key-store'; import { @@ -29,7 +34,7 @@ import { } from '../../../../electron/services/pgp-keyring'; import { pgpOutgoingTransform } from '../../../../electron/services/pgp-outgoing'; import { PgpReader } from '../../../../electron/services/pgp-reader'; -import { KEYCHAIN_REFUSED_MESSAGE, type Keychain } from '../../../../electron/services/pgp-secret-seal'; +import type { Keychain } from '../../../../electron/services/pgp-secret-seal'; /** * The keyring's decisions. What this protects: a private key stored in the @@ -382,11 +387,15 @@ describe('a keychain that is there but refuses to decrypt', () => { // A fresh keyring: the first one still holds the key it just generated, opened. return { keyring: new PgpKeyring({ ...first.deps, keychain }), own: (await first.keyring.ownPublicKeyFor('me@example.org'))! }; }; - const warnLines = (warn: { mock: { calls: unknown[][] } }) => warn.mock.calls.map((call) => call.map(String).join(' ')); - - // Breaks: an encrypted message reads "The message could not be opened. Try - // again." — retrying never helps; unlocking or allowing the keychain does. - it('the reader shows the keychain message, and the log names only the error class', async () => { + // As app.log prints them: objects through util.inspect. + const warnLines = (warn: { mock: { calls: unknown[][] } }) => + warn.mock.calls.map((call) => call.map((arg) => (typeof arg === 'string' ? arg : inspect(arg))).join(' ')); + + // Changed deliberately (CASA 4.1.4): the reader used to show a keychain + // sentence of its own here. + // Breaks: a keychain refusal reads differently from any other OpenPGP + // failure, or safeStorage's text reaches the log. + it('the reader shows the one sentence, and the log names only class and code', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const { keyring, own } = await refusingKeyring(); const raw = Buffer.concat([ @@ -395,15 +404,18 @@ describe('a keychain that is there but refuses to decrypt', () => { ]).toString('latin1'); const reader = new PgpReader({ keyring: () => keyring, source: async () => ({ raw, fromAddress: 'bob@example.org' }) }); - expect(await reader.open('e1')).toEqual({ ok: false, code: 'unavailable', error: KEYCHAIN_REFUSED_MESSAGE }); - expect(warnLines(warn)).toEqual([expect.stringContaining('(Error)')]); + expect(await reader.open('e1')).toEqual({ ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE }); + expect(warnLines(warn)).toEqual([ + expect.stringContaining('(Error)'), + expect.stringMatching(/Could not open OpenPGP message e1 .*SealError.*keychain-unavailable/), + ]); expect(warnLines(warn).join('\n')).not.toContain('safeStorage'); }); - // Breaks: a signed send fails with "Could not sign the message: the OpenPGP - // operation failed", hiding the keychain as the cause — or, worse, is retried - // as transient and goes out unsigned. - it('a signed send fails permanently with the keychain message', async () => { + // Changed deliberately (CASA 4.1.4): the send used to fail with "Could not sign the message: ". + // Breaks: a signed send hides nothing less than any other failure — or, worse, + // is retried as transient and goes out unsigned. + it('a signed send fails permanently with the one sentence', async () => { vi.spyOn(console, 'warn').mockImplementation(() => undefined); const { keyring } = await refusingKeyring(); const transform = pgpOutgoingTransform(keyring, { request: { encrypt: false, sign: true }, preferEncrypt: false }); @@ -414,6 +426,62 @@ describe('a keychain that is there but refuses to decrypt', () => { }).catch((e) => e); expect(error).toBeInstanceOf(OutgoingMimeError); - expect(error).toMatchObject({ transient: false, message: `Could not sign the message: ${KEYCHAIN_REFUSED_MESSAGE}` }); + expect(error).toMatchObject({ transient: false, message: PGP_FAILURE_MESSAGE }); + }); +}); + +// Every refusal of the real keyring, through the real errors it throws. +describe('keyring refusals (CASA 4.1.4)', () => { + afterEach(() => vi.restoreAllMocks()); + + // Breaks: a refusal reads differently from another (a sentence naming the + // cause), or names a key or an address — the locked-key refusal used to say + // "The key for
is locked". + it('every refusal carries the one sentence and its code, and no address', async () => { + const withKeychain = setup(); + const noKeychain = setup({ keychain: false }); + const locked = await protectPrivateKey(bob.armoredPrivateKey, 'secret'); + const generated = await noKeychain.keyring.generateOwnKey({ name: 'Me', email: 'me@example.org', passphrase: 'pw' }); + const nextSession = new PgpKeyring(noKeychain.deps); + const refusals: Array<[() => Promise, string]> = [ + [() => noKeychain.keyring.generateOwnKey({ name: 'Me', email: 'me@example.org' }), 'passphrase-required'], + [() => withKeychain.keyring.importOwnKey(locked), 'passphrase-required'], + [() => noKeychain.keyring.importOwnKey(carol.armoredPrivateKey), 'passphrase-required'], + [() => withKeychain.keyring.exportOwnKey(generated.fingerprint, ''), 'passphrase-required'], + [() => withKeychain.keyring.unlockOwnKey('NOPE', 'x'), 'not-found'], + [() => nextSession.exportOwnKey(generated.fingerprint, 'backup'), 'locked'], + [() => nextSession.signingKeyFor('me@example.org'), 'locked'], + [() => nextSession.unlockOwnKey(generated.fingerprint, 'wrong'), 'bad-passphrase'], + [() => withKeychain.keyring.importOwnKey(locked, 'wrong'), 'bad-passphrase'], + [() => withKeychain.keyring.importOwnKey(bob.armoredPublicKey), 'not-private'], + [() => withKeychain.keyring.importOwnKey('-----BEGIN PGP PRIVATE KEY BLOCK-----\njunk'), 'bad-key'], + [() => withKeychain.keyring.importContactKeys('-----BEGIN PGP PUBLIC KEY BLOCK-----\njunk'), 'bad-key'], + ]; + for (const [refusal, code] of refusals) { + const error = (await refusal().catch((e) => e)) as Error & { code: string }; + expect(error).toBeInstanceOf(Error); + expect({ code: error.code, message: error.message }).toEqual({ code, message: PGP_FAILURE_MESSAGE }); + expect(String(error.stack)).not.toMatch(/@example\.org/); + } + }); + + // Breaks: the address of a locked key (or a library message) reaches app.log through a send that needed it. + it('a send that needs a locked key logs neither the address nor any sentence', async () => { + const { deps, keyring } = setup({ keychain: false }); + await keyring.generateOwnKey({ name: 'Me', email: 'sentinel-locked@example.org', passphrase: 'pw' }); + const transform = pgpOutgoingTransform(new PgpKeyring(deps), { request: { encrypt: false, sign: true }, preferEncrypt: false }); + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const error = await transform(Buffer.from('From: sentinel-locked@example.org\r\nSubject: hi\r\n\r\nhello\r\n'), { + fromHeader: 'Me ', + recipients: ['bob@example.org'], + }).catch((e) => e); + // The fixed "unlock, then retry" text and the `locked` code; still no address. + expect(error).toMatchObject({ transient: false, message: PGP_UNLOCK_THEN_RETRY_MESSAGE, code: 'locked' }); + expect(logs.containing('sentinel-locked')).toEqual([]); + expect(logs.containing("Could not sign an outgoing message { name: 'PgpKeyringError', code: 'locked' }")).toHaveLength(1); + } finally { + logs.stop(); + } }); }); diff --git a/apps/desktop/test/unit/electron/services/pgp-outgoing.test.ts b/apps/desktop/test/unit/electron/services/pgp-outgoing.test.ts index e6615478..6d53d47e 100644 --- a/apps/desktop/test/unit/electron/services/pgp-outgoing.test.ts +++ b/apps/desktop/test/unit/electron/services/pgp-outgoing.test.ts @@ -1,8 +1,12 @@ -import { OutgoingMimeError, isTransientSendError } from '@sarvinbox/core'; +import { inspect } from 'node:util'; + +import { OutgoingMimeError, failureCause, getLogLevel, isTransientSendError, setLogLevel, setLogSink } from '@sarvinbox/core'; import { detectPgpMime, generateKeyPair, openPgpMime, + PGP_FAILURE_MESSAGE, + PGP_UNLOCK_THEN_RETRY_MESSAGE, parseAutocryptHeader, readAnyKey, readUnlockedPrivateKey, @@ -13,13 +17,9 @@ import MailComposer from 'nodemailer/lib/mail-composer'; import * as openpgp from 'openpgp'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; import { PgpKeyringError } from '../../../../electron/services/pgp-keyring'; -import { - encryptDraftMime, - PGP_OPERATION_FAILED_REASON, - pgpOutgoingTransform, - type OutgoingKeyring, -} from '../../../../electron/services/pgp-outgoing'; +import { encryptDraftMime, pgpOutgoingTransform, type OutgoingKeyring } from '../../../../electron/services/pgp-outgoing'; vi.mock('electron', () => ({ safeStorage: {} })); @@ -125,51 +125,110 @@ describe('pgpOutgoingTransform', () => { expect((await openPgpMime(out, await keysFor(bob))).signature.status).toBe('valid'); }); + // Changed deliberately (CASA 4.1.4): this refusal used to name the recipients without a key + // (the composer names them before the send instead). // Breaks: an encrypted send to a keyless recipient went out in plaintext, or the outbox retried it forever. it('refuses to encrypt when a recipient has no key, permanently', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const transform = pgpOutgoingTransform(fakeKeyring(), { request: { encrypt: true, sign: false }, preferEncrypt: true }); const error = await transform(raw, context(['bob@example.org', 'Carol '])).catch((e) => e); expect(error).toBeInstanceOf(OutgoingMimeError); - expect(error.message).toContain('carol@example.org'); - expect(error.message).not.toContain('bob@'); + expect(error.message).toBe(PGP_FAILURE_MESSAGE); expect(isTransientSendError(error)).toBe(false); }); - // Breaks: a send that asked to be signed went out unsigned. + // Changed deliberately (CASA 4.1.4): these refusals used to say "No OpenPGP key for
" and + // "Could not encrypt the message: … locked"; a locked key now says what to do, with its code. + // Breaks: a send that asked to be signed went out unsigned, or was retried + // automatically — or a queued send that met a locked key dead-ends in the + // Outbox with nothing saying the fix is to unlock it and retry. it('refuses to sign without a key or with a locked one', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const noKey = pgpOutgoingTransform(fakeKeyring({ signingKeyFor: async () => null }), { request: { encrypt: false, sign: true }, preferEncrypt: false, }); - await expect(noKey(raw, context())).rejects.toThrow(/No OpenPGP key for me@example.org/); + await expect(noKey(raw, context())).rejects.toMatchObject({ transient: false, message: PGP_FAILURE_MESSAGE, code: undefined }); const locked = pgpOutgoingTransform( - fakeKeyring({ signingKeyFor: async () => { throw new PgpKeyringError('The key for me@example.org is locked', 'locked'); } }), + fakeKeyring({ signingKeyFor: async () => { throw new PgpKeyringError('locked'); } }), { request: { encrypt: true, sign: true }, preferEncrypt: false }, ); const error = await locked(raw, context()).catch((e) => e); expect(error).toBeInstanceOf(OutgoingMimeError); - expect(error.message).toMatch(/Could not encrypt the message: .*locked/); - expect(error.transient).toBe(false); + expect(error).toMatchObject({ transient: false, message: PGP_UNLOCK_THEN_RETRY_MESSAGE, code: 'locked' }); + // The send result's failure kind, and so the Outbox log line, says `locked`. + expect(failureCause(error)).toBe('locked'); const noFrom = pgpOutgoingTransform(fakeKeyring({ signingKeyFor: async () => null }), { request: { encrypt: false, sign: true }, preferEncrypt: false, }); - await expect(noFrom(raw, { fromHeader: '', recipients: [] })).rejects.toThrow(/this sender/); + await expect(noFrom(raw, { fromHeader: '', recipients: [] })).rejects.toMatchObject({ message: PGP_FAILURE_MESSAGE }); }); + // Breaks: Retry from the Outbox after the key was unlocked still fails — the + // queued send must go out signed once the keyring opens the key. + it('sends a send refused for a locked key once the key is unlocked and it is retried', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + let unlocked = false; + const transform = pgpOutgoingTransform( + fakeKeyring({ + signingKeyFor: async (email) => { + if (!unlocked) throw new PgpKeyringError('locked'); + return email === 'me@example.org' ? readUnlockedPrivateKey(me.armoredPrivateKey) : null; + }, + }), + { request: { encrypt: false, sign: true }, preferEncrypt: false }, + ); + await expect(transform(raw, context())).rejects.toMatchObject({ message: PGP_UNLOCK_THEN_RETRY_MESSAGE }); + unlocked = true; + expect(detectPgpMime(await transform(raw, context()))).toBe('signed'); + }); + + // Changed deliberately (CASA 4.1.4): the log line used to carry the thrown text. // Breaks: an openpgp failure mid-wrap (bad key material) escaped as a transient error and was retried. - // Changed deliberately (CASA 4.1.4): the reason no longer quotes the thrown text; it is logged instead. it('wraps unexpected failures as permanent', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const transform = pgpOutgoingTransform( fakeKeyring({ encryptionKeysFor: async () => { throw 'boom'; } }), { request: { encrypt: true, sign: false }, preferEncrypt: false }, ); - await expect(transform(raw, context())).rejects.toMatchObject({ - transient: false, - message: `Could not encrypt the message: ${PGP_OPERATION_FAILED_REASON}`, - }); - expect(warn.mock.calls.map((call) => call.join(' '))).toEqual([expect.stringContaining('boom')]); + await expect(transform(raw, context())).rejects.toMatchObject({ transient: false, message: PGP_FAILURE_MESSAGE }); + // The thrown value's type, never the value: `{ name: 'string' }`. + expect(warn).toHaveBeenCalledTimes(1); + expect(inspect(warn.mock.calls[0])).toContain("name: 'string'"); + expect(inspect(warn.mock.calls[0])).not.toContain('boom'); + }); + + // Breaks (CASA 4.1.4): a refusal's cause — the recipients without a key, the + // sender's address, a library message — reaches app.log. The log keeps the + // class and the code, and nothing else. + it('logs every refusal by class and code only', async () => { + const SENTINEL = 'sentinel-recipient@example.org'; + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const encrypting = { request: { encrypt: true, sign: false }, preferEncrypt: false }; + await pgpOutgoingTransform(fakeKeyring(), encrypting)(raw, context([SENTINEL])).catch(() => undefined); + await pgpOutgoingTransform(fakeKeyring({ signingKeyFor: async () => null }), { request: { encrypt: false, sign: true }, preferEncrypt: false })( + raw, + context(), + ).catch(() => undefined); + const crafted = Object.assign(new Error(`Could not find valid encryption key packet in key for ${SENTINEL}`), { code: 'ERR_CRAFTED' }); + await pgpOutgoingTransform(fakeKeyring({ encryptionKeysFor: async () => { throw crafted; } }), encrypting)(raw, context()).catch(() => undefined); + await pgpOutgoingTransform(fakeKeyring({ ownPublicKeyFor: async () => { throw new TypeError(`db gone for ${SENTINEL}`); } }), { preferEncrypt: false })( + raw, + context(), + ); + + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.lines).toEqual([ + expect.stringContaining("Could not encrypt an outgoing message { name: 'PgpSendRefusal', code: 'no-recipient-key' }"), + expect.stringContaining("Could not sign an outgoing message { name: 'PgpSendRefusal', code: 'no-signing-key' }"), + expect.stringContaining("Could not encrypt an outgoing message { name: 'Error', code: 'ERR_CRAFTED' }"), + expect.stringContaining("Autocrypt header skipped { name: 'TypeError' }"), + ]); + } finally { + logs.stop(); + } }); }); @@ -180,29 +239,44 @@ describe('OpenPGP library failures (CASA 4.1.4)', () => { const signOnlyKey = async () => (await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ email: 'bob@example.org' }], subkeys: [], format: 'object' })).publicKey; + // Changed deliberately (CASA 4.1.4): the send used to read "Could not encrypt the message: " and log openpgp.js's text. // Breaks: a send fails with openpgp.js's own text ("Could not find valid - // encryption key packet in key …"), which varies with the failure — the - // user reads one sentence, the log keeps the library's reason. - it('shows our reason for an OpenPGP failure on send, and logs the library one', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + // encryption key packet in key …"), which varies with the failure, or that + // text reaches app.log. The user reads one sentence, the log class and code. + it('answers an OpenPGP failure on send with the one sentence, and logs no library text', async () => { const bobSignOnly = await signOnlyKey(); - const transform = pgpOutgoingTransform( - fakeKeyring({ encryptionKeysFor: async () => ({ keys: [bobSignOnly], missing: [] }) }), - { request: { encrypt: true, sign: false }, preferEncrypt: false }, - ); - const error = await transform(raw, context()).catch((e) => e); - expect(error).toBeInstanceOf(OutgoingMimeError); - expect(error).toMatchObject({ transient: false, message: `Could not encrypt the message: ${PGP_OPERATION_FAILED_REASON}` }); - expect(warn.mock.calls.map((call) => call.join(' '))).toEqual([expect.stringMatching(/Could not encrypt an outgoing message: .*encryption key/i)]); + const libraryText = await openpgp + .encrypt({ message: await openpgp.createMessage({ text: 'x' }), encryptionKeys: bobSignOnly }) + .then(() => 'encrypted', (error: Error) => error.message); + expect(libraryText).toMatch(/encryption key/i); + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const transform = pgpOutgoingTransform( + fakeKeyring({ encryptionKeysFor: async () => ({ keys: [bobSignOnly], missing: [] }) }), + { request: { encrypt: true, sign: false }, preferEncrypt: false }, + ); + const error = await transform(raw, context()).catch((e) => e); + expect(error).toBeInstanceOf(OutgoingMimeError); + expect(error).toMatchObject({ transient: false, message: PGP_FAILURE_MESSAGE }); + expect(logs.lines).toEqual([expect.stringContaining("Could not encrypt an outgoing message { name: 'Error' }")]); + expect(logs.containing('encryption key')).toEqual([]); + } finally { + logs.stop(); + } }); - // Breaks: a draft that cannot be encrypted shows openpgp.js's text in the composer, or loses its reason from the log. - it('shows our reason when a draft cannot be encrypted, and logs the library one', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + // Changed deliberately (CASA 4.1.4): encryptDraftMime used to map and log the failure itself, as + // "the OpenPGP operation failed" and "No OpenPGP key for
…". Its caller now answers the + // one sentence and logs class and code (see draft-encryption.test.ts). + // Breaks: a draft with no key of its own, or one openpgp.js will not encrypt + // to, is saved anyway — the only other thing to save is the plaintext. + it('refuses a draft it cannot encrypt, naming no address', async () => { const ownSignOnly = await signOnlyKey(); - const error = await encryptDraftMime(raw, 'me@example.org', { ownPublicKeyFor: async () => ownSignOnly } as never).catch((e) => e); - expect(error).toBeInstanceOf(Error); - expect(error.message).toBe(PGP_OPERATION_FAILED_REASON); - expect(warn.mock.calls.map((call) => call.join(' '))).toEqual([expect.stringMatching(/Could not encrypt a draft: .*encryption key/i)]); + await expect(encryptDraftMime(raw, 'me@example.org', { ownPublicKeyFor: async () => ownSignOnly } as never)).rejects.toBeInstanceOf(Error); + const noKey = await encryptDraftMime(raw, 'me@example.org', { ownPublicKeyFor: async () => null }).catch((e) => e); + expect(noKey).toBeInstanceOf(PgpKeyringError); + expect(noKey).toMatchObject({ code: 'not-found', message: PGP_FAILURE_MESSAGE }); + const noFrom = await encryptDraftMime(raw, '', { ownPublicKeyFor: async () => null }).catch((e) => e); + expect(noFrom).toMatchObject({ code: 'not-found', message: PGP_FAILURE_MESSAGE }); }); }); diff --git a/apps/desktop/test/unit/electron/services/pgp-reader.test.ts b/apps/desktop/test/unit/electron/services/pgp-reader.test.ts index 4969aad0..863e0a47 100644 --- a/apps/desktop/test/unit/electron/services/pgp-reader.test.ts +++ b/apps/desktop/test/unit/electron/services/pgp-reader.test.ts @@ -1,7 +1,9 @@ +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; import { encryptOutgoingMime, generateKeyPair, - PGP_DECRYPT_FAILED_MESSAGE, + PGP_FAILURE_MESSAGE, + PgpKeyError, readAnyKey, readUnlockedPrivateKey, signOutgoingMime, @@ -10,15 +12,19 @@ import { import * as openpgp from 'openpgp'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; -import { OPENED_CACHE_SIZE, PGP_OPEN_FAILED_MESSAGE, PgpReader, type StoredSource } from '../../../../electron/services/pgp-reader'; +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { PgpKeyringError } from '../../../../electron/services/pgp-keyring'; +import { OPENED_CACHE_SIZE, PgpReader, type StoredSource } from '../../../../electron/services/pgp-reader'; import { SealError } from '../../../../electron/services/pgp-secret-seal'; /** * Decrypt-on-view. What this protects: an encrypted message that will not - * open in the reader; a "locked" or "no key" state shown as a crash; a green - * signature badge on mail whose key speaks for someone other than From; and - * plaintext attachments lingering in memory after the user deleted their key. + * open in the reader; a locked key shown as a crash instead of a prompt; a + * failure whose answer differs with its cause (CASA 4.1.4); a green signature + * badge on mail whose key speaks for someone other than From; and plaintext + * attachments lingering in memory after the user deleted their key. */ +const FAILED = { ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE } as const; const inner = Buffer.from( [ 'MIME-Version: 1.0', @@ -105,53 +111,65 @@ describe('PgpReader.open', () => { expect(await noFrom.open('e1')).toMatchObject({ signature: { fromMatches: false } }); }); - // Breaks: a message nobody's key opens shows as a crash instead of "no key". - it('returns the PgpOpenError code when no key opens it', async () => { + // Changed deliberately (CASA 4.1.4): this used to answer `no-key` with its own sentence. + // Breaks: a message nobody's key opens shows as a crash, or reads + // differently from a damaged one ("none of your keys" tells a sender which + // key IDs the user holds). + it('answers a message no key opens like any other failure', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => ({ decryptionKeys: [], verificationKeys: [], })); - expect(await reader.open('e1')).toMatchObject({ ok: false, code: 'no-key' }); + expect(await reader.open('e1')).toEqual(FAILED); expect(reader.attachment('e1', undefined, 0)).toBeNull(); }); + // Breaks: a key that is only locked reads as a failure, so the reader offers no passphrase prompt. + it('answers a locked key with the locked prompt and the same sentence', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => ({ + decryptionKeys: [], + lockedKeys: [rita], + verificationKeys: [], + })); + expect(await reader.open('e1')).toEqual({ ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE }); + }); + + // Changed deliberately (CASA 4.1.4): a source failure used to answer `unavailable` and quote the fetch error. // Breaks: a message whose source is gone (deleted on the server, offline) - // hangs the reader or throws into the renderer. - it('reports an unavailable source, thrown or missing', async () => { - expect(await readerWith(null).reader.open('e1')).toMatchObject({ ok: false, code: 'unavailable' }); + // hangs the reader or throws into the renderer — or the fetch's own text + // (which can quote a server's reply) reaches the renderer. + it('answers a source that is missing or fails to load with the one sentence', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await readerWith(null).reader.open('e1')).toEqual(FAILED); const thrown = readerWith(async () => { throw new Error('connection reset'); }); - expect(await thrown.reader.open('e1')).toMatchObject({ ok: false, code: 'unavailable', error: expect.stringContaining('connection reset') }); - }); - - // Breaks: an unexpected failure (keyring unreadable) escapes as a rejected IPC call — - // or (CASA 4.1.4) shows the library's / platform's own text instead of ours. - it('maps an unexpected failure to unavailable, with its reason in the log only', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => { - throw new Error('keyring unreadable'); - }); - expect(await reader.open('e1')).toEqual({ ok: false, code: 'unavailable', error: PGP_OPEN_FAILED_MESSAGE }); - expect(warnLines(warn)).toEqual([expect.stringContaining('keyring unreadable')]); + expect(await thrown.reader.open('e1')).toEqual(FAILED); }); - // Breaks: "the keychain is not available" — decided before any decryption, - // and the one thing the user can act on — is flattened into the vague message. - it('keeps our own keychain refusal in its own words', async () => { + // Changed deliberately (CASA 4.1.4): an unexpected failure used to answer `unavailable`, and our own + // keychain refusal its own sentence. + // Breaks: an unexpected failure (keyring unreadable, a keychain that will + // not open, an envelope we do not know) escapes as a rejected IPC call, or + // reads differently from a decryption failure. + it.each([ + ['a keyring that cannot be read', () => new Error('keyring unreadable')], + ['no keychain', () => new SealError('keychain-unavailable')], + ['an unknown key envelope', () => new SealError('unknown-format')], + ['an unreadable own key', () => new PgpKeyError('bad-key')], + ['a missing own key', () => new PgpKeyringError('not-found')], + ['a non-Error throw', () => 'boom'], + ])('answers %s with the one sentence', async (_name, failure) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => { - throw new SealError('This key is sealed by the OS keychain, which is not available', 'keychain-unavailable'); - }); - expect(await reader.open('e1')).toEqual({ - ok: false, - code: 'unavailable', - error: 'This key is sealed by the OS keychain, which is not available', + throw failure(); }); + expect(await reader.open('e1')).toEqual(FAILED); }); }); -const warnLines = (warn: { mock: { calls: unknown[][] } }): string[] => warn.mock.calls.map((call) => call.map(String).join(' ')); - describe('PgpReader decryption failures (CASA 4.1.4)', () => { /** The encrypted fixture with one bit of its binary ciphertext flipped at `offset` (negative: from the end). */ const tampered = async (offset: number): Promise => { @@ -162,41 +180,89 @@ describe('PgpReader decryption failures (CASA 4.1.4)', () => { return encryptedRaw.replace(armor, rearmored); }; + /** What openpgp.js itself says about a ciphertext for rita — text that must reach neither the renderer nor the log. */ + const libraryReason = async (raw: string): Promise => { + const armored = raw.match(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/)![0]; + try { + await openpgp.decrypt({ message: await openpgp.readMessage({ armoredMessage: armored }), decryptionKeys: rita }); + return 'opened'; + } catch (error) { + return (error as Error).message; + } + }; + + // Changed deliberately (CASA 4.1.4): the log used to carry the library's reason. // Breaks: the reader shows "Key Data Integrity failed" for one tampered // message and "Modification detected" for another — a decryption oracle for - // whoever sent them. The renderer must get one sentence; the log the reason. - it('shows the same text for a bad session key and a failed integrity check, and logs each reason', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - const views = []; - for (const raw of [await tampered(40), await tampered(-5)]) { - views.push(await readerWith({ raw, fromAddress: 'gee@example.org' }).reader.open('e1')); + // whoever sent them — or writes those reasons to app.log, which users attach + // to bug reports. The renderer gets one sentence; the log the class and code. + it('answers a bad session key, a failed integrity check and garbage alike, and logs only class and code', async () => { + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const raws = [await tampered(40), await tampered(-5), encryptedRaw.replace(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/, '-----BEGIN PGP MESSAGE-----\r\n\r\nnonsense\r\n-----END PGP MESSAGE-----')]; + const reasons = await Promise.all(raws.map(libraryReason)); + // Proof these are three different failures inside the library. + expect(new Set(reasons).size).toBe(3); + for (const raw of raws) expect(await readerWith({ raw, fromAddress: 'gee@example.org' }).reader.open('e1')).toEqual(FAILED); + expect(logs.containing('Could not open OpenPGP message e1')).toEqual([ + expect.stringContaining("{ name: 'PgpOpenError', code: 'bad-data' }"), + expect.stringContaining("{ name: 'PgpOpenError', code: 'bad-data' }"), + expect.stringContaining("{ name: 'PgpOpenError', code: 'bad-data' }"), + ]); + for (const reason of reasons) expect(logs.containing(reason)).toEqual([]); + // The log line names the message, never its content. + expect(logs.containing('the secret plan')).toEqual([]); + } finally { + logs.stop(); } - views.forEach((view) => expect(view).toEqual({ ok: false, code: 'bad-data', error: PGP_DECRYPT_FAILED_MESSAGE })); - const lines = warnLines(warn); - expect(lines).toEqual([ - expect.stringContaining('Key Data Integrity failed'), - expect.stringContaining('Modification detected'), - ]); - // The log line names the message, never its content. - lines.forEach((line) => expect(line).not.toContain('the secret plan')); }); - // Breaks: a refusal decided before decrypting ("no key") starts writing log noise for every message the user cannot open. - it('logs nothing for a refusal that carries no library reason', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => ({ decryptionKeys: [], verificationKeys: [] })); - expect(await reader.open('e1')).toMatchObject({ ok: false, code: 'no-key' }); - expect(warn).not.toHaveBeenCalled(); + // Breaks (CASA 4.1.4): a failure's own text — a fetch error quoting a + // server, a keychain's refusal, a crafted library message, an address — + // reaches app.log. The sentinel never may; the class and code always do. + it('never writes a failure\'s message to the log', async () => { + const SENTINEL = 'sentinel-pgp-reason@example.org'; + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const crafted = Object.assign(new Error(`Session key decryption failed for ${SENTINEL}`), { code: 'ERR_CRAFTED' }); + await readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => { throw crafted; }).reader.open('e1'); + await readerWith(async () => { throw new TypeError(`fetch of ${SENTINEL} failed`); }).reader.open('e2'); + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.containing("Could not open OpenPGP message e1 { name: 'Error', code: 'ERR_CRAFTED' }")).toHaveLength(1); + expect(logs.containing("Could not load the source of OpenPGP message e2 { name: 'TypeError' }")).toHaveLength(1); + } finally { + logs.stop(); + } }); - // Breaks: why a signature failed ("Signed digest did not match") reaches the renderer, or is lost from the log. - it('logs why a signature did not verify and sends the renderer only the verdict', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - const forged = signedRaw.replace('the secret plan', 'the forged plan'); - const view = await readerWith({ raw: forged, fromAddress: 'gee@example.org' }).reader.open('e1'); - expect(view).toMatchObject({ ok: true, signature: { status: 'invalid' } }); - expect(JSON.stringify(view)).not.toMatch(/digest|could not be verified/i); - expect(warnLines(warn)).toEqual([expect.stringMatching(/signature on e1 did not verify: .+/)]); + // Changed deliberately: a refusal decided before decrypting ("no key") used + // to log nothing. Now that the user reads one sentence for every cause, the + // log's class and code is the only record of which it was. + // Breaks: a failure that leaves no trace, so a bug report cannot tell "no key" from "damaged". + it('logs a refusal decided before decrypting, by its code', async () => { + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'gee@example.org' }, () => ({ decryptionKeys: [], verificationKeys: [] })); + expect(await reader.open('e1')).toEqual(FAILED); + expect(logs.containing("{ name: 'PgpOpenError', code: 'no-key' }")).toHaveLength(1); + } finally { + logs.stop(); + } + }); + + // Changed deliberately (CASA 4.1.4): this line used to quote the library's reason. + // Breaks: why a signature failed ("Signed digest did not match") reaches the renderer or the log. + it('logs that a signature did not verify, and sends the renderer only the verdict', async () => { + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + const forged = signedRaw.replace('the secret plan', 'the forged plan'); + const view = await readerWith({ raw: forged, fromAddress: 'gee@example.org' }).reader.open('e1'); + expect(view).toMatchObject({ ok: true, signature: { status: 'invalid' } }); + expect(JSON.stringify(view)).not.toMatch(/digest|could not be verified/i); + expect(logs.lines).toEqual([expect.stringMatching(/OpenPGP signature on e1 did not verify$/)]); + } finally { + logs.stop(); + } }); }); @@ -256,12 +322,13 @@ describe('PgpReader.openDraft', () => { // Breaks: a draft that cannot be decrypted opens as its placeholder, and the next autosave overwrites the real one. it('passes a refusal through instead of an empty draft', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); const { reader } = readerWith({ raw: encryptedRaw, fromAddress: 'rita@example.com' }, () => ({ decryptionKeys: [], verificationKeys: [], })); - expect(await reader.openDraft('d1')).toMatchObject({ ok: false, code: 'no-key' }); + expect(await reader.openDraft('d1')).toEqual(FAILED); const { reader: unavailable } = readerWith(null); - expect(await unavailable.openDraft('d1')).toMatchObject({ ok: false, code: 'unavailable' }); + expect(await unavailable.openDraft('d1')).toEqual(FAILED); }); }); diff --git a/apps/desktop/test/unit/electron/services/pgp-secret-seal.test.ts b/apps/desktop/test/unit/electron/services/pgp-secret-seal.test.ts index eff8130f..783889c9 100644 --- a/apps/desktop/test/unit/electron/services/pgp-secret-seal.test.ts +++ b/apps/desktop/test/unit/electron/services/pgp-secret-seal.test.ts @@ -1,3 +1,4 @@ +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; import { describe, expect, it, vi } from 'vitest'; const h = vi.hoisted(() => ({ @@ -12,7 +13,6 @@ const h = vi.hoisted(() => ({ vi.mock('electron', () => ({ safeStorage: h.safeStorage })); import { - KEYCHAIN_REFUSED_MESSAGE, SealError, electronKeychain, protectionOf, @@ -60,11 +60,11 @@ describe('pgp secret seal', () => { } }); + // Changed deliberately (CASA 4.1.4): the refusal used to carry a keychain sentence of its own. // Breaks: a keychain that exists but will not decrypt (macOS access denied, // a locked or rotated Linux keyring, a copied profile) throws safeStorage's - // plain Error, which the reader and the send path show as a vague OpenPGP - // failure ("Try again") instead of the one thing the user can fix — or the - // platform's message (or the key) reaches the log. + // plain Error, whose platform text could reach the user, or reads as "no + // key" — or the platform's message (or the key) reaches the log. it('turns a keychain that refuses to decrypt into keychain-unavailable, logging only the error class', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { @@ -82,7 +82,7 @@ describe('pgp secret seal', () => { thrown = error; } expect(thrown).toBeInstanceOf(SealError); - expect(thrown).toMatchObject({ code: 'keychain-unavailable', message: KEYCHAIN_REFUSED_MESSAGE }); + expect(thrown).toMatchObject({ code: 'keychain-unavailable', message: PGP_FAILURE_MESSAGE }); const logged = warn.mock.calls.map((call) => call.map(String).join(' ')); expect(logged).toEqual([expect.stringContaining('(Error)')]); expect(logged.join('\n')).not.toMatch(/SECRET-KEY|safeStorage/); @@ -101,12 +101,38 @@ describe('pgp secret seal', () => { }); }); + // Changed deliberately (CASA 4.1.4): this used to throw "Unknown private-key envelope". // Breaks: a corrupt or foreign blob was treated as one of our envelopes. it('rejects an unknown envelope', () => { - expect(() => protectionOf(Buffer.from('PLAIN:key'))).toThrow(/Unknown/); + expect(() => protectionOf(Buffer.from('PLAIN:key'))).toThrow(SealError); expect(() => unseal(fakeKeychain(), Buffer.from(''))).toThrow(SealError); }); + // Breaks (CASA 4.1.4): a seal failure reads differently by cause (no keychain, + // a refusing one, a foreign envelope), where the reader or a key operation would show it. + it('gives every seal failure the one sentence, its cause only as the code', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const refusing: Keychain = { ...fakeKeychain(), decrypt: () => { throw new Error('refused'); } }; + const sealed = sealWithKeychain(fakeKeychain(), 'K'); + const failures: Array<[() => unknown, string]> = [ + [() => sealWithKeychain(fakeKeychain(false), 'K'), 'keychain-unavailable'], + [() => unseal(fakeKeychain(false), sealed), 'keychain-unavailable'], + [() => unseal(refusing, sealed), 'keychain-unavailable'], + [() => protectionOf(Buffer.from('PLAIN:key')), 'unknown-format'], + ]; + for (const [fail, code] of failures) { + let thrown: unknown; + try { + fail(); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(SealError); + expect(thrown).toMatchObject({ name: 'SealError', code, message: PGP_FAILURE_MESSAGE }); + } + vi.restoreAllMocks(); + }); + // basic_text "encrypts" with a published key, so sealing a private key with // it is the plaintext form this module refuses. Breaks if it counts as a // keychain: whoever copies the profile reads the user's encrypted mail diff --git a/apps/desktop/test/unit/electron/services/pgp-service.test.ts b/apps/desktop/test/unit/electron/services/pgp-service.test.ts index 980579d1..b55bc278 100644 --- a/apps/desktop/test/unit/electron/services/pgp-service.test.ts +++ b/apps/desktop/test/unit/electron/services/pgp-service.test.ts @@ -1,4 +1,5 @@ import { OutgoingMimeError, getLogLevel, setLogLevel, setLogSink, type OutgoingMimeContext } from '@sarvinbox/core'; +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; import { describe, expect, it, vi } from 'vitest'; vi.mock('electron', () => ({ safeStorage: {} })); @@ -62,12 +63,28 @@ describe('sendTransformFor', () => { expect(() => getPgpKeyring()).toThrow('core DB not open'); }); + // Changed deliberately (CASA 4.1.4): the refusal used to read "The OpenPGP keyring could not be opened, so the message was not sent". // Breaks: an encrypted send went out as plaintext because the keyring was not ready. it('refuses an encrypted or signed send when the keyring cannot open', async () => { const transform = sendTransformFor({ encrypt: true, sign: false }, { keyring: () => { throw new Error('no db'); } })!; const error = await transform(Buffer.from('x'), ctx).catch((e) => e); expect(error).toBeInstanceOf(OutgoingMimeError); - expect(error.transient).toBe(false); + expect(error).toMatchObject({ transient: false, message: PGP_FAILURE_MESSAGE }); + }); + + // Breaks (CASA 4.1.4): the keyring's own error text (a path, a SQLite message) reaches app.log once per send. + it('logs a keyring that cannot open by class and code only', () => { + const SENTINEL = 'sentinel-keyring-path'; + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + sendTransformFor({ encrypt: true, sign: false }, { + keyring: () => { throw Object.assign(new Error(`unable to open /Users/${SENTINEL}/core.db`), { code: 'SQLITE_CANTOPEN' }); }, + }); + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.containing("OpenPGP keyring unavailable for this send { name: 'Error', code: 'SQLITE_CANTOPEN' }")).toHaveLength(1); + } finally { + logs.stop(); + } }); // Breaks: unreadable settings made the transform throw instead of sending with no preference. diff --git a/apps/desktop/test/unit/src/components/ComposeEmail-account.test.tsx b/apps/desktop/test/unit/src/components/ComposeEmail-account.test.tsx index 1ec9f2bf..016416e4 100644 --- a/apps/desktop/test/unit/src/components/ComposeEmail-account.test.tsx +++ b/apps/desktop/test/unit/src/components/ComposeEmail-account.test.tsx @@ -85,7 +85,8 @@ describe('the shared composer sending account', () => { expect(view.container.textContent).toContain('sales@example.com'); expect(h.autosave).toHaveBeenCalledWith(expect.objectContaining({ accountId: 'sales' })); expect(h.signature).toHaveBeenCalledWith('new', 'sales'); - expect(h.pgp).toHaveBeenCalledWith('sales@example.com', ['buyer@example.com'], false); + // The 4th argument is the request a send refused for a locked key restores; none here. + expect(h.pgp).toHaveBeenCalledWith('sales@example.com', ['buyer@example.com'], false, undefined); expect(h.send).not.toHaveBeenCalled(); fire(view.all('button').find(button => button.textContent === 'Send') ?? null, 'click'); await settle(); @@ -97,7 +98,7 @@ describe('the shared composer sending account', () => { fire(view.all('button').find(button => button.textContent === 'Send') ?? null, 'click'); await settle(); expect(h.send).toHaveBeenCalledWith(expect.objectContaining({ accountId: undefined })); - expect(h.pgp).toHaveBeenCalledWith('work@example.com', ['buyer@example.com'], false); + expect(h.pgp).toHaveBeenCalledWith('work@example.com', ['buyer@example.com'], false, undefined); }); it('does not send from the active mailbox when the draft account was removed', async () => { diff --git a/apps/desktop/test/unit/src/components/ComposeEmail-pgp-unlock.test.tsx b/apps/desktop/test/unit/src/components/ComposeEmail-pgp-unlock.test.tsx new file mode 100644 index 00000000..08a5e430 --- /dev/null +++ b/apps/desktop/test/unit/src/components/ComposeEmail-pgp-unlock.test.tsx @@ -0,0 +1,177 @@ +// @vitest-environment happy-dom +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ComposeEmail } from '../../../../src/components/ComposeEmail'; +import { PGP_LOCKED_TITLE, PGP_UNLOCK_TO_SIGN } from '../../../../src/components/email-detail/pgp-view-model'; +import { act, cleanup, fire, render, settle, typeInto } from '../../../helpers/render'; + +// What breaks if this file fails: the popup composer, reopened because main +// refused its send for a locked signing key, gives no way to unlock — or its +// prompt says why an unlock failed in words that vary (CASA 4.1.4) — or, once +// unlocked, Send does not go out with the toggles the refused send had. + +const h = vi.hoisted(() => ({ + send: vi.fn(), pgp: vi.fn(), failure: vi.fn(), listOwnKeys: vi.fn(), unlock: vi.fn(), signingKeyLocked: vi.fn(), + pgpState: null as Record | null, +})); +vi.mock('../../../../src/store/email-store', () => ({ + useEmailStore: (selector?: (state: unknown) => unknown) => { + const state = { + accounts: [{ id: 'work', email: 'work@example.com', identities: ['work@example.com', 'alias@example.com'] }], + activeAccountId: 'work', + imapConfig: { username: 'work@example.com' }, + }; + return selector ? selector(state) : state; + }, +})); +vi.mock('../../../../src/components/useCompose', () => ({ + useCompose: ({ initialDraft }: { initialDraft?: { to?: string; subject?: string; htmlContent?: string } }) => ({ + to: initialDraft?.to ?? 'buyer@example.com', cc: '', bcc: '', pendingTo: [], pendingCc: [], pendingBcc: [], + subject: initialDraft?.subject ?? 'Proposal', htmlBody: initialDraft?.htmlContent ?? '

Please review.

', plainBody: 'Please review.', + attachments: [], sending: false, showCc: false, showBcc: false, showPolishModal: false, + mergeEmails: (value: string) => value ? value.split(', ') : [], getSignature: () => '', sendEmail: h.send, + setTo: vi.fn(), setCc: vi.fn(), setBcc: vi.fn(), setPendingTo: vi.fn(), setPendingCc: vi.fn(), setPendingBcc: vi.fn(), + setSubject: vi.fn(), setHtmlBody: vi.fn(), setBody: vi.fn(), setAttachments: vi.fn(), setSending: vi.fn(), + setShowCc: vi.fn(), setShowBcc: vi.fn(), setShowPolishModal: vi.fn(), setPolishMode: vi.fn(), + }), +})); +vi.mock('../../../../src/hooks/useDraftAutosave', () => ({ useDraftAutosave: () => ({ markDiscarded: () => 'draft-message-id', closeAction: vi.fn() }) })); +vi.mock('../../../../src/hooks/useForwardAttachments', () => ({ useForwardAttachments: () => ({ blocked: false }) })); +vi.mock('../../../../src/hooks/useCloseComposePrompt', () => ({ useCloseComposePrompt: () => ({ requestClose: vi.fn(), isAsking: () => false, closePromptDialog: null }) })); +// The hook's answer for what the composer asks: the restored request as the +// user's own choice (what the real hook does), unless a test says otherwise. +vi.mock('../../../../src/hooks/usePgpCompose', () => ({ + usePgpCompose: (...args: unknown[]) => { h.pgp(...args); return { state: h.pgpState ?? { encrypt: true, request: args[3] ?? undefined, downgrade: false } }; }, +})); +vi.mock('../../../../src/services/ai-service', () => ({ getDefaultProvider: () => null })); +vi.mock('../../../../src/utils/attachment-reminder', () => ({ checkAttachmentBeforeSend: async () => true })); +vi.mock('../../../../src/utils/send-failure', () => ({ reportSendFailure: h.failure })); +vi.mock('../../../../src/components/ComposeToolbar', () => ({ ComposeToolbar: ({ onSend }: { onSend: () => void }) => })); +vi.mock('../../../../src/components/EmailInput', () => ({ EmailInput: () =>
})); +vi.mock('../../../../src/components/RichTextEditor', () => ({ RichTextEditor: () =>
, EMPTY_EDITOR_HTML: '

' })); +vi.mock('../../../../src/components/ForwardAttachmentStatus', () => ({ ForwardAttachmentStatus: () => null })); +vi.mock('../../../../src/components/SmtpNotConfiguredBanner', () => ({ SmtpNotConfiguredBanner: () => null })); +vi.mock('../../../../src/components/QuotedOriginalPreview', () => ({ QuotedOriginalPreview: () => null })); +vi.mock('../../../../src/components/SandboxedEmailBody', () => ({ SandboxedEmailBody: () => null })); +vi.mock('../../../../src/components/PolishModal', () => ({ PolishModal: () => null })); +vi.mock('../../../../src/components/SelectionPolishMenu', () => ({ SelectionPolishMenu: () => null })); + +const RESTORED = { to: 'buyer@example.com', subject: 'Proposal', htmlContent: '

Please review.

', pgpUnlock: { encrypt: true, sign: true } }; + +beforeEach(() => { + vi.clearAllMocks(); + h.pgpState = null; + h.send.mockResolvedValue(undefined); + h.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: false }] }); + h.signingKeyLocked.mockResolvedValue({ success: true, data: false }); + (window as unknown as { electronAPI: unknown }).electronAPI = { pgp: { listOwnKeys: h.listOwnKeys, unlock: h.unlock, signingKeyLocked: h.signingKeyLocked } }; +}); +afterEach(cleanup); + +const prompt = (view: ReturnType) => view.find('[data-pgp-send-unlock]'); +const submitPassphrase = async (view: ReturnType, passphrase: string) => { + typeInto(view.byLabel('Key passphrase'), passphrase); + await act(async () => prompt(view)!.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); + await settle(); +}; + +describe('ComposeEmail reopened for a locked signing key', () => { + // Breaks: the reopened composer has no unlock prompt, a failed unlock says + // "wrong passphrase" (or nothing), the prompt is gone before a retry, or Send + // after unlocking drops the encrypt/sign the refused send asked for. + it('shows the unlock prompt, keeps it for a retry, and sends with the restored toggles once unlocked', async () => { + h.unlock.mockResolvedValueOnce({ success: false, error: PGP_FAILURE_MESSAGE }).mockResolvedValueOnce({ success: true }); + // Still locked after the wrong passphrase, open after the right one. + h.signingKeyLocked.mockResolvedValueOnce({ success: true, data: true }).mockResolvedValueOnce({ success: true, data: false }); + const view = render(); + expect(prompt(view)?.textContent).toContain(PGP_LOCKED_TITLE); + expect(prompt(view)?.textContent).toContain(PGP_UNLOCK_TO_SIGN); + expect(h.pgp).toHaveBeenLastCalledWith('work@example.com', ['buyer@example.com'], false, { encrypt: true, sign: true }); + + await submitPassphrase(view, 'wrong'); + expect(prompt(view)?.textContent).toContain(PGP_FAILURE_MESSAGE); + expect(prompt(view)?.textContent).not.toMatch(/wrong|did not unlock/i); + + await submitPassphrase(view, 'right'); + expect(h.unlock).toHaveBeenLastCalledWith('A', 'right'); + // Re-checked for the address this composer sends as. + expect(h.signingKeyLocked).toHaveBeenLastCalledWith('work@example.com'); + expect(prompt(view)).toBeNull(); + + fire(view.all('button').find((button) => button.textContent === 'Send') ?? null, 'click'); + await settle(); + expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ pgp: { encrypt: true, sign: true } })); + expect(h.failure).not.toHaveBeenCalled(); + }); + + // THE plaintext leak (A1): a send from an alias — the address with the key — + // refused for a locked key reopened on the PRIMARY address, which has no + // key, so the retried message went out unencrypted (or signed as someone + // else). The reopened composer keeps the alias, re-checks its key, and sends + // from it, encrypted. The same draft carries the alias through Undo send. + it('reopens on the alias it sent as, unlocks that key, and sends from it, encrypted', async () => { + h.unlock.mockResolvedValue({ success: true }); + const view = render(); + expect(h.pgp).toHaveBeenLastCalledWith('alias@example.com', ['buyer@example.com'], false, { encrypt: true, sign: true }); + await submitPassphrase(view, 'alias-pass'); + expect(h.signingKeyLocked).toHaveBeenLastCalledWith('alias@example.com'); + expect(prompt(view)).toBeNull(); + + fire(view.all('button').find((button) => button.textContent === 'Send') ?? null, 'click'); + await settle(); + expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + from: 'alias@example.com', + pgp: { encrypt: true, sign: true }, + draft: expect.objectContaining({ from: 'alias@example.com' }), + })); + }); + + // Breaks: a passphrase that opened some OTHER key closes the prompt, Send is + // refused again for the same locked key, and the prompt comes back — a loop. + it('keeps the prompt while the key this composer needs is still locked', async () => { + h.unlock.mockResolvedValue({ success: true }); + h.signingKeyLocked.mockResolvedValue({ success: true, data: true }); + const view = render(); + await submitPassphrase(view, 'other-key-pass'); + expect(prompt(view)?.textContent).toContain(PGP_FAILURE_MESSAGE); + expect(view.byLabel('Key passphrase')).not.toBeNull(); + }); + + // Breaks: the key was unlocked elsewhere meanwhile — nothing is locked, and the prompt is a dead end. + it('closes the prompt when nothing is locked any more', async () => { + h.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: true }] }); + const view = render(); + await submitPassphrase(view, 'anything'); + expect(h.unlock).not.toHaveBeenCalled(); + expect(prompt(view)).toBeNull(); + }); + + // The backstop for A1: whatever else goes wrong, encryption asked for but + // not deliverable (an address with no key, defaults not loaded) must never + // become a plaintext send. The composer stays open, with the one sentence. + it('refuses to send while encryption was asked for but cannot be carried', async () => { + h.pgpState = { encrypt: false, request: undefined, downgrade: true }; + const onClose = vi.fn(); + const view = render(); + fire(view.all('button').find((button) => button.textContent === 'Send') ?? null, 'click'); + await settle(); + expect(h.send).not.toHaveBeenCalled(); + expect(onClose).not.toHaveBeenCalled(); + expect(h.failure).toHaveBeenCalledWith(expect.objectContaining({ message: PGP_FAILURE_MESSAGE })); + }); + + // Breaks: the prompt appears on a composer nobody refused, or survives a switch to full screen after unlocking. + it('shows no prompt for an ordinary draft', () => { + const view = render(); + expect(prompt(view)).toBeNull(); + }); + + // Breaks: the prompt is lost when the composer goes full screen before the user unlocks. + it('keeps the prompt in full screen', async () => { + const view = render(); + fire(view.all('button').find((button) => button.getAttribute('title') === 'Full screen') ?? null, 'click'); + await settle(); + expect(prompt(view)?.textContent).toContain(PGP_UNLOCK_TO_SIGN); + }); +}); diff --git a/apps/desktop/test/unit/src/components/ComposeToolbar.pgp.test.tsx b/apps/desktop/test/unit/src/components/ComposeToolbar.pgp.test.tsx index 92451b5b..cb063179 100644 --- a/apps/desktop/test/unit/src/components/ComposeToolbar.pgp.test.tsx +++ b/apps/desktop/test/unit/src/components/ComposeToolbar.pgp.test.tsx @@ -30,7 +30,7 @@ const props = { }; const controls = (over: Partial = {}): PgpComposeControls => ({ - state: { available: true, encrypt: false, sign: false, missing: [], resolving: false, request: { encrypt: false, sign: false }, ...over }, + state: { available: true, encrypt: false, sign: false, missing: [], resolving: false, request: { encrypt: false, sign: false }, downgrade: false, ...over }, toggleEncrypt: vi.fn(), toggleSign: vi.fn(), }); diff --git a/apps/desktop/test/unit/src/components/email-detail/PgpMessageView.test.tsx b/apps/desktop/test/unit/src/components/email-detail/PgpMessageView.test.tsx index 0451e028..e4b280a5 100644 --- a/apps/desktop/test/unit/src/components/email-detail/PgpMessageView.test.tsx +++ b/apps/desktop/test/unit/src/components/email-detail/PgpMessageView.test.tsx @@ -1,8 +1,10 @@ // @vitest-environment happy-dom +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; import { act } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { PgpViewResult } from '../../../../../electron/services/pgp-reader'; +import { PGP_FAILURE_HINT } from '../../../../../src/components/email-detail/pgp-view-model'; import { PgpMessageView } from '../../../../../src/components/email-detail/PgpMessageView'; import { render, settle, typeInto, type Mounted } from '../../../../helpers/render'; @@ -199,12 +201,13 @@ describe('PgpMessageView', () => { expect(view.find('[data-pgp-badge]')?.textContent).toBe('Signed'); }); - // Breaks: the reader hangs on "Decrypting…" when the bridge rejects. + // Changed deliberately (CASA 4.1.4): a rejection used to show its own text ("IPC gone"). + // Breaks: the reader hangs on "Decrypting…" when the bridge rejects, or shows the rejection's text. it('turns a rejected open into a retryable failure, and retries', async () => { api.open.mockRejectedValueOnce(new Error('IPC gone')).mockResolvedValueOnce(opened()); const view = await mount('encrypted'); - expect(view.container.textContent).toContain('could not be loaded'); - expect(view.container.textContent).toContain('IPC gone'); + expect(view.find('[role="alert"]')?.textContent).toBe(`Encrypted message${PGP_FAILURE_MESSAGE}${PGP_FAILURE_HINT}Try again`); + expect(view.container.textContent).not.toContain('IPC gone'); const retry = [...view.container.querySelectorAll('button')].find((button) => button.textContent?.includes('Try again')); await act(async () => retry!.click()); await settle(); @@ -212,42 +215,102 @@ describe('PgpMessageView', () => { expect(view.find('[data-sandboxed]')).not.toBeNull(); }); - // Breaks: no key reads as a crash, with nothing telling the user where to go. - it('explains a message none of the keys open', async () => { - api.open.mockResolvedValue({ ok: false, code: 'no-key', error: 'no key' }); + // Changed deliberately (CASA 4.1.4): "no key" used to have its own title and guidance. + // Breaks: a failed open reads differently by cause — the reader must show + // the same title, main's one sentence and a retry for every failure, and + // offer no passphrase field for anything but a locked key. + it('shows every failure to open the same way', async () => { + api.open.mockResolvedValue({ ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE }); const view = await mount('encrypted'); - expect(view.container.textContent).toContain('None of your keys can open this message'); + // The same title, sentence, one fixed line of guidance and retry, whatever the cause. + expect(view.find('[role="alert"]')?.textContent).toBe(`Encrypted message${PGP_FAILURE_MESSAGE}${PGP_FAILURE_HINT}Try again`); expect(view.byLabel('Key passphrase')).toBeNull(); + expect(view.find('[data-sandboxed]')).toBeNull(); }); - // Breaks: a locked key cannot be unlocked from the message, or a wrong passphrase says nothing. + // Changed deliberately (CASA 4.1.4): a passphrase that unlocked nothing used to read "That passphrase + // did not unlock any of your keys". + // Breaks: a locked key cannot be unlocked from the message, a wrong + // passphrase says nothing (or says "wrong passphrase"), or the form is gone + // before the user can try again. it('unlocks with a passphrase and reopens the message', async () => { - api.open.mockResolvedValueOnce({ ok: false, code: 'locked', error: 'locked' }).mockResolvedValue(opened()); + const locked = { ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE } as const; + // Opened, then re-checked after each passphrase: still locked after the wrong one, open after the right one. + api.open.mockResolvedValueOnce(locked).mockResolvedValueOnce(locked).mockResolvedValue(opened()); api.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: false }] }); - api.unlock.mockResolvedValueOnce({ success: false }).mockResolvedValueOnce({ success: true }); + api.unlock.mockResolvedValueOnce({ success: false, error: PGP_FAILURE_MESSAGE }).mockResolvedValueOnce({ success: true }); const view = await mount('encrypted'); + expect(view.container.textContent).toContain('Your key is locked'); const submit = () => act(async () => view.find('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); typeInto(view.byLabel('Key passphrase'), 'wrong'); await submit(); await settle(); - expect(view.container.textContent).toContain('did not unlock any of your keys'); + expect(view.find('form')?.textContent).toContain(PGP_FAILURE_MESSAGE); + expect(view.container.textContent).not.toMatch(/wrong|did not unlock/i); typeInto(view.byLabel('Key passphrase'), 'right'); await submit(); await settle(); expect(api.unlock).toHaveBeenLastCalledWith('A', 'right'); expect(view.find('[data-sandboxed]')).not.toBeNull(); + // The re-check's open is what the reader shows: no third open. + expect(api.open).toHaveBeenCalledTimes(3); + }); + + // Breaks: the key was unlocked elsewhere (Settings, another message) while + // this prompt was up, so nothing is locked any more — and the form answered + // that with the failure sentence and no way forward. + it('opens the message when nothing is locked any more', async () => { + api.open.mockResolvedValueOnce({ ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE }).mockResolvedValue(opened()); + api.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: true }] }); + const view = await mount('encrypted'); + typeInto(view.byLabel('Key passphrase'), 'anything'); + await act(async () => view.find('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); + await settle(); + expect(api.unlock).not.toHaveBeenCalled(); + expect(view.find('[data-sandboxed]')).not.toBeNull(); + }); + + // Breaks: a passphrase that opened some OTHER key reads as success — the + // prompt goes away though the message's key is still locked. + it('keeps the prompt when the passphrase opened a key this message does not need', async () => { + api.open.mockResolvedValue({ ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE }); + api.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'OTHER', unlocked: false }] }); + api.unlock.mockResolvedValue({ success: true }); + const view = await mount('encrypted'); + typeInto(view.byLabel('Key passphrase'), 'other-key-pass'); + await act(async () => view.find('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); + await settle(); + expect(api.unlock).toHaveBeenCalledWith('OTHER', 'other-key-pass'); + expect(view.find('form')?.textContent).toContain(PGP_FAILURE_MESSAGE); + expect(view.byLabel('Key passphrase')).not.toBeNull(); + }); + + // Breaks: once unlocked, a message that then fails to open for another reason shows nothing, or still the prompt. + it('shows the failure the re-check finds, like any other', async () => { + api.open.mockResolvedValueOnce({ ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE }).mockResolvedValue({ ok: false, code: 'failed', error: PGP_FAILURE_MESSAGE }); + api.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: false }] }); + api.unlock.mockResolvedValue({ success: true }); + const view = await mount('encrypted'); + typeInto(view.byLabel('Key passphrase'), 'pass'); + await act(async () => view.find('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); + await settle(); + expect(view.find('[role="alert"]')?.textContent).toBe(`Encrypted message${PGP_FAILURE_MESSAGE}${PGP_FAILURE_HINT}Try again`); }); - // Breaks: a failing key list during unlock is swallowed with no feedback. + // Changed deliberately (CASA 4.1.4): a rejected key list used to show its own text ("bridge down"). + // Breaks: a failing key list during unlock is swallowed with no feedback, or shows the rejection's text. it('shows an unlock error', async () => { - api.open.mockResolvedValue({ ok: false, code: 'locked', error: 'locked' }); + api.open.mockResolvedValue({ ok: false, code: 'locked', error: PGP_FAILURE_MESSAGE }); api.listOwnKeys.mockRejectedValue(new Error('bridge down')); const view = await mount('encrypted'); typeInto(view.byLabel('Key passphrase'), 'pass'); await act(async () => view.find('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); await settle(); - expect(view.container.textContent).toContain('bridge down'); + expect(view.find('form')?.textContent).toContain(PGP_FAILURE_MESSAGE); + expect(view.container.textContent).not.toContain('bridge down'); + // The form stays for another try. + expect(view.byLabel('Key passphrase')).not.toBeNull(); }); }); diff --git a/apps/desktop/test/unit/src/components/email-detail/pgp-view-model.test.ts b/apps/desktop/test/unit/src/components/email-detail/pgp-view-model.test.ts index 7213cd5f..7eeb0300 100644 --- a/apps/desktop/test/unit/src/components/email-detail/pgp-view-model.test.ts +++ b/apps/desktop/test/unit/src/components/email-detail/pgp-view-model.test.ts @@ -1,6 +1,8 @@ +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; import { describe, expect, it, vi } from 'vitest'; import { + PGP_FAILURE_HINT, pgpBadge, pgpFailureView, shortFingerprint, @@ -70,19 +72,44 @@ describe('shortFingerprint', () => { }); describe('pgpFailureView', () => { - // Breaks: a locked key shows no way to unlock, or a transient failure offers no retry. - it('offers unlock for a locked key and retry only for an unavailable source', () => { - expect(pgpFailureView('locked', '')).toMatchObject({ canUnlock: true, canRetry: false }); - expect(pgpFailureView('no-key', '')).toMatchObject({ canUnlock: false, canRetry: false, detail: expect.stringContaining('Settings') }); - expect(pgpFailureView('bad-data', 'broken packet')).toMatchObject({ detail: 'broken packet', canRetry: false }); - expect(pgpFailureView('unavailable', 'offline')).toMatchObject({ detail: 'offline', canRetry: true }); + // Breaks: a locked key shows no way to unlock, or its guidance varies. + it('offers unlock for a locked key, with fixed guidance', () => { + expect(pgpFailureView('locked', PGP_FAILURE_MESSAGE)).toEqual({ + title: 'Your key is locked', + detail: 'Enter the passphrase of your OpenPGP key to read this message. It stays unlocked until you quit.', + canUnlock: true, + canRetry: false, + }); + }); + + // Changed deliberately (CASA 4.1.4): no-key, bad-data and unavailable used to have titles and + // guidance of their own (and only unavailable offered a retry); main now sends one code for all. + // Breaks: a failed open looks different by cause — a title, a hint or a + // retry button that appears for one cause and not another tells whoever + // crafted the message how far decryption got — or the user loses the one + // pointer to the fix for a key they have not added. + it('shows every other failure the same way: one title, main\'s sentence, one fixed hint, a retry', () => { + expect(pgpFailureView('failed', PGP_FAILURE_MESSAGE)).toEqual({ + title: 'Encrypted message', + detail: PGP_FAILURE_MESSAGE, + hint: PGP_FAILURE_HINT, + canUnlock: false, + canRetry: true, + }); + expect(PGP_FAILURE_HINT).toBe("If it was encrypted to a key you haven't added, import that key in Settings → Encryption."); }); }); describe('unlockLockedKeys', () => { - // Breaks: the passphrase is tried on keys that are already open, or only on the first locked one. - it('tries every locked key and counts the ones it opened', async () => { - const unlock = vi.fn(async (fingerprint: string) => ({ success: fingerprint === 'B' })); + // Changed deliberately: it used to resolve to how many keys it opened, which callers read as + // success or failure — wrong both ways (see PgpUnlockForm's recheck). + // Breaks: the passphrase is tried on keys that are already open, only on the + // first locked one, or one key's refusal stops the others being tried. + it('tries every locked key, whichever of them refuses', async () => { + const unlock = vi.fn(async (fingerprint: string) => { + if (fingerprint === 'A') throw new Error('bridge hiccup'); + return { success: fingerprint === 'B' }; + }); const api = { listOwnKeys: async () => ({ success: true, @@ -94,12 +121,14 @@ describe('unlockLockedKeys', () => { }), unlock, }; - expect(await unlockLockedKeys(api, 'pass')).toBe(1); + await expect(unlockLockedKeys(api, 'pass')).resolves.toBeUndefined(); expect(unlock.mock.calls.map(([fingerprint]) => fingerprint)).toEqual(['A', 'B']); }); - // Breaks: an unreadable key list throws instead of reporting "nothing unlocked". - it('unlocks nothing when the keys cannot be listed', async () => { - expect(await unlockLockedKeys({ listOwnKeys: async () => ({ success: false }), unlock: vi.fn() }, 'pass')).toBe(0); + // Breaks: an unreadable key list throws instead of leaving the caller's re-check to decide. + it('tries nothing when the keys cannot be listed', async () => { + const unlock = vi.fn(); + await expect(unlockLockedKeys({ listOwnKeys: async () => ({ success: false }), unlock }, 'pass')).resolves.toBeUndefined(); + expect(unlock).not.toHaveBeenCalled(); }); }); diff --git a/apps/desktop/test/unit/src/components/email-detail/useEmailDetail.composer-drafts.test.tsx b/apps/desktop/test/unit/src/components/email-detail/useEmailDetail.composer-drafts.test.tsx index 321d8ed2..d983231b 100644 --- a/apps/desktop/test/unit/src/components/email-detail/useEmailDetail.composer-drafts.test.tsx +++ b/apps/desktop/test/unit/src/components/email-detail/useEmailDetail.composer-drafts.test.tsx @@ -92,6 +92,7 @@ type Restore = { htmlContent: string; attachments: unknown[]; draftMessageId: string; + pgpUnlock?: { encrypt: boolean; sign: boolean }; }; const baseState = () => ({ @@ -367,6 +368,25 @@ describe('useEmailDetail — the forward composer\'s seed', () => { expect(ctx().inlineForwardDraft?.to).toBe('carol@acme.example'); }); + // Breaks: a reply or forward whose send was refused for a locked signing key + // reopens without the unlock prompt (and with other encrypt/sign toggles); + // an ordinary Undo restore must not gain one. + it('hands a reply or forward refused for a locked key its unlock request, and an Undo restore none', async () => { + state.restoreDraft = { ...restored('forward', A), pgpUnlock: { encrypt: true, sign: true } }; + await mount(); + expect(ctx().inlineForwardDraft?.pgpUnlock).toEqual({ encrypt: true, sign: true }); + mounted!.unmount(); + + state = { ...baseState(), restoreDraft: { ...restored('reply', A), pgpUnlock: { encrypt: false, sign: true } } }; + await mount(); + expect(ctx().inlineReplyDraft?.pgpUnlock).toEqual({ encrypt: false, sign: true }); + mounted!.unmount(); + + state = { ...baseState(), restoreDraft: restored('reply', A) }; + await mount(); + expect(ctx().inlineReplyDraft).not.toHaveProperty('pgpUnlock'); + }); + // THE regression: closing the forward left its draft behind, and the next // forward — of any message — opened on it. it('drops the draft when the forward closes', async () => { diff --git a/apps/desktop/test/unit/src/components/inline-composer-pgp-unlock.test.tsx b/apps/desktop/test/unit/src/components/inline-composer-pgp-unlock.test.tsx new file mode 100644 index 00000000..9956385e --- /dev/null +++ b/apps/desktop/test/unit/src/components/inline-composer-pgp-unlock.test.tsx @@ -0,0 +1,115 @@ +// @vitest-environment happy-dom +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: an inline reply or forward, reopened in the +// thread because main refused its send for a locked signing key, gives no way +// to unlock — or tells causes apart when an unlock fails (CASA 4.1.4) — or, +// once unlocked, Send does not go out with the encrypt/sign it was sent with. + +const h = vi.hoisted(() => ({ + send: vi.fn(), pgp: vi.fn(), listOwnKeys: vi.fn(), unlock: vi.fn(), signingKeyLocked: vi.fn(), failure: vi.fn(), + pgpState: null as Record | null, +})); +vi.mock('../../../../src/store/email-store', async () => { + const { create } = await import('zustand'); + return { useEmailStore: create(() => ({ accounts: [], activeAccountId: null, viewAccountId: null, + selectedVirtualFolder: null, imapConfig: null, sendEmail: h.send })) }; +}); +vi.mock('../../../../src/hooks/useDraftAutosave', () => ({ useDraftAutosave: () => ({ markDiscarded: vi.fn(), closeAction: vi.fn() }) })); +vi.mock('../../../../src/hooks/useCloseComposePrompt', () => ({ useCloseComposePrompt: () => ({ requestClose: vi.fn(), isAsking: () => false, closePromptDialog: null }) })); +vi.mock('../../../../src/hooks/useForwardAttachments', () => ({ useForwardAttachments: () => ({ blocked: false, prepareAttachments: async (files: unknown) => files }) })); +vi.mock('../../../../src/hooks/usePgpCompose', () => ({ + usePgpCompose: (...args: unknown[]) => { h.pgp(...args); return { state: h.pgpState ?? { encrypt: false, request: args[3], downgrade: false } }; }, +})); +vi.mock('../../../../src/utils/send-failure', () => ({ reportSendFailure: h.failure })); +vi.mock('../../../../src/services/ai-service', () => ({ getDefaultProvider: () => undefined })); +vi.mock('../../../../src/utils/attachment-reminder', () => ({ checkAttachmentBeforeSend: async () => true })); +vi.mock('../../../../src/components/RichTextEditor', () => ({ RichTextEditor: () => null })); +vi.mock('../../../../src/components/ComposeToolbar', () => ({ ComposeToolbar: ({ onSend }: { onSend: () => void }) => })); +vi.mock('../../../../src/components/SmtpNotConfiguredBanner', () => ({ SmtpNotConfiguredBanner: () => null })); +vi.mock('../../../../src/components/FromAccountBar', () => ({ FromAccountBar: () => null })); +vi.mock('../../../../src/components/ForwardAttachmentStatus', () => ({ ForwardAttachmentStatus: () => null })); +vi.mock('../../../../src/components/PolishModal', () => ({ PolishModal: () => null })); +vi.mock('../../../../src/components/SandboxedEmailBody', () => ({ SandboxedEmailBody: () => null })); +vi.mock('../../../../src/components/SelectionPolishMenu', () => ({ SELECTION_MENU_WIDTH: 200, SelectionPolishMenu: () => null })); +vi.mock('../../../../src/components/EmailInput', () => ({ EmailInput: () => null })); + +import { PGP_LOCKED_TITLE, PGP_UNLOCK_TO_SIGN } from '../../../../src/components/email-detail/pgp-view-model'; +import { InlineForward } from '../../../../src/components/InlineForward'; +import { InlineReply } from '../../../../src/components/InlineReply'; +import { useEmailStore } from '../../../../src/store/email-store'; +import type { StoredAccount } from '../../../../src/store/types'; +import type { ForwardSource } from '../../../../src/utils/forward-quote'; +import type { ReplySource } from '../../../../src/utils/reply-source'; +import { act, cleanup, fire, render, settle, typeInto } from '../../../helpers/render'; + +const home = { id: 'home', email: 'me@home.test', identities: ['me@home.test'] } as StoredAccount; +const incoming: ReplySource & ForwardSource = { id: 'incoming', accountId: 'home', messageId: '', threadId: 'thread', + subject: 'Plan', fromAddress: 'client@example.test', fromName: 'Client', toAddress: 'me@home.test', ccAddress: null, + date: 100, cleanBody: 'The plan.', rawBody: '

The plan.

' } as ReplySource & ForwardSource; +const RESTORED = { to: 'client@example.test', cc: '', htmlContent: '

Agreed.

', attachments: [], pgpUnlock: { encrypt: true, sign: true } }; + +beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + h.pgpState = null; + h.send.mockResolvedValue(undefined); + h.listOwnKeys.mockResolvedValue({ success: true, data: [{ fingerprint: 'A', unlocked: false }] }); + h.signingKeyLocked.mockResolvedValue({ success: true, data: false }); + (window as unknown as { electronAPI: unknown }).electronAPI = { pgp: { listOwnKeys: h.listOwnKeys, unlock: h.unlock, signingKeyLocked: h.signingKeyLocked } }; + useEmailStore.setState({ accounts: [home], activeAccountId: 'home', viewAccountId: null, imapConfig: { username: home.email }, selectedVirtualFolder: null }); +}); +afterEach(cleanup); + +const composers = [ + ['InlineReply', (draft?: object) => ], + ['InlineForward', (draft?: object) => ], +] as const; + +describe.each(composers)('%s reopened for a locked signing key', (_name, composer) => { + const prompt = (view: ReturnType) => view.find('[data-pgp-send-unlock]'); + const submitPassphrase = async (view: ReturnType, passphrase: string) => { + typeInto(view.byLabel('Key passphrase'), passphrase); + await act(async () => prompt(view)!.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))); + await settle(); + }; + + // Breaks: no unlock prompt, a cause-specific failure text, no retry, or a send without the restored toggles. + it('shows the unlock prompt, keeps it for a retry, and sends with the restored toggles once unlocked', async () => { + h.unlock.mockResolvedValueOnce({ success: false, error: PGP_FAILURE_MESSAGE }).mockResolvedValueOnce({ success: true }); + h.signingKeyLocked.mockResolvedValueOnce({ success: true, data: true }).mockResolvedValueOnce({ success: true, data: false }); + const view = render(composer(RESTORED)); + expect(prompt(view)?.textContent).toContain(PGP_LOCKED_TITLE); + expect(prompt(view)?.textContent).toContain(PGP_UNLOCK_TO_SIGN); + expect(h.pgp.mock.lastCall?.[3]).toEqual({ encrypt: true, sign: true }); + + await submitPassphrase(view, 'wrong'); + expect(prompt(view)?.textContent).toContain(PGP_FAILURE_MESSAGE); + await submitPassphrase(view, 'right'); + // Re-checked for the account address this composer sends as. + expect(h.signingKeyLocked).toHaveBeenLastCalledWith('me@home.test'); + expect(prompt(view)).toBeNull(); + + fire(view.all('button').find((button) => button.textContent === 'Send') ?? null, 'click'); + await settle(); + expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ pgp: { encrypt: true, sign: true } })); + }); + + // Breaks: encryption asked for but not deliverable goes out in plaintext. + it('refuses to send while encryption was asked for but cannot be carried', async () => { + h.pgpState = { encrypt: false, request: undefined, downgrade: true }; + const view = render(composer(RESTORED)); + fire(view.all('button').find((button) => button.textContent === 'Send') ?? null, 'click'); + await settle(); + expect(h.send).not.toHaveBeenCalled(); + expect(h.failure).toHaveBeenCalledWith(expect.objectContaining({ message: PGP_FAILURE_MESSAGE })); + }); + + // Breaks: the prompt shows on a composer nobody refused. + it('shows no prompt for an ordinary draft', () => { + const view = render(composer({ to: 'client@example.test', cc: '', htmlContent: '

Hi

', attachments: [] })); + expect(prompt(view)).toBeNull(); + expect(h.pgp.mock.lastCall?.[3]).toBeUndefined(); + }); +}); diff --git a/apps/desktop/test/unit/src/components/settings/EncryptionTab.test.tsx b/apps/desktop/test/unit/src/components/settings/EncryptionTab.test.tsx index a19173de..20661664 100644 --- a/apps/desktop/test/unit/src/components/settings/EncryptionTab.test.tsx +++ b/apps/desktop/test/unit/src/components/settings/EncryptionTab.test.tsx @@ -1,7 +1,9 @@ // @vitest-environment happy-dom +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; import { act } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { IMPORT_PASSPHRASE_HINT, UNLOCK_HINT } from '../../../../../src/components/settings/encryption-view'; import { EncryptionTab } from '../../../../../src/components/settings/EncryptionTab'; import type { AppSettings } from '../../../../../src/components/settings/types'; import type { SecureStorageStatus } from '../../../../../src/types/secure-storage'; @@ -58,6 +60,8 @@ const contactKey = { const ok = (data: T) => ({ success: true as const, data }); const fail = (error: string) => ({ success: false as const, error }); +/** What main answers for every OpenPGP failure, with a prompt code when there is one. */ +const pgpFail = (code?: 'locked' | 'passphrase-required') => ({ success: false as const, error: PGP_FAILURE_MESSAGE, ...(code ? { code } : {}) }); const api = { status: vi.fn(), @@ -181,16 +185,17 @@ describe('EncryptionTab', () => { expect(view.find(`[data-own-key="${FP}"]`)?.textContent).not.toContain('Saved with encryption'); }); - // Breaks: a failing key list reads as "no keys" with no hint anything went wrong. + // Changed deliberately (CASA 4.1.4): a rejected bridge used to show its own text ("IPC gone"). + // Breaks: a failing key list reads as "no keys" with no hint anything went wrong, or a rejection's text reaches the screen. it('shows a list failure, and a rejected bridge', async () => { - api.listOwnKeys.mockResolvedValue(fail('Keyring unreadable')); + api.listOwnKeys.mockResolvedValue(pgpFail()); const view = await mount(); - expect(view.find('[role="alert"]')?.textContent).toBe('Keyring unreadable'); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); view.unmount(); api.status.mockRejectedValue(new Error('IPC gone')); mounted = await mount(); - expect(mounted.find('[role="alert"]')?.textContent).toBe('IPC gone'); + expect(mounted.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); expect(mounted.container.textContent).toContain('You have no OpenPGP key yet'); }); @@ -251,9 +256,10 @@ describe('EncryptionTab', () => { expect(textarea.value).toBe(''); }); - // Breaks: a failed import wipes what the user pasted, or a non-Error rejection shows nothing. + // Changed deliberately (CASA 4.1.4): a rejected import used to show the rejection itself ("boom"). + // Breaks: a failed import wipes what the user pasted, or a non-Error rejection shows nothing — or shows its own text. it('keeps the pasted key when the import fails', async () => { - api.importOwnKey.mockResolvedValueOnce(ok([ownKey()])).mockResolvedValueOnce(fail('Not a key')).mockRejectedValueOnce('boom'); + api.importOwnKey.mockResolvedValueOnce(ok([ownKey()])).mockResolvedValueOnce(pgpFail()).mockRejectedValueOnce('boom'); const view = await mount(); const textarea = view.byLabel('Paste your private key') as HTMLTextAreaElement; typeInto(textarea, 'KEY'); @@ -262,10 +268,44 @@ describe('EncryptionTab', () => { expect(view.find('[role="status"]')?.textContent).toBe('Imported your key'); typeInto(textarea, 'JUNK'); await submit(formOf(textarea)); - expect(view.find('[role="alert"]')?.textContent).toBe('Not a key'); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); expect(textarea.value).toBe('JUNK'); + // No prompt code: no passphrase hint either. + expect(view.find('[data-passphrase-hint]')).toBeNull(); await submit(formOf(textarea)); - expect(view.find('[role="alert"]')?.textContent).toBe('boom'); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); + }); + + // Breaks: importing a protected key without its passphrase (or any key + // where there is no keychain) fails with no hint that a passphrase is the + // way through, or the hint stays after the import worked. + it('asks for a passphrase when main says one is needed, with fixed guidance', async () => { + api.importOwnKey.mockResolvedValueOnce(pgpFail('passphrase-required')).mockResolvedValueOnce(ok([ownKey()])); + const view = await mount(); + const textarea = view.byLabel('Paste your private key') as HTMLTextAreaElement; + typeInto(textarea, 'PROTECTED KEY'); + await submit(formOf(textarea)); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); + expect(view.find('[data-passphrase-hint]')?.textContent).toBe(IMPORT_PASSPHRASE_HINT); + expect(textarea.value).toBe('PROTECTED KEY'); + typeInto(view.byLabel('Its passphrase, if it has one'), 'pw'); + await submit(formOf(textarea)); + expect(api.importOwnKey).toHaveBeenLastCalledWith('PROTECTED KEY', 'pw'); + expect(view.find('[data-passphrase-hint]')).toBeNull(); + }); + + // Breaks: a create refused for want of a passphrase (the keychain check said + // none was needed, main found no keychain) leaves the user no field to give one. + it('shows the passphrase field when main says a new key needs one', async () => { + api.generateKey.mockResolvedValueOnce(pgpFail('passphrase-required')).mockResolvedValueOnce(ok(ownKey())); + const view = await mount(); + expect(view.byLabel('Passphrase for the new key')).toBeNull(); + await submit(formOf(buttonNamed(view, 'Create key'))); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); + expect((buttonNamed(view, 'Create key') as HTMLButtonElement).disabled).toBe(true); + typeInto(view.byLabel('Passphrase for the new key'), 'secret'); + await submit(formOf(buttonNamed(view, 'Create key'))); + expect(api.generateKey).toHaveBeenLastCalledWith({ name: '', email: 'me@work.example', passphrase: 'secret' }); }); // Breaks: a key file cannot be picked, or an unreadable file fails silently. @@ -303,17 +343,20 @@ describe('EncryptionTab', () => { expect(view.find('[role="status"]')?.textContent).toBe('Imported 2 keys'); }); - // Breaks: a locked key cannot be unlocked from Settings, or the form never closes. + // Changed deliberately (CASA 4.1.4): main used to answer a wrong passphrase with "Wrong passphrase". + // Breaks: a locked key cannot be unlocked from Settings, a wrong passphrase + // gives no chance to retry, or the form never closes. it('unlocks a locked key with its passphrase', async () => { api.listOwnKeys.mockResolvedValue(ok([ownKey({ protection: 'passphrase', unlocked: false })])); - api.unlock.mockResolvedValueOnce(fail('Wrong passphrase')).mockResolvedValueOnce(ok(undefined)); + api.unlock.mockResolvedValueOnce(pgpFail()).mockResolvedValueOnce(ok(undefined)); const view = await mount(); expect(view.find(`[data-own-key="${FP}"]`)?.textContent).toContain('Locked'); await click(buttonNamed(view, 'Unlock')); const field = view.byLabel('Passphrase of this key'); + expect(view.container.textContent).toContain(UNLOCK_HINT); typeInto(field, 'wrong'); await submit(formOf(field)); - expect(view.find('[role="alert"]')?.textContent).toBe('Wrong passphrase'); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); expect(view.byLabel('Passphrase of this key')).not.toBeNull(); typeInto(view.byLabel('Passphrase of this key'), 'right'); await submit(formOf(view.byLabel('Passphrase of this key'))); @@ -339,6 +382,44 @@ describe('EncryptionTab', () => { expect(view.find('[role="status"]')?.textContent).toBe('Backup saved to /keys/me.asc'); }); + // Breaks: backing up a key that is locked this session fails with no way + // forward — main's 'locked' must swap the backup form for the unlock form, + // fresh (the backup passphrase typed so far must not become the unlock try). + it('offers to unlock a locked key whose backup was refused, then backs it up', async () => { + api.listOwnKeys.mockResolvedValue(ok([ownKey({ protection: 'passphrase', unlocked: false })])); + api.exportOwnKey.mockResolvedValueOnce(pgpFail('locked')).mockResolvedValueOnce(ok({ saved: true, filePath: '/keys/me.asc' })); + api.unlock.mockResolvedValue(ok(undefined)); + const view = await mount(); + await click(buttonNamed(view, 'Back up secret key')); + typeInto(view.byLabel('Passphrase for the backup file'), 'backup-pw'); + await submit(formOf(view.byLabel('Passphrase for the backup file'))); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); + expect(view.byLabel('Passphrase for the backup file')).toBeNull(); + const unlockField = view.byLabel('Passphrase of this key') as HTMLInputElement; + expect(unlockField.value).toBe(''); + expect(view.container.textContent).toContain(UNLOCK_HINT); + + typeInto(unlockField, 'key-pw'); + await submit(formOf(unlockField)); + expect(api.unlock).toHaveBeenCalledWith(FP, 'key-pw'); + await click(buttonNamed(view, 'Back up secret key')); + typeInto(view.byLabel('Passphrase for the backup file'), 'backup-pw'); + await submit(formOf(view.byLabel('Passphrase for the backup file'))); + expect(view.find('[role="status"]')?.textContent).toBe('Backup saved to /keys/me.asc'); + }); + + // Breaks: a backup failure that is not a prompt opens a form it did not ask for, or closes the backup form. + it('keeps the backup form after a failure with no prompt code', async () => { + api.exportOwnKey.mockResolvedValue(pgpFail()); + const view = await mount(); + await click(buttonNamed(view, 'Back up secret key')); + typeInto(view.byLabel('Passphrase for the backup file'), 'backup-pw'); + await submit(formOf(view.byLabel('Passphrase for the backup file'))); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); + expect(view.byLabel('Passphrase for the backup file')).not.toBeNull(); + expect(view.byLabel('Passphrase of this key')).toBeNull(); + }); + // Breaks: exporting the public key does nothing, or a cancelled save claims success. it('exports the public key, and says nothing when the save is cancelled', async () => { api.exportPublicKey.mockResolvedValueOnce(ok({ saved: true, filePath: '/keys/pub.asc' })).mockResolvedValueOnce(ok({ saved: false })); @@ -376,6 +457,7 @@ describe('EncryptionTab', () => { expect(view.find('[role="status"]')?.textContent).toBe('Key deleted'); }); + // Changed deliberately (CASA 4.1.4): a rejected removal used to show its own text ("bridge down"). // Breaks: a contact's key cannot be removed, or a rejected removal leaves the tab stuck busy. it('removes a contact’s key after confirming, and recovers from a rejection', async () => { api.deleteContactKey.mockRejectedValueOnce(new Error('bridge down')).mockResolvedValueOnce(ok(true)); @@ -384,7 +466,7 @@ describe('EncryptionTab', () => { await click(remove()); await click([...(view.find('[role="dialog"]')?.querySelectorAll('button') ?? [])].find((button) => button.textContent === 'Remove') ?? null); expect(api.deleteContactKey).toHaveBeenCalledWith('gee@example.org', 'B'.repeat(40)); - expect(view.find('[role="alert"]')?.textContent).toBe('bridge down'); + expect(view.find('[role="alert"]')?.textContent).toBe(PGP_FAILURE_MESSAGE); expect((remove() as HTMLButtonElement).disabled).toBe(false); }); diff --git a/apps/desktop/test/unit/src/components/settings/OutboxTab.test.tsx b/apps/desktop/test/unit/src/components/settings/OutboxTab.test.tsx index b16f9cb0..42cabe93 100644 --- a/apps/desktop/test/unit/src/components/settings/OutboxTab.test.tsx +++ b/apps/desktop/test/unit/src/components/settings/OutboxTab.test.tsx @@ -1,4 +1,5 @@ // @vitest-environment happy-dom +import { PGP_UNLOCK_THEN_RETRY_MESSAGE } from '@sarvinbox/core/pgp-failure'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { OutboxTab } from '../../../../../src/components/settings/OutboxTab'; @@ -238,6 +239,21 @@ describe('OutboxTab delivered rows', () => { expect(view.container.textContent).toContain('Failed'); view.unmount(); }); + + // Breaks: a queued send that met an OpenPGP key locked this session (a + // scheduled send after a restart) dead-ends with nothing saying the fix — + // main stores the fixed "unlock, then retry" text as the row's error, and + // Retry must send it once the key is unlocked. + it('shows a send refused for a locked key with what to do, and retries it', async () => { + api.outbox.retry.mockResolvedValueOnce({ success: true, data: { outcome: 'sent', connected: true, lastError: null } } as never); + const view = await show([row({ status: 'failed', lastError: PGP_UNLOCK_THEN_RETRY_MESSAGE })]); + expect(view.container.textContent).toContain('Unlock your key in Settings → Encryption, then retry.'); + fire(view.byLabel('Retry send'), 'click'); + await settle(); + expect(api.outbox.retry).toHaveBeenCalledWith(21); + expect(view.container.textContent).toContain('Message sent.'); + view.unmount(); + }); }); describe('OutboxTab preview', () => { diff --git a/apps/desktop/test/unit/src/hooks/usePgpCompose.test.tsx b/apps/desktop/test/unit/src/hooks/usePgpCompose.test.tsx index 0f71970b..bd444259 100644 --- a/apps/desktop/test/unit/src/hooks/usePgpCompose.test.tsx +++ b/apps/desktop/test/unit/src/hooks/usePgpCompose.test.tsx @@ -16,8 +16,8 @@ const api = { resolveRecipients: vi.fn(), }; -function Probe({ from, recipients, reply = false }: { from?: string; recipients: string[]; reply?: boolean }) { - const { state, toggleEncrypt, toggleSign } = usePgpCompose(from, recipients, reply); +function Probe({ from, recipients, reply = false, restored }: { from?: string; recipients: string[]; reply?: boolean; restored?: { encrypt: boolean; sign: boolean } }) { + const { state, toggleEncrypt, toggleSign } = usePgpCompose(from, recipients, reply, restored); return (
+
+ + ); +} diff --git a/apps/desktop/src/components/security/Security.tsx b/apps/desktop/src/components/security/Security.tsx index 3609227f..40490f29 100644 --- a/apps/desktop/src/components/security/Security.tsx +++ b/apps/desktop/src/components/security/Security.tsx @@ -23,6 +23,7 @@ import { Tooltip } from '../Tooltip'; import { BlocklistsTab } from './BlocklistsTab'; import { CredentialStorageStatus } from './CredentialStorageStatus'; +import { RememberedLinkSites } from './RememberedLinkSites'; import { TrustedSendersPanel } from './TrustedSendersPanel'; type SecurityTab = 'overview' | 'links' | 'senders' | 'images' | 'identity' | 'blocklists' | 'spam'; @@ -103,7 +104,7 @@ export function Security({ initialTab }: { initialTab?: SecurityTab } = {}) { const PROTECTIONS: Array<{ title: string; detail: string }> = [ { title: 'Isolated message rendering', detail: 'Every email body renders inside a sandboxed frame. Scripts, stylesheets, fonts and imports are stripped before it loads.' }, - { title: 'Links open in your browser', detail: 'Clicking a link never navigates inside the app — it hands the address to your system browser with referrer and opener stripped.' }, + { title: 'Links open in your browser', detail: 'Clicking a link never navigates inside the app — it hands the address to your system browser with referrer and opener stripped. Before a link opens a site the app did not put there, a warning names the site, unless you chose “Don’t ask again” for it (Trusted & blocked links).' }, { title: 'Sender authentication', detail: 'SPF, DKIM and DMARC verdicts are read from the receiving server’s Authentication-Results header and shown on the shield beside each sender.' }, { title: 'Impersonation checks', detail: 'A display name that names one domain while the message came from another, and links whose text says one domain while pointing to another, are flagged.' }, { title: 'Brand verification (BIMI)', detail: 'A sender domain’s published logo is shown only on mail that passed DMARC, and the blue verified tick only when its Verified Mark Certificate chains to a pinned Mark Verifying Authority for that exact logo and domain. Details per domain under Sender identity.' }, @@ -313,6 +314,7 @@ function LinksTab() { onRevoke={revoke} revokeLabel="Unblock" /> +
); } diff --git a/apps/desktop/src/components/settings/AccountRemovalNotes.tsx b/apps/desktop/src/components/settings/AccountRemovalNotes.tsx index 200b27cc..c2a32b5b 100644 --- a/apps/desktop/src/components/settings/AccountRemovalNotes.tsx +++ b/apps/desktop/src/components/settings/AccountRemovalNotes.tsx @@ -8,15 +8,20 @@ * user is pointed at the pages where they can do it themselves. A password * account keeps nothing but the password. */ +import { + GOOGLE_PERMISSIONS_URL, + MICROSOFT_PERSONAL_CONSENT_URL, + MICROSOFT_WORK_APPS_URL, +} from '@sarvinbox/core/app-links'; import { X } from 'lucide-react'; import type { ReactNode } from 'react'; import { openExternalLink } from '../../utils/open-external'; import { Tooltip } from '../Tooltip'; -export const MICROSOFT_PERSONAL_CONSENT_URL = 'https://account.live.com/consent/Manage'; -export const MICROSOFT_WORK_APPS_URL = 'https://myapps.microsoft.com'; -export const GOOGLE_PERMISSIONS_URL = 'https://myaccount.google.com/permissions'; +// The addresses live on the app-links list, which main's external-link gate +// opens without a warning; re-exported under the names this module always had. +export { GOOGLE_PERMISSIONS_URL, MICROSOFT_PERSONAL_CONSENT_URL, MICROSOFT_WORK_APPS_URL }; const linkClass = 'font-medium text-primary underline underline-offset-2 hover:text-primary/80'; diff --git a/apps/desktop/src/components/settings/ai/AgentTab.tsx b/apps/desktop/src/components/settings/ai/AgentTab.tsx index 9ddbd9de..98628fe0 100644 --- a/apps/desktop/src/components/settings/ai/AgentTab.tsx +++ b/apps/desktop/src/components/settings/ai/AgentTab.tsx @@ -1,3 +1,4 @@ +import { TAVILY_HOME_URL } from '@sarvinbox/core/app-links'; import { Bot, Shield, Brain, AlertTriangle, Globe, Key, FileText, RotateCcw, Save, Check, Eye, Zap, PenLine, FlaskConical, LayoutDashboard, @@ -347,7 +348,7 @@ export function AgentTab({ aiProviders }: AgentTabProps) { Enter your Tavily API key.{' '} -
+ Get a free key at tavily.com {' '} (1,000 searches/month free). diff --git a/apps/desktop/src/services/ai-service.ts b/apps/desktop/src/services/ai-service.ts index 607a23c9..8047efa5 100644 --- a/apps/desktop/src/services/ai-service.ts +++ b/apps/desktop/src/services/ai-service.ts @@ -5,6 +5,7 @@ import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; import { stripHtmlTags } from '@sarvinbox/core/html-text'; import { fieldSizesForLog } from '@sarvinbox/core/log-text'; import { createLogger } from '@sarvinbox/core/logger'; +import { truncateMiddle } from '@sarvinbox/core/truncate-middle'; // Canonical AI feature defaults live in settings/types (a types+consts // leaf module — safe to import here, no component code, no cycle). @@ -111,16 +112,6 @@ export function htmlToPlainTextForPrompt(html: string): string { .trim(); } -/** Cap a string by cutting the middle out, keeping head and tail. */ -function truncateMiddle(text: string, maxChars: number): string { - if (text.length <= maxChars) return text; - const marker = ' […] '; - const keep = Math.max(maxChars - marker.length, 2); - const head = Math.ceil(keep / 2); - const tail = keep - head; - return text.slice(0, head).trimEnd() + marker + text.slice(text.length - tail).trimStart(); -} - /** * Get the current user's email address (for "(you)" labeling and reply UIs). * Priority: IMAP credentials username > profile email > caller fallback. diff --git a/apps/desktop/src/utils/open-external.ts b/apps/desktop/src/utils/open-external.ts index a19c1640..a85970fb 100644 --- a/apps/desktop/src/utils/open-external.ts +++ b/apps/desktop/src/utils/open-external.ts @@ -31,8 +31,11 @@ export function opensExternally(url: string): boolean { /** * Open a web link from a message outside the app: the system browser in - * Electron (the main process re-checks the scheme against its allow-list), a - * new tab anywhere else. A link `opensExternally` refuses opens nothing. + * Electron, a new tab anywhere else. A link `opensExternally` refuses opens + * nothing. In Electron the main process's external-link gate decides, not this + * function: it re-checks the scheme and, unless the link is one the app wrote + * or a site the user chose "Don't ask again" for, shows a warning naming the + * host first. * * A module-level function, so its identity never changes — the chat library * re-attaches its frame listeners only when a frame loads, and a link handler diff --git a/apps/desktop/src/utils/translate.ts b/apps/desktop/src/utils/translate.ts new file mode 100644 index 00000000..db35f1d3 --- /dev/null +++ b/apps/desktop/src/utils/translate.ts @@ -0,0 +1,27 @@ +import { TRANSLATE_MAX_CHARS } from '@sarvinbox/core/app-links'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; +import { createLogger } from '@sarvinbox/core/logger'; + +const log = createLogger('translate'); + +/** The language the Translate menu item translates into. */ +export const TRANSLATE_TARGET_LANGUAGE = 'en'; + +/** + * The Translate menu item. Only WHAT to translate crosses to main — the + * message's text, cut to TRANSLATE_MAX_CHARS, and the target language. Main + * builds the Google Translate address itself and opens it without the link + * warning, because the user chose the app's own command. No URL is built here: + * the renderer cannot choose where the browser goes. + */ +export function openTranslation(email: { cleanBody?: unknown; rawBody?: unknown } | null | undefined): void { + if (!email) return; + const body = email.cleanBody || email.rawBody || ''; + const text = typeof body === 'string' ? body : ''; + window.electronAPI.app + .openTranslation(text.substring(0, TRANSLATE_MAX_CHARS), TRANSLATE_TARGET_LANGUAGE) + .catch((error: unknown) => { + // The failure's kind only: nothing of the message's text. + log.warn('Translate could not be opened:', errorDiagnostic(error)); + }); +} diff --git a/apps/desktop/test/unit/electron/external-link-paths.test.ts b/apps/desktop/test/unit/electron/external-link-paths.test.ts new file mode 100644 index 00000000..de2996ea --- /dev/null +++ b/apps/desktop/test/unit/electron/external-link-paths.test.ts @@ -0,0 +1,85 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join, relative, sep } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +/** + * Every place the main process hands a URL to the OS (CASA 5.1.2) — a source + * guard over electron/**, because "nothing else calls shell.openExternal" is a + * property of the whole tree, not of one module. + * + * What breaks if this file fails: a new path opens an address the app did not + * write (a link from a message, a header, an extension, a provider) straight + * through `shell.openExternal`, skipping the external-link gate and its + * warning. Route it through `openExternalUrl` (services/external-link-gate.ts) + * instead. Adding a file to the list below needs the same justification as the + * ones already there: the app builds the whole address itself. + */ + +const ELECTRON = join(__dirname, '../../../electron'); + +/** The files allowed to call shell.openExternal, and why the address is the app's own. */ +const ALLOWED: Record = { + 'services/external-link-gate.ts': 'the gate itself', + 'services/oauth-service.ts': 'the mail sign-in authorization URL, built from the provider registry', + 'services/antivirus-onboarding.ts': 'the scanner sign-in authorization URL, built by antivirus-oauth-service', + 'services/default-app-service.ts': "the OS's own default-apps settings page (ms-settings:, x-apple.systempreferences:)", +}; + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = join(dir, entry.name); + if (entry.isDirectory()) return entry.name === '__testing__' ? [] : sourceFiles(path); + return /\.(ts|mts|cts)$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [path] : []; + }); +} + +/** The file with comments removed, so prose about shell.openExternal cannot match. */ +function code(file: string): string { + return readFileSync(file, 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .split('\n') + .map((line) => line.replace(/(^|[^:])\/\/.*$/, '$1')) + .join('\n'); +} + +const OPENS = /\bshell\s*\.\s*openExternal\b|\bopenExternal\s*[:=]\s*shell\b|\{\s*[^}]*\bopenExternal\b[^}]*\}\s*=\s*shell\b/; + +describe('URLs leaving the main process', () => { + // THE guard: no file outside the list hands a URL to the OS directly. + it('reach shell.openExternal only through the gate or an address the app builds itself', () => { + const offenders = sourceFiles(ELECTRON) + .filter((file) => OPENS.test(code(file))) + .map((file) => relative(ELECTRON, file).split(sep).join('/')); + expect(offenders.sort()).toEqual(Object.keys(ALLOWED).sort()); + }); + + // Breaks: the guard silently stops seeing the tree (a moved folder), and + // passes because it read nothing. + it('actually reads the main-process sources', () => { + const files = sourceFiles(ELECTRON).map((file) => relative(ELECTRON, file).split(sep).join('/')); + expect(files).toContain('main.ts'); + expect(files).toContain('ipc/app-handlers.ts'); + expect(files).toContain('ipc/unsubscribe-handlers.ts'); + expect(files.length).toBeGreaterThan(100); + }); + + // Breaks: an address the app did not build (from mail, the renderer, an + // extension) is opened through the no-warning app-built path. Only the + // Translate handler may call it, with the URL main builds from the text. + it('opens an app-built address (no warning) only from the Translate handler', () => { + const callers = sourceFiles(ELECTRON) + .filter((file) => /\bopenAppBuiltUrl\(/.test(code(file))) + .map((file) => relative(ELECTRON, file).split(sep).join('/')); + expect(callers.sort()).toEqual(['ipc/app-handlers.ts', 'services/external-link-gate.ts']); + const handlers = code(join(ELECTRON, 'ipc/app-handlers.ts')); + expect(handlers.match(/\bopenAppBuiltUrl\(/g)).toHaveLength(1); + expect(handlers).toContain('const url = translationUrl(text, targetLanguage);'); + expect(handlers).toContain('await openAppBuiltUrl(url)'); + }); + + // Breaks: the renderer-facing paths stop going through the gate. + it.each(['ipc/app-handlers.ts', 'ipc/unsubscribe-handlers.ts', 'main.ts'])('%s opens through openExternalUrl', (file) => { + expect(code(join(ELECTRON, file))).toMatch(/\bopenExternalUrl\(/); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/app-handlers-open-external.test.ts b/apps/desktop/test/unit/electron/ipc/app-handlers-open-external.test.ts index 955317de..da48e07b 100644 --- a/apps/desktop/test/unit/electron/ipc/app-handlers-open-external.test.ts +++ b/apps/desktop/test/unit/electron/ipc/app-handlers-open-external.test.ts @@ -1,20 +1,27 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -// `app:openExternal` is the one choke point for handing a URL to the OS; the -// URL is typically a link clicked in a message. Its refusal line is warn, which -// a release app.log keeps. What breaks if this file fails: a refused link's -// address (its host, path and query, from the mail) reaches app.log, or a safe -// link stops opening. +// `app:openExternal` is how the renderer hands a URL to the OS; the URL is +// typically a link clicked in a message. It goes through the external-link +// gate, whose refusal line is warn, which a release app.log keeps. What breaks +// if this file fails: a refused link's address (its host, path and query, from +// the mail) reaches app.log; a link from a message opens without the warning +// (CASA 5.1.2) or the renderer can skip it; the app's own links start asking; +// or the Security page's count / "Forget all" stop working. const h = vi.hoisted(() => ({ handlers: new Map any>(), warn: vi.fn(), + info: vi.fn(), openExternal: vi.fn(async (_url: string) => {}), + showMessageBox: vi.fn(async (..._args: unknown[]) => ({ response: 1, checkboxChecked: false })), + fromWebContents: vi.fn((_contents: unknown): unknown => null), })); vi.mock('electron', () => ({ ipcMain: { handle: (n: string, fn: (...a: any[]) => any) => h.handlers.set(n, fn) }, shell: { openExternal: (url: string) => h.openExternal(url) }, + dialog: { showMessageBox: (...args: unknown[]) => h.showMessageBox(...args) }, + BrowserWindow: { fromWebContents: (contents: unknown) => h.fromWebContents(contents) }, })); // app-handlers reads the bundled package.json for the version at load time. vi.mock('fs', async () => { @@ -24,32 +31,44 @@ vi.mock('fs', async () => { }); vi.mock('@sarvinbox/core', async (importOriginal) => ({ ...(await importOriginal()), - createLogger: () => ({ info: () => {}, warn: h.warn, error: () => {}, debug: () => {} }), + createLogger: () => ({ info: h.info, warn: h.warn, error: () => {}, debug: () => {} }), })); vi.mock('../../../../electron/sentry', () => ({ crashReportChoice: () => 'unasked', setCrashReportsEnabled: () => {} })); +vi.mock('../../../../electron/services/core-db', async () => await import('../../../../electron/services/__testing__/fake-core-db')); import { registerAppHandlers } from '../../../../electron/ipc/app-handlers'; +import { resetFakeCoreDb, state as coreDb } from '../../../../electron/services/__testing__/fake-core-db'; +import { REMEMBERED_HOSTS_BLOB_KEY } from '../../../../electron/services/external-link-gate'; -const open = (url: unknown) => h.handlers.get('app:openExternal')!(null, url); +const WINDOW = { isDestroyed: () => false }; +const SENDER = { id: 1 }; +const open = (url: unknown) => h.handlers.get('app:openExternal')!({ sender: SENDER }, url); +const call = async (channel: string) => h.handlers.get(channel)!({ sender: SENDER }); beforeEach(() => { h.handlers.clear(); h.warn.mockReset(); + h.info.mockReset(); h.openExternal.mockReset().mockResolvedValue(undefined); + h.showMessageBox.mockReset().mockResolvedValue({ response: 1, checkboxChecked: false }); + h.fromWebContents.mockReset().mockReturnValue(WINDOW); + resetFakeCoreDb(); registerAppHandlers(); }); describe('app:openExternal — what reaches the log', () => { - // Breaks: '[App] Blocked openExternal for unsafe URL scheme: ' writes - // the whole link. + // Breaks: the refusal line writes the whole link. Changed deliberately: the + // scheme check moved from this handler into the external-link gate, which + // every path shares, so the line is the gate's. it('logs a refused link by its scheme only', async () => { await expect(open('file:///Users/SENTINEL-user/Payslip-SENTINEL.pdf')).resolves.toEqual({ success: false, error: 'Unsupported URL scheme' }); await expect(open('ms-word:ofe|u|https://SENTINEL.example/doc.docx')).resolves.toMatchObject({ success: false }); expect(h.openExternal).not.toHaveBeenCalled(); + expect(h.showMessageBox).not.toHaveBeenCalled(); expect(h.warn.mock.calls).toEqual([ - ['[App] Blocked openExternal for unsafe URL scheme:', 'file:'], - ['[App] Blocked openExternal for unsafe URL scheme:', 'ms-word:'], + ['[ExternalLink] Refused a link with an unsupported scheme:', 'file:'], + ['[ExternalLink] Refused a link with an unsupported scheme:', 'ms-word:'], ]); }); @@ -60,17 +79,150 @@ describe('app:openExternal — what reaches the log', () => { await open({ href: 'SENTINEL' }); expect(h.warn.mock.calls).toEqual([ - ['[App] Blocked openExternal for unsafe URL scheme:', 'unparseable'], - ['[App] Blocked openExternal for unsafe URL scheme:', 'not-a-string:object'], + ['[ExternalLink] Refused a link with an unsupported scheme:', 'unparseable'], + ['[ExternalLink] Refused a link with an unsupported scheme:', 'not-a-string:object'], ]); }); - // Breaks: the change to the log line stops safe links opening, or makes an - // allowed open write a line. - it('opens a safe link and logs nothing', async () => { - await expect(open('https://example.com/SENTINEL')).resolves.toEqual({ success: true }); + // Breaks: the app's own links (the Sarv logo) start asking, or an allowed + // open writes a line. + it('opens an app link without asking and logs nothing', async () => { + await expect(open('https://sarv.com')).resolves.toEqual({ success: true }); - expect(h.openExternal).toHaveBeenCalledWith('https://example.com/SENTINEL'); + expect(h.openExternal).toHaveBeenCalledWith('https://sarv.com/'); + expect(h.showMessageBox).not.toHaveBeenCalled(); expect(h.warn).not.toHaveBeenCalled(); + expect(h.info).not.toHaveBeenCalled(); + }); +}); + +describe('app:openExternal — the warning (CASA 5.1.2)', () => { + // Changed deliberately: a link to any other site used to open at once. It + // now asks first, attached to the window that sent the request, and Cancel + // (the default) opens nothing. + it('asks before a link from a message, in the sending window, and Cancel opens nothing', async () => { + await expect(open('https://example.com/SENTINEL')).resolves.toEqual({ success: false, cancelled: true }); + + expect(h.fromWebContents).toHaveBeenCalledWith(SENDER); + expect(h.showMessageBox).toHaveBeenCalledOnce(); + expect(h.showMessageBox.mock.calls[0][0]).toBe(WINDOW); + expect(h.showMessageBox.mock.calls[0][1]).toMatchObject({ type: 'warning', detail: expect.stringMatching(/^example\.com\n/) }); + expect(h.openExternal).not.toHaveBeenCalled(); + // The answer is logged by its booleans, never the address. + expect(JSON.stringify([...h.info.mock.calls, ...h.warn.mock.calls])).not.toContain('SENTINEL'); + expect(JSON.stringify([...h.info.mock.calls, ...h.warn.mock.calls])).not.toContain('example.com'); + }); + + // Breaks: "Open link" does not open the link. + it('opens the link when the user chooses Open link', async () => { + h.showMessageBox.mockResolvedValueOnce({ response: 0, checkboxChecked: false }); + await expect(open('https://example.com/page')).resolves.toEqual({ success: true }); + expect(h.openExternal).toHaveBeenCalledWith('https://example.com/page'); + }); + + // Breaks: the OS failing to open a link is reported with its message (which + // can quote the address), or rejects into the renderer. + it('answers a fixed error when the browser cannot be opened', async () => { + h.openExternal.mockRejectedValueOnce(new Error('Failed to open https://SENTINEL.example')); + await expect(open('https://sarv.com/')).resolves.toEqual({ success: false, error: 'The link could not be opened' }); + }); + + // Breaks: a second request while the warning is open stacks another dialog. + it('answers busy while a warning is already open in the window', async () => { + let release!: (answer: { response: number; checkboxChecked: boolean }) => void; + h.showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; })); + const first = open('https://example.com/1'); + await expect(open('https://example.com/2')).resolves.toEqual({ success: false, error: 'Another link is waiting for an answer' }); + release({ response: 1, checkboxChecked: false }); + await expect(first).resolves.toEqual({ success: false, cancelled: true }); + expect(h.showMessageBox).toHaveBeenCalledOnce(); + }); +}); + +describe('app:openTranslation — the Translate menu item', () => { + const translate = (text: unknown, target: unknown) => h.handlers.get('app:openTranslation')!({ sender: SENDER }, text, target); + + // Breaks: the app's own Translate command shows the link warning, or main + // opens a different address than the one it builds from the text. + it('opens the Google Translate page main builds, without a warning', async () => { + await expect(translate('Hallo Welt & SENTINEL', 'en')).resolves.toEqual({ success: true }); + expect(h.openExternal).toHaveBeenCalledExactlyOnceWith( + 'https://translate.google.com/?sl=auto&tl=en&text=Hallo%20Welt%20%26%20SENTINEL', + ); + expect(h.showMessageBox).not.toHaveBeenCalled(); + }); + + // THE boundary: the renderer cannot send its own address through here. + // Breaks: a URL, an oversized text or a smuggled target opens anything other + // than the Translate page with that text. + it('refuses non-string, oversized or malformed input, and never opens an address it was sent', async () => { + for (const [text, target] of [ + [{ url: 'https://evil.example/' }, 'en'], + [42, 'en'], + ['x'.repeat(5001), 'en'], + ['hello', 'en&u=https://evil.example/'], + ['hello', undefined], + ] as const) { + await expect(translate(text, target)).resolves.toEqual({ success: false, error: 'This message cannot be sent for translation' }); + } + expect(h.openExternal).not.toHaveBeenCalled(); + + await translate('https://evil.example/', 'en'); + expect(h.openExternal).toHaveBeenCalledExactlyOnceWith('https://translate.google.com/?sl=auto&tl=en&text=https%3A%2F%2Fevil.example%2F'); + }); + + // Breaks: the message's text reaches app.log on a refusal or an open. + it('never logs the text', async () => { + await translate('SENTINEL secret words', 'en'); + await translate(`SENTINEL ${'x'.repeat(5001)}`, 'en'); + await translate('SENTINEL', 'SENTINEL'); + const lines = JSON.stringify([...h.info.mock.calls, ...h.warn.mock.calls]); + expect(lines).not.toContain('SENTINEL'); + expect(h.warn).toHaveBeenCalledWith('[App] Refused a translation request:', 'string(5010 chars)', 'string(2 chars)'); + }); + + // Breaks: making our own Translate command quiet also silences a + // translate.google.com link in a MESSAGE, which proxies any site. + it('still warns, with no "Don\'t ask again", for a Translate link from mail', async () => { + await expect(open('https://translate.google.com/translate?sl=auto&tl=en&u=https://evil.example/')).resolves.toEqual({ success: false, cancelled: true }); + await expect(open('https://translate.google.com/?sl=auto&tl=en&text=hello')).resolves.toEqual({ success: false, cancelled: true }); + expect(h.showMessageBox).toHaveBeenCalledTimes(2); + for (const [, options] of h.showMessageBox.mock.calls as unknown as Array<[unknown, Electron.MessageBoxOptions]>) { + expect(options.checkboxLabel).toBeUndefined(); + } + expect((h.showMessageBox.mock.calls[0] as unknown as [unknown, Electron.MessageBoxOptions])[1].detail).toContain('It goes on to: evil.example'); + expect(h.openExternal).not.toHaveBeenCalled(); + }); +}); + +describe('Security → remembered link sites', () => { + // Breaks: the Security page shows a wrong count, or "Forget all" leaves a + // site that still opens without asking. + it('counts the remembered sites and forgets them all', async () => { + h.showMessageBox.mockResolvedValueOnce({ response: 0, checkboxChecked: true }); + await open('https://news.example/'); + await expect(call('security:getRememberedLinkSites')).resolves.toEqual({ success: true, data: { count: 1 } }); + + await expect(call('security:forgetRememberedLinkSites')).resolves.toEqual({ success: true, data: { count: 0 } }); + await open('https://news.example/'); + expect(h.showMessageBox).toHaveBeenCalledTimes(2); + }); + + // Breaks: an unreadable store is shown as "no sites" (the opposite fact), or + // its error text reaches the renderer or the log. + it('says the list could not be read rather than answering zero', async () => { + coreDb.blobs.set(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from('{"hosts":["SENTINEL.example"]')); + const answer = await call('security:getRememberedLinkSites'); + expect(answer).toEqual({ success: false, error: expect.stringContaining("couldn't be read") }); + expect(JSON.stringify(h.warn.mock.calls)).not.toContain('SENTINEL'); + + // Forgetting clears even a damaged list. + await expect(call('security:forgetRememberedLinkSites')).resolves.toEqual({ success: true, data: { count: 0 } }); + }); + + // Breaks: "Forget all" answers 0 when the store could not be read afterwards. + it('reports a forget it could not confirm', async () => { + coreDb.fail.add('blob-read'); + await expect(call('security:forgetRememberedLinkSites')).resolves.toMatchObject({ success: false }); }); }); diff --git a/apps/desktop/test/unit/electron/ipc/unsubscribe-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/unsubscribe-handlers.test.ts index 76bd4d0e..0895fe1f 100644 --- a/apps/desktop/test/unit/electron/ipc/unsubscribe-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/unsubscribe-handlers.test.ts @@ -11,8 +11,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; * POST from the reader's network to an address the attacker chose. * * Also pinned: the multi-account read (an All-Inboxes message must be read from - * ITS account's database), and that every failure path answers rather than - * throwing — this handler is driven by a user action with a dialog in front of it. + * ITS account's database), that every failure path answers rather than + * throwing — this handler is driven by a user action with a dialog in front of + * it — and that the sender's page opens only through the external-link gate, + * which names the sender's host in a warning first (CASA 5.1.2). */ const ONE_CLICK_HEADER = ', '; @@ -22,7 +24,10 @@ const h = vi.hoisted(() => ({ handlers: new Map any>(), emails: new Map>(), otherEmails: new Map>(), - openExternal: vi.fn(async (_url: string) => undefined), + // The external-link gate. Its own rules are tested in external-link-gate.test.ts. + openExternal: vi.fn(async (_url: string, _parent: unknown): Promise => 'opened'), + window: { id: 'main-window' }, + sender: { id: 'renderer' }, // The result type is spelled out so a test can hand back a failure with a // null status (a request that never got an answer) without widening it. postOneClick: vi.fn( @@ -36,7 +41,10 @@ const h = vi.hoisted(() => ({ vi.mock('electron', () => ({ ipcMain: { handle: (name: string, fn: (...a: any[]) => any) => h.handlers.set(name, fn) }, - shell: { openExternal: (url: string) => h.openExternal(url) }, +})); +vi.mock('../../../../electron/services/external-link-gate', () => ({ + openExternalUrl: (url: string, parent: unknown) => h.openExternal(url, parent), + windowOfSender: (event: { sender?: unknown } | null) => (event?.sender === h.sender ? h.window : null), })); vi.mock('../../../../electron/shared', () => ({ requireStorage: () => ({ getEmail: async (id: string) => h.emails.get(id) ?? null }), @@ -57,13 +65,14 @@ import { registerUnsubscribeHandlers } from '../../../../electron/ipc/unsubscrib registerUnsubscribeHandlers(); const run = (emailId: string, route: string, accountId?: string) => - h.handlers.get('unsubscribe:run')!(null, emailId, route, accountId); + h.handlers.get('unsubscribe:run')!({ sender: h.sender }, emailId, route, accountId); beforeEach(() => { h.emails.clear(); h.otherEmails.clear(); h.notified = 0; vi.clearAllMocks(); + h.openExternal.mockResolvedValue('opened'); h.postOneClick.mockResolvedValue({ ok: true, status: 200 }); h.emails.set('bulk-1', { id: 'bulk-1', @@ -95,7 +104,27 @@ describe('unsubscribe:run', () => { h.emails.set('page-only', { id: 'page-only', listUnsubscribe: ONE_CLICK_HEADER, listUnsubscribePost: null }); expect(await run('page-only', 'page')).toEqual({ success: true, route: 'page', needsBrowser: true }); - expect(h.openExternal).toHaveBeenCalledWith('https://brand.example/u/abc'); + // Through the gate, attached to the window that asked: the address is the + // sender's choice, so its host is named in a warning before it opens. + expect(h.openExternal).toHaveBeenCalledWith('https://brand.example/u/abc', h.window); + }); + + // Breaks: Cancel on the link warning reads as a failure ("The unsubscribe + // request failed") or as done ("Finish unsubscribing in your browser"). + it('answers cancelled when the reader declines the link warning', async () => { + h.emails.set('page-only', { id: 'page-only', listUnsubscribe: ONE_CLICK_HEADER, listUnsubscribePost: null }); + h.openExternal.mockResolvedValueOnce('cancelled'); + + expect(await run('page-only', 'page')).toEqual({ success: false, cancelled: true }); + }); + + // Breaks: a page the gate refused or could not open is reported as opened, + // so the reader is told to finish in a browser that never opened. + it.each(['failed', 'refused', 'busy'])('reports a page the gate answered %s as not opened', async (outcome) => { + h.emails.set('page-only', { id: 'page-only', listUnsubscribe: ONE_CLICK_HEADER, listUnsubscribePost: null }); + h.openExternal.mockResolvedValueOnce(outcome); + + expect(await run('page-only', 'page')).toEqual({ success: false, error: "The sender's unsubscribe page could not be opened" }); }); it('sends a mailto unsubscribe through the outbox', async () => { diff --git a/apps/desktop/test/unit/electron/main-window-wiring.test.ts b/apps/desktop/test/unit/electron/main-window-wiring.test.ts index 00fa2ea2..160e45b8 100644 --- a/apps/desktop/test/unit/electron/main-window-wiring.test.ts +++ b/apps/desktop/test/unit/electron/main-window-wiring.test.ts @@ -79,11 +79,23 @@ describe('main.ts main-window wiring', () => { // Breaks: the navigation guards are not installed, or not with the app URL, // and a local HTML page can replace the app or the email frame. it('installs the navigation guards on the window with the app URL', () => { - expect(code).toContain('installNavigationGuards(mainWindow.webContents, APP_URL, {'); + expect(code).toContain('installNavigationGuards(mainWindow.webContents, APP_URL, leaveWindow);'); expect(code).not.toContain("'will-navigate'"); expect(code).not.toContain("'will-frame-navigate'"); }); + // Breaks (CASA 5.1.2): a web address leaves the window — a window-open + // request or a navigation the policy sends to the browser — without the + // external-link gate, so a link from a message opens with no warning; or an + // inline window-open handler with its own scheme check comes back. + it('sends every address leaving the window through the external-link gate', () => { + expect(code).toContain('openExternal: (url: string) => openExternalUrl(url, mainWindow),'); + expect(code).toContain('installWindowOpenGuard(mainWindow.webContents, leaveWindow);'); + expect(code).not.toContain('setWindowOpenHandler('); + expect(code).not.toContain('shell.openExternal('); + expect(code).not.toMatch(/\bshell\b/); + }); + // Breaks: extension code runs in-process with full Node in main, the fallback the // CLI and tests use, because nothing told the host about the sandbox; or `network:fetch` // has no way out and an extension holding it is told the network is unavailable. diff --git a/apps/desktop/test/unit/electron/services/external-link-gate.test.ts b/apps/desktop/test/unit/electron/services/external-link-gate.test.ts new file mode 100644 index 00000000..2ba21009 --- /dev/null +++ b/apps/desktop/test/unit/electron/services/external-link-gate.test.ts @@ -0,0 +1,630 @@ +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * The external-link gate (CASA 5.1.2): the one way main hands a URL the app + * did not write to the OS. What breaks if this file fails: + * - a link from a message opens a site with no warning (an allowlist that + * matches too much, a remembered host that matches a subdomain, an + * unreadable store read as "trusted", a dialog whose default is Open); + * - the warning hides what it is about (a Unicode look-alike host, a URL too + * long to read, no word that http is not secure); + * - a frame firing navigations stacks warnings, or a dropped one is lost silently; + * - "Don't ask again" forgets the other sites, or is never kept; + * - the address, its host or its path reaches app.log. + */ + +const h = vi.hoisted(() => ({ + showMessageBox: vi.fn(async (..._args: unknown[]) => ({ response: 1, checkboxChecked: false })), + openExternal: vi.fn(async (_url: string) => {}), + fromWebContents: vi.fn((_contents: unknown): unknown => null), +})); + +vi.mock('electron', () => ({ + BrowserWindow: { fromWebContents: (contents: unknown) => h.fromWebContents(contents) }, + dialog: { showMessageBox: (...args: unknown[]) => h.showMessageBox(...args) }, + shell: { openExternal: (url: string) => h.openExternal(url) }, +})); +vi.mock('../../../../electron/services/core-db', async () => await import('../../../../electron/services/__testing__/fake-core-db')); + +import { captureLogs, type CapturedLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { resetFakeCoreDb, state as coreDb } from '../../../../electron/services/__testing__/fake-core-db'; +import { + CANCEL_BUTTON, + coreDbRememberedHostStore, + createExternalLinkGate, + forgetRememberedLinkHosts, + linkWarningOptions, + MAX_REMEMBERED_HOSTS, + OPEN_BUTTON, + openAppBuiltUrl, + openExternalUrl, + rememberedLinkHostCount, + REMEMBERED_HOSTS_BLOB_KEY, + windowOfSender, + type RememberedHostStore, +} from '../../../../electron/services/external-link-gate'; + +type Answer = { response: number; checkboxChecked: boolean }; + +/** A gate over fakes: a memory store (which can be made unreadable), a scripted warning. */ +function harness(options: { hosts?: string[]; unreadable?: boolean } = {}) { + let hosts = [...(options.hosts ?? [])]; + let unreadable = options.unreadable ?? false; + const store: RememberedHostStore & { hosts: () => string[]; breakReads: (on: boolean) => void } = { + read: vi.fn(() => { + if (unreadable) throw new Error('SQLITE_NOTADB: file is not a database'); + return [...hosts]; + }), + write: vi.fn((next: readonly string[]) => { hosts = [...next]; }), + clear: vi.fn(() => { hosts = []; }), + hosts: () => hosts, + breakReads: (on) => { unreadable = on; }, + }; + const openExternal = vi.fn(async (_url: string) => {}); + const showWarning = vi.fn(async (_parent: object | null, _options: Electron.MessageBoxOptions): Promise => + ({ response: CANCEL_BUTTON, checkboxChecked: false })); + const gate = createExternalLinkGate({ openExternal, showWarning, store }); + const answer = (response: number, checkboxChecked = false) => + showWarning.mockResolvedValueOnce({ response, checkboxChecked }); + return { gate, store, openExternal, showWarning, answer }; +} + +const WINDOW = { id: 'main-window' }; + +let logs: CapturedLogs; +beforeEach(() => { + vi.clearAllMocks(); + resetFakeCoreDb(); + h.showMessageBox.mockResolvedValue({ response: CANCEL_BUTTON, checkboxChecked: false }); + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(() => { logs.stop(); }); + +describe('what opens without a warning', () => { + // Breaks: the app's own buttons (the Sarv logo, the privacy policy, the + // Microsoft/Google pages in the remove dialog) show the warning. + it.each([ + 'https://sarv.com', + 'https://inbox.sarv.com/privacy-policy.html', + 'https://myaccount.google.com/permissions', + 'https://account.live.com/consent/Manage', + 'https://myapps.microsoft.com', + 'https://tavily.com', + ])('opens the app link %s at once', async (url) => { + const { gate, openExternal, showWarning } = harness(); + await expect(gate.open(url, WINDOW)).resolves.toBe('opened'); + expect(showWarning).not.toHaveBeenCalled(); + expect(openExternal).toHaveBeenCalledWith(new URL(url).href); + }); + + // Breaks: an exact-origin rule that is really a prefix, suffix or + // scheme-blind match lets a look-alike open without a word. + it.each([ + 'https://sarv.com/pricing', + 'https://inbox.sarv.com/other.html', + 'https://sarv.com.evil.example/login', + 'https://sarv.com:8443/', + 'http://sarv.com/', + 'https://www.sarv.com/', + 'https://myaccount.google.com/permissions?continue=https://evil.example', + ])('warns before %s, which is not an app link', async (url) => { + const { gate, openExternal, showWarning } = harness(); + await expect(gate.open(url, WINDOW)).resolves.toBe('cancelled'); + expect(showWarning).toHaveBeenCalledOnce(); + expect(openExternal).not.toHaveBeenCalled(); + }); + + // Breaks: a mailto: link (which loads no web content) starts asking, or + // takes a different path than before the gate. + it('opens a mailto: link at once, whoever wrote it', async () => { + const { gate, openExternal, showWarning } = harness(); + await expect(gate.open('mailto:someone@evil.example?subject=Hi', WINDOW)).resolves.toBe('opened'); + expect(showWarning).not.toHaveBeenCalled(); + expect(openExternal).toHaveBeenCalledWith('mailto:someone@evil.example?subject=Hi'); + }); + + // Breaks: email content opens file:, smb: or a custom protocol handler, or a + // broken renderer's non-string reaches the OS. + it.each([ + 'file:///Users/me/Payslip.pdf', + 'smb://evil.example/share', + 'ms-word:ofe|u|https://evil.example/doc.docx', + 'javascript:alert(1)', + 'not a url', + '', + 42, + null, + { href: 'https://sarv.com' }, + ])('refuses %s without asking', async (url) => { + const { gate, openExternal, showWarning } = harness(); + await expect(gate.open(url, WINDOW)).resolves.toBe('refused'); + expect(showWarning).not.toHaveBeenCalled(); + expect(openExternal).not.toHaveBeenCalled(); + }); +}); + +describe('the warning', () => { + // Breaks: Cancel opens the link anyway, or the dialog is not attached to the window. + it('opens nothing when the user cancels, or closes the dialog', async () => { + const { gate, openExternal, showWarning, answer } = harness(); + answer(CANCEL_BUTTON); + await expect(gate.open('https://evil.example/login', WINDOW)).resolves.toBe('cancelled'); + // Escape / the close box answers cancelId, which is Cancel. + answer(CANCEL_BUTTON, true); + await expect(gate.open('https://evil.example/login', WINDOW)).resolves.toBe('cancelled'); + expect(openExternal).not.toHaveBeenCalled(); + expect(showWarning.mock.calls[0][0]).toBe(WINDOW); + }); + + // Breaks: "Open link" opens nothing, or opens something other than what was shown. + it('opens the address it showed when the user chooses Open link', async () => { + const { gate, openExternal, store, answer } = harness(); + answer(OPEN_BUTTON); + await expect(gate.open('https://evil.example/a b?q=1#f', WINDOW)).resolves.toBe('opened'); + expect(openExternal).toHaveBeenCalledWith('https://evil.example/a%20b?q=1#f'); + // Not ticked: nothing is remembered. + expect(store.write).not.toHaveBeenCalled(); + }); + + // Breaks: the dialog defaults to Open (Enter opens the link), has no cancel + // id (Escape picks Open on some platforms), or pre-ticks "Don't ask again". + it('is a warning whose default and cancel answer is Cancel, with the checkbox unticked', () => { + const options = linkWarningOptions(new URL('https://evil.example/login')); + expect(options).toMatchObject({ + type: 'warning', + message: 'Open this link in your browser?', + buttons: ['Open link', 'Cancel'], + defaultId: CANCEL_BUTTON, + cancelId: CANCEL_BUTTON, + checkboxLabel: "Don't ask again for evil.example", + checkboxChecked: false, + noLink: true, + }); + expect(options.buttons![OPEN_BUTTON]).toBe('Open link'); + expect(options.detail).toBe('evil.example\n\nhttps://evil.example/login'); + }); + + // Breaks: a look-alike Unicode host (Cyrillic "а" in paypal) is shown as the + // brand it imitates instead of its punycode. + it('shows a Unicode host as punycode, on its own line and in the checkbox', () => { + const options = linkWarningOptions(new URL('https://pаypal.com/login')); + const [hostLine] = options.detail!.split('\n'); + expect(hostLine).toBe('xn--pypal-4ve.com'); + expect(options.detail).not.toContain('pаypal'); + expect(options.checkboxLabel).toBe("Don't ask again for xn--pypal-4ve.com"); + }); + + // Breaks: a user name in front of the host (`https://bank.example@evil.example`) + // hides the real destination, which the host line must name. + it('names the real host when the address starts with a decoy user name', () => { + const options = linkWarningOptions(new URL('https://www.bank.example@evil.example/')); + expect(options.detail!.split('\n')[0]).toBe('evil.example'); + }); + + // Breaks: a very long address (a Translate link carrying a whole message, a + // tracking URL) makes the dialog unreadable, or loses its start or end. + it('shortens a long address, keeping its start and its end', () => { + const url = `https://evil.example/${'x'.repeat(5000)}/end-of-path`; + const shown = linkWarningOptions(new URL(url)).detail!.split('\n')[2]; + expect(shown.length).toBe(200); + expect(shown.startsWith('https://evil.example/xxx')).toBe(true); + expect(shown.endsWith('/end-of-path')).toBe(true); + expect(shown).toContain('…'); + }); + + // Breaks: a host longer than any DNS name (the URL parser allows it) floods + // the dialog; the end, which names the domain, must survive. + it('keeps only the end of a host longer than any DNS name', () => { + const host = `${'a'.repeat(60)}.`.repeat(6) + 'evil.example'; + const shown = linkWarningOptions(new URL(`https://${host}/`)).detail!.split('\n')[0]; + expect(shown.length).toBe(253); + expect(shown.startsWith('…')).toBe(true); + expect(shown.endsWith('.evil.example')).toBe(true); + // A real host is shown exactly. + expect(linkWarningOptions(new URL('https://a.b.evil.example/')).detail!.split('\n')[0]).toBe('a.b.evil.example'); + }); + + // Breaks: an http: link looks as safe as an https: one. + it('says an http: link is not secure, and an https: one is not flagged', () => { + expect(linkWarningOptions(new URL('http://evil.example/')).detail).toBe( + 'evil.example\n\nhttp://evil.example/\n\nThis link is not secure (http).', + ); + expect(linkWarningOptions(new URL('https://evil.example/')).detail).not.toContain('not secure'); + }); + + // Breaks: a warning that cannot be shown (window torn down) opens the link + // anyway, or the rejection escapes to the caller. + it('opens nothing when the warning cannot be shown', async () => { + const { gate, openExternal, showWarning } = harness(); + showWarning.mockRejectedValueOnce(new Error('Object has been destroyed')); + await expect(gate.open('https://evil.example/', WINDOW)).resolves.toBe('failed'); + expect(openExternal).not.toHaveBeenCalled(); + // And the window is free for the next one. + await expect(gate.open('https://evil.example/', WINDOW)).resolves.toBe('cancelled'); + }); + + // Breaks: the OS refusing to open the link rejects into the caller (an IPC + // handler, a navigation guard) instead of being answered. + it('answers failed when the OS cannot open the link', async () => { + const { gate, openExternal } = harness(); + openExternal.mockRejectedValueOnce(new Error('No application knows how to open the URL')); + await expect(gate.open('https://sarv.com/', WINDOW)).resolves.toBe('failed'); + }); +}); + +describe('"Don\'t ask again"', () => { + // Breaks: ticking the box does not stick, so the same site asks every time. + it('remembers the host, and the next link to it opens without asking', async () => { + const { gate, store, openExternal, showWarning, answer } = harness(); + answer(OPEN_BUTTON, true); + await expect(gate.open('https://News.Example/today', WINDOW)).resolves.toBe('opened'); + expect(store.hosts()).toEqual(['news.example']); + + await expect(gate.open('https://news.example/tomorrow?x=1', WINDOW)).resolves.toBe('opened'); + await expect(gate.open('http://news.example:8080/', WINDOW)).resolves.toBe('opened'); + expect(showWarning).toHaveBeenCalledOnce(); + expect(openExternal).toHaveBeenCalledTimes(3); + }); + + // Breaks: a remembered host also trusts its subdomains, its parent, or a + // host that merely ends with it. + it('matches the exact hostname only', async () => { + const { gate, showWarning } = harness({ hosts: ['news.example'] }); + for (const url of ['https://evil.news.example/', 'https://example/', 'https://badnews.example/', 'https://news.example.evil.example/', 'https://news.example./']) { + await expect(gate.open(url, WINDOW)).resolves.toBe('cancelled'); + } + expect(showWarning).toHaveBeenCalledTimes(5); + }); + + // Breaks: Cancel with the box ticked remembers the site anyway. + it('remembers nothing when the user ticks the box and cancels', async () => { + const { gate, store, answer } = harness(); + answer(CANCEL_BUTTON, true); + await gate.open('https://evil.example/', WINDOW); + expect(store.write).not.toHaveBeenCalled(); + }); + + // THE fail-closed rule: an unreadable list is not an empty one, and "trusted" + // is the wrong answer for both. Breaks: a damaged store opens links silently. + it('asks when the store cannot be read', async () => { + const { gate, showWarning } = harness({ hosts: ['news.example'], unreadable: true }); + await expect(gate.open('https://news.example/', WINDOW)).resolves.toBe('cancelled'); + expect(showWarning).toHaveBeenCalledOnce(); + }); + + // Breaks: remembering over a list that could not be read writes [host] and + // forgets every other site the user chose. + it('does not overwrite a list it could not read, and still opens the link', async () => { + const { gate, store, answer } = harness({ hosts: ['a.example'] }); + store.breakReads(true); + answer(OPEN_BUTTON, true); + await expect(gate.open('https://b.example/', WINDOW)).resolves.toBe('opened'); + expect(store.write).not.toHaveBeenCalled(); + store.breakReads(false); + expect(store.hosts()).toEqual(['a.example']); + }); + + // Breaks: a failed write rejects into the caller, or stops the link opening. + it('still opens the link when the site cannot be written down', async () => { + const { gate, store, openExternal, answer } = harness(); + vi.mocked(store.write).mockImplementationOnce(() => { throw new Error('SQLITE_FULL'); }); + answer(OPEN_BUTTON, true); + await expect(gate.open('https://b.example/', WINDOW)).resolves.toBe('opened'); + expect(openExternal).toHaveBeenCalledOnce(); + }); + + // Breaks: the log says a site was remembered when it was not (the tick was + // logged, not the outcome), so a "why does it still ask?" report is misread. + it('logs remembered=true only when the host is in the list afterwards', async () => { + const { gate, store, answer } = harness(); + answer(OPEN_BUTTON, true); + await gate.open('https://saved.example/', WINDOW); + // A write that throws. + vi.mocked(store.write).mockImplementationOnce(() => { throw new Error('SQLITE_FULL'); }); + answer(OPEN_BUTTON, true); + await gate.open('https://thrown.example/', WINDOW); + // A write that silently does nothing (the core-DB write swallows its errors). + vi.mocked(store.write).mockImplementationOnce(() => {}); + answer(OPEN_BUTTON, true); + await gate.open('https://lost.example/', WINDOW); + // A list that cannot be read at all. + store.breakReads(true); + answer(OPEN_BUTTON, true); + await gate.open('https://unread.example/', WINDOW); + store.breakReads(false); + + expect(store.hosts()).toEqual(['saved.example']); + expect(logs.containing('opened=true, remembered=true, forwarder=false')).toHaveLength(1); + expect(logs.containing('opened=true, remembered=false, forwarder=false')).toHaveLength(3); + }); + + // Breaks: the list grows without bound, or the cap drops the NEWEST site. + it('keeps the newest 500 hosts, dropping the oldest', async () => { + const full = Array.from({ length: MAX_REMEMBERED_HOSTS }, (_, i) => `site-${i}.example`); + const { gate, store, answer } = harness({ hosts: full }); + answer(OPEN_BUTTON, true); + await gate.open('https://newest.example/', WINDOW); + expect(store.hosts()).toHaveLength(MAX_REMEMBERED_HOSTS); + expect(store.hosts()[0]).toBe('site-1.example'); + expect(store.hosts().at(-1)).toBe('newest.example'); + }); + + // Breaks: the count or "Forget all" lies about the list. + it('counts the remembered hosts and forgets them all', async () => { + const { gate, showWarning } = harness({ hosts: ['a.example', 'b.example'] }); + expect(gate.rememberedHostCount()).toBe(2); + gate.forgetRememberedHosts(); + expect(gate.rememberedHostCount()).toBe(0); + await gate.open('https://a.example/', WINDOW); + expect(showWarning).toHaveBeenCalledOnce(); + }); +}); + +describe('link forwarders (Safe Links, redirects, Translate, shorteners, click trackers)', () => { + const SAFE_LINK = `https://nam02.safelinks.protection.outlook.com/?url=${encodeURIComponent('https://evil.example/login')}&data=05`; + + // THE regression: one tick on a Safe Links link (every link in a protected + // tenant's mail) would turn the warning off for all mail. + it('offers no "Don\'t ask again" for a forwarder', () => { + for (const url of [ + SAFE_LINK, + 'https://www.google.com/url?q=https://evil.example/', + 'https://translate.google.com/?sl=auto&tl=en&text=hello', + 'https://t.co/AbCdEf', + 'https://lnkd.in/x', + 'https://brand.us1.list-manage.com/track/click?u=1', + ]) { + const options = linkWarningOptions(new URL(url)); + expect(options.checkboxLabel, url).toBeUndefined(); + expect(options.checkboxChecked, url).toBeUndefined(); + expect(options.detail, url).toContain('This site forwards links to other sites, so its links always ask.'); + expect(options.defaultId, url).toBe(CANCEL_BUTTON); + } + }); + + // Breaks: the warning names only the wrapper, so every Safe Links link + // looks the same and the user cannot see where it goes. + it('names where a forwarder goes on to, on its own line under the host', () => { + const lines = linkWarningOptions(new URL(SAFE_LINK)).detail!.split('\n'); + expect(lines[0]).toBe('nam02.safelinks.protection.outlook.com'); + expect(lines[1]).toBe('It goes on to: evil.example'); + expect(lines[2]).toBe(''); + expect(lines[3]).toBe(SAFE_LINK); + }); + + // Breaks: a look-alike destination behind a wrapper is named as the brand. + it('names the destination in punycode', () => { + const wrapped = `https://www.google.com/url?q=${encodeURIComponent('https://pаypal.com/')}`; + expect(linkWarningOptions(new URL(wrapped)).detail!.split('\n')[1]).toBe('It goes on to: xn--pypal-4ve.com'); + }); + + // Breaks: a shortener whose destination only its server knows gets an + // invented "goes on to" line, or an ordinary link gets the forwarder note. + it('adds no destination line when the link does not say, and no forwarder note to other links', () => { + expect(linkWarningOptions(new URL('https://t.co/AbCdEf')).detail).not.toContain('It goes on to'); + const plain = linkWarningOptions(new URL('https://shop.example/r?url=https://evil.example/')); + expect(plain.detail).not.toContain('It goes on to'); + expect(plain.detail).not.toContain('forwards links'); + expect(plain.checkboxLabel).toBe("Don't ask again for shop.example"); + }); + + // Breaks: a forwarder host that got into the list (an older build, a planted + // entry) still opens every link behind it without asking. + it('never honours a remembered forwarder', async () => { + const { gate, showWarning, openExternal } = harness({ hosts: ['nam02.safelinks.protection.outlook.com', 't.co', 'www.google.com'] }); + await expect(gate.open(SAFE_LINK, WINDOW)).resolves.toBe('cancelled'); + await expect(gate.open('https://t.co/AbCdEf', WINDOW)).resolves.toBe('cancelled'); + await expect(gate.open('https://www.google.com/url?q=https://evil.example/', WINDOW)).resolves.toBe('cancelled'); + expect(showWarning).toHaveBeenCalledTimes(3); + expect(openExternal).not.toHaveBeenCalled(); + // An ordinary page on a remembered host that is not a forwarder path still opens. + await expect(gate.open('https://www.google.com/search?q=x', WINDOW)).resolves.toBe('opened'); + }); + + // Breaks: a dialog that answers "checked" anyway writes the forwarder down. + it('never remembers a forwarder, whatever the dialog answered', async () => { + const { gate, store, openExternal, answer } = harness(); + answer(OPEN_BUTTON, true); + await expect(gate.open(SAFE_LINK, WINDOW)).resolves.toBe('opened'); + expect(store.write).not.toHaveBeenCalled(); + // What opens is the link that was clicked, never the unwrapped destination. + expect(openExternal).toHaveBeenCalledExactlyOnceWith(SAFE_LINK); + }); +}); + +describe('app-built addresses (the Translate menu item)', () => { + // Breaks: the app's own Translate command shows the "untrusted link" warning + // (translate.google.com is a forwarder, so it could never be silenced). + it('opens an address main built without a warning, even while one is open', async () => { + const { gate, openExternal, showWarning } = harness(); + showWarning.mockImplementationOnce(() => new Promise(() => {})); + void gate.open('https://evil.example/', WINDOW); + + const url = new URL('https://translate.google.com/?sl=auto&tl=en&text=hello'); + await expect(gate.openAppBuilt(url)).resolves.toBe('opened'); + expect(openExternal).toHaveBeenCalledExactlyOnceWith(url.href); + expect(showWarning).toHaveBeenCalledOnce(); + }); + + // Breaks: the app-built path hands a file:, custom-protocol or non-URL value to the OS. + it('still refuses anything but http, https and mailto', async () => { + const { gate, openExternal } = harness(); + await expect(gate.openAppBuilt(new URL('file:///etc/passwd'))).resolves.toBe('refused'); + await expect(gate.openAppBuilt('https://evil.example/' as unknown as URL)).resolves.toBe('refused'); + expect(openExternal).not.toHaveBeenCalled(); + expect(logs.containing('Refused an app-built link with an unsupported scheme: file:')).toHaveLength(1); + }); + + // Breaks: the OS failing to open it rejects into the IPC handler. + it('answers failed when the OS cannot open it', async () => { + const { gate, openExternal } = harness(); + openExternal.mockRejectedValueOnce(new Error('no browser')); + await expect(gate.openAppBuilt(new URL('https://translate.google.com/'))).resolves.toBe('failed'); + }); + + // The app wiring: the exported entry point reaches the OS with no dialog. + it('is wired to the OS without the dialog', async () => { + await expect(openAppBuiltUrl(new URL('https://translate.google.com/?sl=auto&tl=en&text=x'))).resolves.toBe('opened'); + expect(h.openExternal).toHaveBeenCalledWith('https://translate.google.com/?sl=auto&tl=en&text=x'); + expect(h.showMessageBox).not.toHaveBeenCalled(); + }); +}); + +describe('one warning at a time per window', () => { + // Breaks: a frame firing navigations stacks one warning per request, or a + // request in another window waits on this one. + it('drops further requests in the same window while one is open, and counts them', async () => { + const { gate, showWarning, openExternal } = harness(); + let answerFirst!: (answer: Answer) => void; + showWarning.mockImplementationOnce(() => new Promise((resolve) => { answerFirst = resolve; })); + const first = gate.open('https://evil.example/1', WINDOW); + + await expect(gate.open('https://evil.example/2', WINDOW)).resolves.toBe('busy'); + await expect(gate.open('https://sarv.com/', WINDOW)).resolves.toBe('busy'); + await expect(gate.open('mailto:x@evil.example', WINDOW)).resolves.toBe('busy'); + // Another window has its own warning. + await expect(gate.open('https://evil.example/3', { id: 'other' })).resolves.toBe('cancelled'); + expect(showWarning).toHaveBeenCalledTimes(2); + + answerFirst({ response: OPEN_BUTTON, checkboxChecked: false }); + await expect(first).resolves.toBe('opened'); + expect(openExternal).toHaveBeenCalledExactlyOnceWith('https://evil.example/1'); + expect(logs.containing('Dropped 3 more link request(s) while a warning was open')).toHaveLength(1); + + // The window is free again. + await expect(gate.open('https://evil.example/4', WINDOW)).resolves.toBe('cancelled'); + }); + + // Breaks: requests with no window bypass the one-at-a-time rule. + it('treats requests with no window as one window', async () => { + const { gate, showWarning } = harness(); + showWarning.mockImplementationOnce(() => new Promise(() => {})); + void gate.open('https://evil.example/1', null); + await expect(gate.open('https://evil.example/2', null)).resolves.toBe('busy'); + }); +}); + +describe('the app wiring (Electron dialog, shell, core DB)', () => { + const win = (destroyed = false) => ({ isDestroyed: () => destroyed }) as unknown as Electron.BrowserWindow; + + // Breaks: the warning is not modal to the window that asked, or a torn-down + // window crashes the dialog call. + it('attaches the warning to a live window, and shows it unattached otherwise', async () => { + const live = win(); + await openExternalUrl('https://evil.example/', live); + await openExternalUrl('https://evil.example/', win(true)); + await openExternalUrl('https://evil.example/', null); + expect(h.showMessageBox.mock.calls[0][0]).toBe(live); + expect(h.showMessageBox.mock.calls[0][1]).toMatchObject({ type: 'warning' }); + expect(h.showMessageBox.mock.calls[1]).toHaveLength(1); + expect(h.showMessageBox.mock.calls[2]).toHaveLength(1); + expect(h.openExternal).not.toHaveBeenCalled(); + }); + + // Breaks: a remembered site is not kept in the core DB (lost on restart), or + // the count/forget IPC reads another store than the gate. + it('keeps remembered sites in the core DB, counts and forgets them', async () => { + h.showMessageBox.mockResolvedValueOnce({ response: OPEN_BUTTON, checkboxChecked: true }); + await expect(openExternalUrl('https://news.example/', win())).resolves.toBe('opened'); + expect(JSON.parse(coreDb.blobs.get(REMEMBERED_HOSTS_BLOB_KEY)!.toString('utf8'))).toEqual({ hosts: ['news.example'] }); + expect(rememberedLinkHostCount()).toBe(1); + + await expect(openExternalUrl('https://news.example/again', win())).resolves.toBe('opened'); + expect(h.showMessageBox).toHaveBeenCalledOnce(); + expect(h.openExternal).toHaveBeenCalledTimes(2); + + forgetRememberedLinkHosts(); + expect(coreDb.blobs.has(REMEMBERED_HOSTS_BLOB_KEY)).toBe(false); + expect(rememberedLinkHostCount()).toBe(0); + }); + + // Fail closed against the real store: an unreadable core DB asks, and the + // count throws rather than answering 0. + it('asks when the core DB cannot be read, and does not report an empty list', async () => { + coreDb.blobs.set(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from(JSON.stringify({ hosts: ['news.example'] }))); + coreDb.fail.add('blob-read'); + await expect(openExternalUrl('https://news.example/', win())).resolves.toBe('cancelled'); + expect(h.showMessageBox).toHaveBeenCalledOnce(); + expect(() => rememberedLinkHostCount()).toThrow(); + }); + + // Breaks: a damaged value reads as "no sites" and the next remember + // overwrites it, or it reads as trusted. + it('treats a damaged value as unreadable, and never overwrites it', async () => { + coreDb.blobs.set(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from('{"hosts": "news.example"')); + expect(() => coreDbRememberedHostStore.read()).toThrow(); + coreDb.blobs.set(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from('{"hosts": "news.example"}')); + expect(() => coreDbRememberedHostStore.read()).toThrow(); + + h.showMessageBox.mockResolvedValueOnce({ response: OPEN_BUTTON, checkboxChecked: true }); + await expect(openExternalUrl('https://other.example/', win())).resolves.toBe('opened'); + expect(coreDb.blobs.get(REMEMBERED_HOSTS_BLOB_KEY)!.toString('utf8')).toBe('{"hosts": "news.example"}'); + + // "Forget all" is how a damaged list is cleared. + forgetRememberedLinkHosts(); + expect(coreDbRememberedHostStore.read()).toEqual([]); + }); + + // Breaks: an entry that is not a parsed hostname (planted, or left by an + // older shape) is trusted. + it('drops stored entries that are not lower-case hostnames', () => { + coreDb.blobs.set(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from(JSON.stringify({ hosts: ['ok.example', 'Upper.Example', 'has space', '', 7, null] }))); + expect(coreDbRememberedHostStore.read()).toEqual(['ok.example']); + }); + + // Breaks: the warning attaches to no window for an IPC request, or a gone + // sender throws inside the handler. + it('finds the window an IPC request came from', () => { + const window = win(); + h.fromWebContents.mockReturnValueOnce(window); + expect(windowOfSender({ sender: {} as Electron.WebContents })).toBe(window); + expect(windowOfSender(null)).toBeNull(); + expect(windowOfSender({})).toBeNull(); + h.fromWebContents.mockImplementationOnce(() => { throw new Error('Object has been destroyed'); }); + expect(windowOfSender({ sender: {} as Electron.WebContents })).toBeNull(); + }); +}); + +describe('what reaches the log', () => { + // Breaks: the address, its host or its path — the mail's — is written to + // app.log by any outcome of the gate. + it('never writes the URL, its host or its path', async () => { + const SENTINEL_HOST = 'sentinel-host.example'; + const { gate, store, openExternal, showWarning, answer } = harness(); + await gate.open('file:///Users/SENTINEL-user/Payslip-SENTINEL.pdf', WINDOW); + answer(CANCEL_BUTTON); + await gate.open(`https://${SENTINEL_HOST}/SENTINEL-path?q=SENTINEL`, WINDOW); + answer(OPEN_BUTTON, true); + await gate.open(`http://${SENTINEL_HOST}/SENTINEL-path`, WINDOW); + store.breakReads(true); + answer(OPEN_BUTTON, true); + await gate.open(`https://other-${SENTINEL_HOST}/SENTINEL`, WINDOW); + store.breakReads(false); + openExternal.mockRejectedValueOnce(new Error(`Failed to open https://${SENTINEL_HOST}/SENTINEL`)); + await gate.open(`https://${SENTINEL_HOST}/SENTINEL-again`, WINDOW); + showWarning.mockRejectedValueOnce(new Error(`dialog for https://x-${SENTINEL_HOST}/SENTINEL failed`)); + await gate.open(`https://x-${SENTINEL_HOST}/SENTINEL`, WINDOW); + let release!: (answer: Answer) => void; + showWarning.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; })); + const pending = gate.open(`https://y-${SENTINEL_HOST}/SENTINEL`, WINDOW); + await gate.open(`https://z-${SENTINEL_HOST}/SENTINEL`, WINDOW); + release({ response: CANCEL_BUTTON, checkboxChecked: false }); + await pending; + // A forwarder whose destination is the sentinel: shown in the dialog, never logged. + answer(OPEN_BUTTON, true); + await gate.open(`https://nam02.safelinks.protection.outlook.com/?url=${encodeURIComponent(`https://${SENTINEL_HOST}/SENTINEL`)}`, WINDOW); + + expect(logs.lines.length).toBeGreaterThan(0); + expect(logs.containing('SENTINEL')).toEqual([]); + expect(logs.containing('sentinel-host')).toEqual([]); + expect(logs.containing('safelinks')).toEqual([]); + // What a line may say: the scheme, booleans and counts. + expect(logs.containing('Refused a link with an unsupported scheme: file:')).toHaveLength(1); + expect(logs.containing('Warned before a https: link: opened=false, remembered=false, forwarder=false')).toHaveLength(2); + expect(logs.containing('Warned before a http: link: opened=true, remembered=true, forwarder=false')).toHaveLength(1); + // Ticked, but the list could not be read, so nothing was saved. + expect(logs.containing('Warned before a https: link: opened=true, remembered=false, forwarder=false')).toHaveLength(1); + expect(logs.containing('Warned before a https: link: opened=true, remembered=false, forwarder=true')).toHaveLength(1); + }); +}); diff --git a/apps/desktop/test/unit/electron/utils/app-icon.test.ts b/apps/desktop/test/unit/electron/utils/app-icon.test.ts index d4b02065..4b8abe40 100644 --- a/apps/desktop/test/unit/electron/utils/app-icon.test.ts +++ b/apps/desktop/test/unit/electron/utils/app-icon.test.ts @@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'fs'; import { dirname, join, resolve } from 'path'; import { fileURLToPath } from 'url'; +import { SARV_HOME_URL } from '@sarvinbox/core/app-links'; import { describe, it, expect } from 'vitest'; import { resolveAppIconPath } from '../../../../electron/utils/app-icon'; @@ -147,12 +148,16 @@ describe('branded icon assets', () => { // The link is the bare origin on purpose: /sarvinbox does not exist yet, and a // deep link that 404s is worse than the home page. Point it at the product // page once that ships. + // Changed deliberately: the address moved from a literal in AppSidebar to the + // shared SARV_HOME_URL (core app-links), the list main's external-link gate + // opens without a warning; the destination is the same bare origin. it('keeps the Sarv mark and the sarv.com link together in the app rail', () => { const source = readFileSync(join(DESKTOP_ROOT, 'src/components/AppSidebar.tsx'), 'utf8'); expect(source).toContain("'./sarv.png'"); expect(source).not.toContain("'./icon.svg'"); - expect(source).toContain("openExternal('https://sarv.com')"); + expect(source).toContain('openExternal(SARV_HOME_URL)'); + expect(SARV_HOME_URL).toBe('https://sarv.com'); }); // Breaks: the sidebar header loses the lockup — the medallion disappears, or diff --git a/apps/desktop/test/unit/electron/utils/navigation-guards.test.ts b/apps/desktop/test/unit/electron/utils/navigation-guards.test.ts index 7d6188b4..3e3e9a0a 100644 --- a/apps/desktop/test/unit/electron/utils/navigation-guards.test.ts +++ b/apps/desktop/test/unit/electron/utils/navigation-guards.test.ts @@ -1,7 +1,7 @@ import { ATTACHMENT_SCHEME, panelAssetUrl } from '@sarvinbox/core'; import { describe, expect, it, vi } from 'vitest'; -import { installNavigationGuards, type GuardedNavigation } from '../../../../electron/utils/navigation-guards'; +import { installNavigationGuards, installWindowOpenGuard, type GuardedNavigation } from '../../../../electron/utils/navigation-guards'; // The wiring of the window's two navigation guards (main.ts cannot be imported // by a test). What breaks if this file fails: a navigation the policy refuses @@ -149,12 +149,56 @@ describe('installNavigationGuards', () => { expect(fire('will-frame-navigate', undefined, false).preventDefault).toHaveBeenCalledOnce(); }); + // Changed deliberately: the line used to carry the Error itself, whose + // message can quote the address (the mail's). It carries the failure's kind. it('logs a failed hand-off to the browser instead of rejecting unhandled', async () => { const { fire, deps } = harness(); - deps.openExternal.mockRejectedValueOnce(new Error('no handler')); + deps.openExternal.mockRejectedValueOnce(new Error('no handler for mailto:SENTINEL@b.com')); fire('will-navigate', 'mailto:a@b.com'); await Promise.resolve(); await Promise.resolve(); - expect(deps.warn).toHaveBeenCalledWith('[Main] openExternal failed:', expect.any(Error)); + expect(deps.warn).toHaveBeenCalledWith('[Main] openExternal failed:', { name: 'Error' }); + }); +}); + +describe('installWindowOpenGuard', () => { + function windowOpenHarness() { + let handler!: (details: { url: string }) => { action: 'deny' }; + const contents = { setWindowOpenHandler: vi.fn((fn: typeof handler) => { handler = fn; }) }; + const deps = { openExternal: vi.fn(async (_url: string): Promise => 'opened'), warn: vi.fn() }; + installWindowOpenGuard(contents, deps); + return { request: (url: unknown) => handler({ url } as { url: string }), deps, contents }; + } + + // Breaks (CASA 5.1.2): an email's target="_blank" link — the path a click + // takes before the frame's click listener attaches — reaches the OS without + // the external-link gate, so it opens with no warning; or an Electron window + // opens inside the app. + it('denies every new window and hands the address to the gate', () => { + const { request, deps, contents } = windowOpenHarness(); + expect(contents.setWindowOpenHandler).toHaveBeenCalledOnce(); + expect(request('https://evil.example/login')).toEqual({ action: 'deny' }); + expect(deps.openExternal).toHaveBeenCalledWith('https://evil.example/login'); + }); + + // Breaks: the guard pre-filters with its own scheme rule again (the copy + // that drifted), instead of leaving every decision — and its log line — to + // the gate; or a missing URL from a changed Electron event opens something. + it('leaves the scheme decision to the gate, and still denies the window', () => { + const { request, deps } = windowOpenHarness(); + expect(request('file:///Users/me/invoice.html')).toEqual({ action: 'deny' }); + expect(request(undefined)).toEqual({ action: 'deny' }); + expect(deps.openExternal.mock.calls).toEqual([['file:///Users/me/invoice.html'], [undefined]]); + }); + + // Breaks: a rejected hand-off is an unhandled rejection in main, or its + // message (which can quote the address) reaches the log. + it('logs a failed hand-off by its kind', async () => { + const { request, deps } = windowOpenHarness(); + deps.openExternal.mockRejectedValueOnce(new TypeError('cannot open https://SENTINEL.example')); + request('https://SENTINEL.example'); + await Promise.resolve(); + await Promise.resolve(); + expect(deps.warn).toHaveBeenCalledWith('[Main] openExternal failed:', { name: 'TypeError' }); }); }); diff --git a/apps/desktop/test/unit/src/components/app-links-buttons.test.tsx b/apps/desktop/test/unit/src/components/app-links-buttons.test.tsx new file mode 100644 index 00000000..30ef34ce --- /dev/null +++ b/apps/desktop/test/unit/src/components/app-links-buttons.test.tsx @@ -0,0 +1,57 @@ +// @vitest-environment happy-dom +import { isAppLink } from '@sarvinbox/core/app-links'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { AppSidebar } from '../../../../src/components/AppSidebar'; +import { GmailPrivacyNotice } from '../../../../src/components/GmailPrivacyNotice'; +import { RemovalAccessNote, RevokeFailedNotice } from '../../../../src/components/settings/AccountRemovalNotes'; +import { cleanup, fire, render } from '../../../helpers/render'; + +/** + * The app's own link buttons and main's external-link gate agree on what the + * app wrote. What breaks if this file fails: a button's address drifts off the + * app-links allowlist, so clicking the Sarv logo, the privacy policy or a + * Microsoft/Google page in the remove dialog shows the "untrusted link" + * warning — which teaches users to click through it. + */ + +const openExternal = vi.fn(async (_url: string) => ({ success: true })); + +beforeEach(() => { + openExternal.mockClear(); + (window as unknown as { electronAPI: unknown }).electronAPI = { app: { openExternal } }; +}); +afterEach(cleanup); + +const opened = () => openExternal.mock.calls.map(([url]) => url); + +describe('app link buttons', () => { + it('the Sarv logo opens an app link', () => { + const view = render( {}} />); + fire(view.find('img[alt="Sarv.com"]')!.closest('button'), 'click'); + expect(opened()).toEqual(['https://sarv.com']); + expect(opened().every(isAppLink)).toBe(true); + }); + + it('the privacy policy opens an app link', () => { + const view = render(); + fire(view.all('button').find((b) => b.textContent?.includes('Privacy policy'))!, 'click'); + expect(opened()).toEqual(['https://inbox.sarv.com/privacy-policy.html']); + expect(opened().every(isAppLink)).toBe(true); + }); + + it("the remove dialog's Microsoft and Google pages open app links", () => { + const microsoft = render(); + for (const button of microsoft.all('button')) fire(button, 'click'); + microsoft.unmount(); + const google = render( {}} />); + fire(google.all('button').find((b) => b.textContent?.includes('myaccount.google.com'))!, 'click'); + + expect(opened()).toEqual([ + 'https://account.live.com/consent/Manage', + 'https://myapps.microsoft.com', + 'https://myaccount.google.com/permissions', + ]); + expect(opened().every(isAppLink)).toBe(true); + }); +}); diff --git a/apps/desktop/test/unit/src/components/email-detail/UnsubscribeButton.test.tsx b/apps/desktop/test/unit/src/components/email-detail/UnsubscribeButton.test.tsx index 61cd9078..bba2e230 100644 --- a/apps/desktop/test/unit/src/components/email-detail/UnsubscribeButton.test.tsx +++ b/apps/desktop/test/unit/src/components/email-detail/UnsubscribeButton.test.tsx @@ -101,6 +101,21 @@ describe('UnsubscribeButton', () => { view.unmount(); }); + // The reader chose Cancel on main's link warning (which names the sender's + // host). Breaks: that reads as a failure ("The unsubscribe request failed") + // or as done ("Finish unsubscribing in your browser"), when nothing happened. + it('says nothing and keeps the button when the reader cancels the link warning', async () => { + run.mockResolvedValue({ success: false, cancelled: true }); + const view = mount({ listUnsubscribePost: null }); + fire(button(view), 'click'); + await settle(); + + expect(view.find('[role="alert"]')).toBeNull(); + expect(view.find('[role="status"]')).toBeNull(); + expect((button(view) as HTMLButtonElement).disabled).toBe(false); + view.unmount(); + }); + // Mailto-only mail: the message goes through the outbox, so the wording says // sent-and-pending rather than done. it('takes the mailto route when that is all the sender offered', async () => { diff --git a/apps/desktop/test/unit/src/components/security/RememberedLinkSites.test.tsx b/apps/desktop/test/unit/src/components/security/RememberedLinkSites.test.tsx new file mode 100644 index 00000000..2ba8e736 --- /dev/null +++ b/apps/desktop/test/unit/src/components/security/RememberedLinkSites.test.tsx @@ -0,0 +1,153 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { RememberedLinkSites } from '../../../../../src/components/security/RememberedLinkSites'; +import { Security } from '../../../../../src/components/security/Security'; +import { cleanup, fire, render, settle } from '../../../../helpers/render'; + +/** + * Security → Trusted & blocked links → "Sites that open without asking": the + * sites the link warning was told "Don't ask again" for. + * + * What breaks if this file goes red: the user cannot see that links to some + * sites skip the warning, or cannot take that back; an unreadable list is + * shown as "None" (the opposite fact); or "Forget all" claims a clear main did + * not confirm. + */ + +type Answer = { success: boolean; data?: { count: number }; error?: string }; + +function mount(options: { count?: Answer; forget?: Answer | Error } = {}) { + const getRememberedLinkSites = vi.fn(async () => options.count ?? { success: true, data: { count: 3 } }); + const forgetRememberedLinkSites = vi.fn(async () => { + if (options.forget instanceof Error) throw options.forget; + return options.forget ?? { success: true, data: { count: 0 } }; + }); + (window as unknown as { electronAPI: unknown }).electronAPI = { + security: { getRememberedLinkSites, forgetRememberedLinkSites, listLinkRules: async () => ({ success: true, data: [] }) }, + }; + return { getRememberedLinkSites, forgetRememberedLinkSites }; +} + +const forgetButton = (view: ReturnType) => + view.all('button').find((button) => button.textContent === 'Forget all') as HTMLButtonElement; +const status = (view: ReturnType) => view.find('[role="status"]')?.textContent ?? ''; + +afterEach(() => { + cleanup(); + document.body.innerHTML = ''; +}); + +describe('RememberedLinkSites', () => { + // Breaks: the count is not shown, so links silently skip the warning. + it('shows how many sites open without asking', async () => { + mount(); + const view = render(); + expect(status(view)).toBe('Checking…'); + expect(forgetButton(view).disabled).toBe(true); + await settle(); + + expect(status(view)).toContain('3 sites you chose'); + expect(forgetButton(view).disabled).toBe(false); + }); + + // Breaks: singular/plural wording, or "Forget all" offered with nothing to forget. + it('words one site and none correctly, and disables Forget all at none', async () => { + mount({ count: { success: true, data: { count: 1 } } }); + const one = render(); + await settle(); + expect(status(one)).toContain('1 site you chose'); + one.unmount(); + + mount({ count: { success: true, data: { count: 0 } } }); + const none = render(); + await settle(); + expect(status(none)).toContain('None. Every link to another site asks'); + expect(forgetButton(none).disabled).toBe(true); + }); + + // Breaks: "Forget all" does not reach main, or the count does not follow. + it('forgets them all and shows the count main read back', async () => { + const { forgetRememberedLinkSites } = mount(); + const view = render(); + await settle(); + + fire(forgetButton(view), 'click'); + await settle(); + + expect(forgetRememberedLinkSites).toHaveBeenCalledOnce(); + expect(status(view)).toContain('None.'); + expect(forgetButton(view).disabled).toBe(true); + }); + + // THE fail-closed wording: an unreadable list is not "None", and Forget all + // stays available because it is how a damaged list is cleared. + it('says the list could not be read, and still offers Forget all', async () => { + mount({ count: { success: false, error: 'unreadable' } }); + const view = render(); + await settle(); + + expect(status(view)).toContain("couldn't be read"); + expect(status(view)).not.toContain('None'); + expect(forgetButton(view).disabled).toBe(false); + }); + + // Breaks: a forget main could not confirm (or a broken bridge) shows "None". + it('does not claim a clear that main could not confirm', async () => { + mount({ forget: { success: false, error: 'unreadable' } }); + const view = render(); + await settle(); + fire(forgetButton(view), 'click'); + await settle(); + expect(status(view)).toContain("couldn't be read"); + + cleanup(); + mount({ forget: new Error('IPC gone') }); + const broken = render(); + await settle(); + fire(forgetButton(broken), 'click'); + await settle(); + expect(status(broken)).toContain("couldn't be read"); + }); + + // Breaks: an older preload without the bridge (or a throw) crashes the page. + it('reads as unreadable when the bridge is missing or throws', async () => { + (window as unknown as { electronAPI: unknown }).electronAPI = { security: {} }; + const missing = render(); + await settle(); + expect(status(missing)).toContain("couldn't be read"); + cleanup(); + + (window as unknown as { electronAPI: unknown }).electronAPI = { + security: { getRememberedLinkSites: async () => { throw new Error('IPC gone'); } }, + }; + const throwing = render(); + await settle(); + expect(status(throwing)).toContain("couldn't be read"); + }); + + // Breaks: an answer that lands after the user left the page updates an + // unmounted component (React warns, and the state write is lost work). + it('ignores an answer that arrives after it unmounted', async () => { + let answer!: (value: Answer) => void; + (window as unknown as { electronAPI: unknown }).electronAPI = { + security: { getRememberedLinkSites: () => new Promise((resolve) => { answer = resolve; }) }, + }; + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); + const view = render(); + view.unmount(); + answer({ success: true, data: { count: 2 } }); + await settle(); + expect(errors).not.toHaveBeenCalled(); + errors.mockRestore(); + }); + + // Breaks: the section is not where users look for link trust. + it('is on the Security page under Trusted & blocked links', async () => { + mount(); + const view = render(); + await settle(); + expect(view.find('[data-testid="remembered-link-sites"]')).not.toBeNull(); + expect(view.container.textContent).toContain('Sites that open without asking'); + }); +}); diff --git a/apps/desktop/test/unit/src/utils/translate.test.ts b/apps/desktop/test/unit/src/utils/translate.test.ts new file mode 100644 index 00000000..015e3b2f --- /dev/null +++ b/apps/desktop/test/unit/src/utils/translate.test.ts @@ -0,0 +1,59 @@ +import { TRANSLATE_MAX_CHARS } from '@sarvinbox/core/app-links'; +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core/logger'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { captureLogs, type CapturedLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { openTranslation, TRANSLATE_TARGET_LANGUAGE } from '../../../../src/utils/translate'; + +/** + * The Translate menu item's renderer half. What breaks if this file fails: the + * renderer builds (and so chooses) the address again instead of sending only + * the text and language to main; a long message is sent past the limit main + * enforces, so Translate refuses it; or a failure writes the message to the log. + */ + +const openTranslationIpc = vi.fn(async (_text: string, _target: string) => ({ success: true })); +let logs: CapturedLogs; + +beforeEach(() => { + openTranslationIpc.mockReset().mockResolvedValue({ success: true }); + vi.stubGlobal('window', { electronAPI: { app: { openTranslation: openTranslationIpc } } }); + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(() => { + logs.stop(); + vi.unstubAllGlobals(); +}); + +describe('openTranslation', () => { + // Breaks: an address crosses to main, or the cleaned body stops being preferred. + it('sends the cleaned body and the target language, never an address', () => { + openTranslation({ cleanBody: 'Hallo Welt', rawBody: '

raw

' }); + expect(openTranslationIpc).toHaveBeenCalledExactlyOnceWith('Hallo Welt', TRANSLATE_TARGET_LANGUAGE); + expect(TRANSLATE_TARGET_LANGUAGE).toBe('en'); + }); + + // Breaks: a long message is refused by main's limit instead of being cut to it. + it('cuts the text to TRANSLATE_MAX_CHARS, falling back to the raw body', () => { + openTranslation({ cleanBody: '', rawBody: 'y'.repeat(TRANSLATE_MAX_CHARS + 50) }); + expect(openTranslationIpc.mock.calls[0][0]).toHaveLength(TRANSLATE_MAX_CHARS); + }); + + // Breaks: a missing email or a non-string body throws in the menu handler. + it('does nothing without an email, and sends empty text for a body that is not text', () => { + openTranslation(null); + expect(openTranslationIpc).not.toHaveBeenCalled(); + openTranslation({ cleanBody: { html: 'x' } }); + expect(openTranslationIpc).toHaveBeenCalledWith('', 'en'); + }); + + // Breaks: a dead bridge is an unhandled rejection, or its log line quotes the message. + it('logs a failed hand-off by its kind only', async () => { + openTranslationIpc.mockRejectedValueOnce(new Error('IPC gone while sending SENTINEL text')); + openTranslation({ cleanBody: 'SENTINEL text' }); + await Promise.resolve(); + await Promise.resolve(); + expect(logs.containing('Translate could not be opened')).toHaveLength(1); + expect(logs.containing('SENTINEL')).toEqual([]); + }); +}); diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json index 2ac1ab0e..8b9150f0 100644 --- a/apps/desktop/tsconfig.json +++ b/apps/desktop/tsconfig.json @@ -29,8 +29,12 @@ // Same: the one dot-anchored "host is or is under domain" rule, shared // with core's provider detection. "@sarvinbox/core/host-match": ["../../packages/core/src/utils/host-match.ts"], + // Same: the pages the app's own buttons link to, which main's external-link + // gate opens without a warning — one list, so a button cannot drift off it. + "@sarvinbox/core/app-links": ["../../packages/core/src/utils/app-links.ts"], // Mirror the Vite aliases: linear trailing-slash trim and address scans. "@sarvinbox/core/trailing-slash": ["../../packages/core/src/utils/trailing-slash.ts"], + "@sarvinbox/core/truncate-middle": ["../../packages/core/src/utils/truncate-middle.ts"], "@sarvinbox/core/address-tokens": ["../../packages/core/src/utils/address-tokens.ts"], // Mirrors the Vite alias — subpath import of the pure contact-enrichment // module, so renderer and main share one implementation. diff --git a/apps/desktop/vite/renderer-aliases.ts b/apps/desktop/vite/renderer-aliases.ts index 55b38c32..14cb7407 100644 --- a/apps/desktop/vite/renderer-aliases.ts +++ b/apps/desktop/vite/renderer-aliases.ts @@ -30,8 +30,15 @@ function coreSubpathAliases(desktopDir: string): Record { // rule the SMTP prefill and core's provider detection match hosts by, // instead of a substring test that lets imap.acme.com pass for me.com. '@sarvinbox/core/host-match': resolve(desktopDir, '../../packages/core/src/utils/host-match.ts'), + // Pure (zero imports) — the pages the app's own buttons link to, and the one + // rule main's external-link gate opens without a warning (CASA 5.1.2), so a + // button's URL and the allowlist cannot drift apart. + '@sarvinbox/core/app-links': resolve(desktopDir, '../../packages/core/src/utils/app-links.ts'), // Pure (trim-chars only) — a URL without its trailing slashes, in linear time. '@sarvinbox/core/trailing-slash': resolve(desktopDir, '../../packages/core/src/utils/trailing-slash.ts'), + // Pure (zero imports) — a long text with its middle cut out, shared with + // main's external-link warning, which shortens a long address the same way. + '@sarvinbox/core/truncate-middle': resolve(desktopDir, '../../packages/core/src/utils/truncate-middle.ts'), // Pure (zero imports) — the `<…>` of "Name " and address tokens, in linear time. '@sarvinbox/core/address-tokens': resolve(desktopDir, '../../packages/core/src/utils/address-tokens.ts'), // Pure (libphonenumber-js only) — shared with core so the one implementation diff --git a/packages/core/src/utils/app-links.ts b/packages/core/src/utils/app-links.ts new file mode 100644 index 00000000..1e57da27 --- /dev/null +++ b/packages/core/src/utils/app-links.ts @@ -0,0 +1,105 @@ +/** + * The web pages the app's own UI links to, and the one rule for which links + * open in the browser without a warning (CASA 5.1.2). + * + * Main's external-link gate (`apps/desktop/electron/services/external-link-gate.ts`) + * opens a link that `isAppLink` accepts at once, because the app wrote it; every + * other address — a link in a message, a sender's unsubscribe page, a scanner + * provider's privacy policy, an extension's homepage, a sign-up page whose + * address is configuration — gets a warning that names its host first. The + * renderer's buttons import these same constants (`@sarvinbox/core/app-links`), + * so a button and the allowlist cannot drift apart: a button whose URL is not + * here shows the warning, it never opens silently. + * + * Built ONLY from addresses the code already opened before the gate existed. + * Never add a host nobody has confirmed (see "No invented Sarv hostnames"), and + * never add an address that comes from configuration or a provider. + * + * Pure and import-free, so the renderer can deep-import it without the core + * barrel. + */ + +/** The Sarv logo in the sidebar. */ +export const SARV_HOME_URL = 'https://sarv.com'; + +/** Sarv Inbox's privacy policy (the Gmail notice, Settings → Accounts). */ +export const INBOX_PRIVACY_POLICY_URL = 'https://inbox.sarv.com/privacy-policy.html'; + +/** Where a removed Google account's access is revoked by hand (Settings → Accounts). */ +export const GOOGLE_PERMISSIONS_URL = 'https://myaccount.google.com/permissions'; + +/** Where a personal Microsoft account's consent is removed by hand. */ +export const MICROSOFT_PERSONAL_CONSENT_URL = 'https://account.live.com/consent/Manage'; + +/** Where a work or school Microsoft account's apps are removed by hand. */ +export const MICROSOFT_WORK_APPS_URL = 'https://myapps.microsoft.com'; + +/** Where a web-search key for the Inbox Agent comes from (AI → Agent). */ +export const TAVILY_HOME_URL = 'https://tavily.com'; + +/** Google Translate's text page, which the Translate menu item opens with a message's text. */ +export const TRANSLATE_TEXT_URL = 'https://translate.google.com/'; + +/** How much of a message the Translate menu item sends; the renderer cuts the text to this. */ +export const TRANSLATE_MAX_CHARS = 5000; + +/** A language tag as Google Translate takes it (`en`, `pt`, `zh-CN`): letters and one subtag. */ +const TRANSLATE_TARGET = /^[a-z]{2,3}(?:-[A-Za-z]{2,4})?$/; + +/** + * The Translate menu item's address, built by MAIN from its parts: Google + * Translate's text page with the source language auto-detected, the target + * language and the text — the same `sl`, `tl` and `text` parameters, encoded + * the same way, as the renderer used to build it. Null for anything else (a + * text that is not a string or is over TRANSLATE_MAX_CHARS, a target that is + * not a language tag), so a caller can only choose WHAT is translated, never + * where the browser goes: a URL passed as the text is just text to translate. + * + * Not on APP_LINK_PAGES: a translate.google.com link in a message is a proxy to + * any site (see link-wrappers) and still gets the warning. This address opens + * without one only because main built it (`openAppBuiltUrl`). + */ +export function translationUrl(text: unknown, targetLanguage: unknown): URL | null { + if (typeof text !== 'string' || text.length > TRANSLATE_MAX_CHARS) return null; + if (typeof targetLanguage !== 'string' || !TRANSLATE_TARGET.test(targetLanguage)) return null; + return new URL(`${TRANSLATE_TEXT_URL}?sl=auto&tl=${encodeURIComponent(targetLanguage)}&text=${encodeURIComponent(text)}`); +} + +/** + * The pages the app links to, each matched EXACTLY — Sarv's own included. The + * app links to two pages on Sarv's sites, not to the sites: trusting a whole + * origin would let every page of it (any path a message names) open without + * a word, and a third-party origin is not ours to vouch for at all (a + * redirector or a proxy on it would forward anywhere). So `https://sarv.com/pricing`, + * `https://sarv.com.evil.example/`, `http://sarv.com/`, `https://www.sarv.com/` + * and the policy with a query added all get the warning. + */ +export const APP_LINK_PAGES: readonly string[] = Object.freeze( + [ + SARV_HOME_URL, + INBOX_PRIVACY_POLICY_URL, + GOOGLE_PERMISSIONS_URL, + MICROSOFT_PERSONAL_CONSENT_URL, + MICROSOFT_WORK_APPS_URL, + TAVILY_HOME_URL, + ].map((url) => new URL(url).href), +); + +/** + * Whether a link is one the app wrote, so it may open without a warning: + * exactly one of `APP_LINK_PAGES`, compared after URL parsing (so case in the + * host and a default port do not matter, and anything added to the address — + * a path, a query, a fragment, a user name — does). Anything that is not a + * parseable http(s) URL is not an app link. + */ +export function isAppLink(url: unknown): boolean { + if (typeof url !== 'string') return false; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return false; + } + if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false; + return APP_LINK_PAGES.includes(parsed.href); +} diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index 8c942c37..a1fab51d 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -6,6 +6,8 @@ export * from './logger'; export * from './validators'; export * from './provider'; export * from './host-match'; +export * from './app-links'; +export * from './link-wrappers'; export * from './oauth-imap-presets'; export * from './gmail-labels'; export * from './category-authority'; @@ -14,6 +16,7 @@ export * from './timeout'; export * from './atomic-file'; export * from './trailing-slash'; export * from './trim-chars'; +export * from './truncate-middle'; export * from './address-tokens'; export * from './error-class-name'; export * from './error-diagnostic'; diff --git a/packages/core/src/utils/link-wrappers.ts b/packages/core/src/utils/link-wrappers.ts new file mode 100644 index 00000000..0d5b66e9 --- /dev/null +++ b/packages/core/src/utils/link-wrappers.ts @@ -0,0 +1,103 @@ +/** + * Link-wrapping, redirect and proxy sites: sites whose links forward to ANY + * other site. Main's external-link gate treats them differently (CASA 5.1.2): + * + * - "Don't ask again" is never offered for them, and a remembered entry is + * never honoured. Trusting the first hop would trust every destination + * behind it: in a Microsoft 365 tenant with Safe Links, EVERY link in every + * message is `*.safelinks.protection.outlook.com`, so one tick would turn + * the warning off for all mail. + * - When the wrapper carries the destination in plain sight (a query + * parameter holding a URL), the warning also names the destination's host, + * so the user is not judging only the wrapper. The destination is shown, + * never opened directly: what opens is the link the user clicked. + * + * Deliberately short. Each entry is a well-known forwarder that real mail is + * full of; the list does not try to name every shortener on the internet (an + * unknown one still gets the warning, it can only be remembered). A domain + * matches itself and its subdomains (`hostIsOrUnder`), never a look-alike. + * + * Pure (host-match only), so it can move to the renderer if a view ever needs it. + */ +import { hostIsOrUnder } from './host-match'; + +export interface LinkWrapperRule { + /** The domain the forwarder lives on; its subdomains count too. */ + readonly domain: string; + /** Only this exact path forwards (google.com/url); absent: every path. */ + readonly path?: string; + /** Query parameters that carry the destination as a plain URL, tried in order. */ + readonly params?: readonly string[]; +} + +export const LINK_WRAPPERS: readonly LinkWrapperRule[] = Object.freeze([ + // Microsoft Defender for Office 365 Safe Links: every link in a protected + // tenant's mail, e.g. nam02.safelinks.protection.outlook.com/?url=… + { domain: 'safelinks.protection.outlook.com', params: ['url'] }, + // Google's redirector (search results, Gmail's link hand-off): google.com/url?q=… + { domain: 'google.com', path: '/url', params: ['q', 'url'] }, + // Google Translate renders any site through Google (a known phishing proxy), + // translate.google.com/translate?u=…, and the proxied sites themselves are + // served as .translate.goog. + { domain: 'translate.google.com', params: ['u'] }, + { domain: 'translate.goog' }, + // Proofpoint URL Defense (v3 and v2). The destination is encoded in their own + // scheme, so it is not unwrapped here. + { domain: 'urldefense.com' }, + { domain: 'urldefense.proofpoint.com' }, + // Shorteners: the destination is only known to their server. + { domain: 't.co' }, + { domain: 'lnkd.in' }, + // Click trackers of the large bulk-mail senders (Mailchimp, SendGrid, Mandrill). + { domain: 'list-manage.com' }, + { domain: 'sendgrid.net' }, + { domain: 'mandrillapp.com' }, +]); + +/** How many wrappers deep the destination is followed (Safe Links around a Google redirect…). */ +export const MAX_UNWRAP_HOPS = 3; + +function wrapperRuleFor(url: URL): LinkWrapperRule | undefined { + return LINK_WRAPPERS.find( + (rule) => hostIsOrUnder(url.hostname, rule.domain) && (rule.path === undefined || url.pathname === rule.path), + ); +} + +/** Whether a link goes through a known forwarder (see LINK_WRAPPERS). */ +export function isLinkWrapper(url: URL): boolean { + return wrapperRuleFor(url) !== undefined; +} + +/** The first of `names` whose value parses as an http(s) URL. */ +function httpParam(url: URL, names: readonly string[]): URL | null { + for (const name of names) { + const value = url.searchParams.get(name); + if (!value) continue; + try { + const parsed = new URL(value); + if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed; + } catch { + // Not a URL (Proofpoint's encoding, an id): nothing to show. + } + } + return null; +} + +/** + * Where a wrapped link says it goes: the URL in the wrapper's destination + * parameter, followed through up to MAX_UNWRAP_HOPS nested wrappers. Null when + * the link is not a wrapper, or the wrapper does not carry a readable http(s) + * destination. For DISPLAY only — never open the result in place of the link. + */ +export function unwrappedDestination(url: URL): URL | null { + let current = url; + let destination: URL | null = null; + for (let hop = 0; hop < MAX_UNWRAP_HOPS; hop++) { + const params = wrapperRuleFor(current)?.params; + const next = params ? httpParam(current, params) : null; + if (!next) break; + destination = next; + current = next; + } + return destination; +} diff --git a/packages/core/src/utils/truncate-middle.ts b/packages/core/src/utils/truncate-middle.ts new file mode 100644 index 00000000..49bb318d --- /dev/null +++ b/packages/core/src/utils/truncate-middle.ts @@ -0,0 +1,20 @@ +/** + * Cap a string by cutting its middle out, keeping the head and the tail: the + * start and the end of a long text are usually what tells it apart (a URL's + * host and its last path segment, a message's greeting and its sign-off). + * + * The result is at most `maxChars` long (never below head + marker + tail of + * one character each), with `marker` where the cut was. Whitespace hugging the + * cut is trimmed so a prose excerpt does not show a ragged gap. + * + * Used by the AI excerpting (renderer, `@sarvinbox/core/truncate-middle`) and by + * main's external-link warning, which shows a long address in a dialog. + * Pure and import-free, so the renderer can deep-import it. + */ +export function truncateMiddle(text: string, maxChars: number, marker = ' […] '): string { + if (text.length <= maxChars) return text; + const keep = Math.max(maxChars - marker.length, 2); + const head = Math.ceil(keep / 2); + const tail = keep - head; + return text.slice(0, head).trimEnd() + marker + text.slice(text.length - tail).trimStart(); +} diff --git a/packages/core/test/unit/utils/app-links.test.ts b/packages/core/test/unit/utils/app-links.test.ts new file mode 100644 index 00000000..c1e7773e --- /dev/null +++ b/packages/core/test/unit/utils/app-links.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'vitest'; + +import { + APP_LINK_PAGES, + GOOGLE_PERMISSIONS_URL, + INBOX_PRIVACY_POLICY_URL, + isAppLink, + MICROSOFT_PERSONAL_CONSENT_URL, + MICROSOFT_WORK_APPS_URL, + SARV_HOME_URL, + TAVILY_HOME_URL, + TRANSLATE_MAX_CHARS, + translationUrl, +} from '../../../src/utils/app-links'; + +/** + * The allowlist main's external-link gate opens without a warning (CASA 5.1.2). + * What breaks if this file fails: a link in a message opens a look-alike or + * third-party page without the warning (the allowlist matched too much), or + * the app's own buttons start showing the warning (it matched too little). + */ +describe('app links', () => { + // Breaks: the allowlist grows a page nobody added on purpose. Every entry + // here is an address the app's own UI already opened before the gate, and + // each is one page, Sarv's own included. + it('is exactly the pages the UI links to', () => { + expect(APP_LINK_PAGES).toEqual([ + 'https://sarv.com/', + 'https://inbox.sarv.com/privacy-policy.html', + 'https://myaccount.google.com/permissions', + 'https://account.live.com/consent/Manage', + 'https://myapps.microsoft.com/', + 'https://tavily.com/', + ]); + }); + + // Breaks: one of the app's own buttons shows the warning. + it.each([SARV_HOME_URL, INBOX_PRIVACY_POLICY_URL, GOOGLE_PERMISSIONS_URL, MICROSOFT_PERSONAL_CONSENT_URL, MICROSOFT_WORK_APPS_URL, TAVILY_HOME_URL])( + 'accepts the app link %s', + (url) => { + expect(isAppLink(url)).toBe(true); + }, + ); + + // Breaks: the exact-page match is thrown by case in the host or a default + // port, so the app's own Sarv link starts asking. + it('accepts an app page in any host case and with the default port', () => { + expect(isAppLink('HTTPS://SARV.COM/')).toBe(true); + expect(isAppLink('https://sarv.com:443')).toBe(true); + expect(isAppLink('https://Inbox.Sarv.com/privacy-policy.html')).toBe(true); + }); + + // Breaks: Sarv's sites are trusted as whole origins, so any page a message + // names on them opens without a word. The app links to two pages there, and + // only those two may skip the warning. + it.each([ + 'https://sarv.com/pricing', + 'https://sarv.com/?ref=mail', + 'https://sarv.com/#top', + 'https://inbox.sarv.com/', + 'https://inbox.sarv.com/anything.html', + 'https://inbox.sarv.com/privacy-policy.html?x=1', + ])('refuses %s, another page on a Sarv site', (url) => { + expect(isAppLink(url)).toBe(false); + }); + + // THE regression: a match that is a prefix or a suffix match, or ignores the + // scheme or the port, lets a look-alike open silently. + it.each([ + 'https://sarv.com.evil.example/', + 'https://evil.example/https://sarv.com', + 'https://evilsarv.com/', + 'https://www.sarv.com/', + 'https://sarv.com.:443/', + 'http://sarv.com/', + 'https://sarv.com:8443/', + 'http://inbox.sarv.com/privacy-policy.html', + 'https://sarv.com@evil.example/', + ])('refuses %s, which is another origin', (url) => { + expect(isAppLink(url)).toBe(false); + }); + + // Breaks: a third-party site becomes trusted as a whole, so any of its pages + // (a redirector, a proxy) opens from a message without a word. + it.each([ + 'https://myaccount.google.com/', + 'https://myaccount.google.com/permissions?continue=https://evil.example', + 'https://myaccount.google.com/permissions#x', + 'https://account.live.com/consent/Manage/../../redirect', + 'https://tavily.com/anything', + 'https://user@tavily.com/', + 'http://tavily.com/', + ])('refuses %s, which is not exactly an app page', (url) => { + expect(isAppLink(url)).toBe(false); + }); + + // Breaks: something that is not an http(s) URL counts as an app link. + it.each([undefined, null, 42, '', 'sarv.com', 'mailto:support@sarv.com', 'file:///sarv.com', 'javascript:alert(1)//https://sarv.com'])( + 'refuses %s, which is not an http(s) URL', + (url) => { + expect(isAppLink(url)).toBe(false); + }, + ); +}); + +describe('translationUrl (the Translate menu item, built by main)', () => { + // Breaks: the address main builds differs from what the renderer used to + // open (other parameters, other encoding), so Translate shows the wrong page. + it('builds Google Translate\'s text page with sl=auto, the target and the text', () => { + expect(translationUrl('Hello wörld & more?', 'en')?.href).toBe( + 'https://translate.google.com/?sl=auto&tl=en&text=Hello%20w%C3%B6rld%20%26%20more%3F', + ); + expect(translationUrl('', 'zh-CN')?.href).toBe('https://translate.google.com/?sl=auto&tl=zh-CN&text='); + }); + + // THE boundary: the renderer chooses what is translated, never where the + // browser goes. A URL (or parameters) in the text stays text. + it('keeps a URL or extra parameters in the text as text to translate', () => { + const url = translationUrl('https://evil.example/&u=https://evil.example', 'en')!; + expect(url.origin).toBe('https://translate.google.com'); + expect(url.pathname).toBe('/'); + expect([...url.searchParams.keys()]).toEqual(['sl', 'tl', 'text']); + expect(url.searchParams.get('text')).toBe('https://evil.example/&u=https://evil.example'); + expect(url.searchParams.has('u')).toBe(false); + }); + + // Breaks: an oversized text (longer than the menu item ever sends) or a + // non-string is accepted, or the limit is off by one. + it('takes text up to TRANSLATE_MAX_CHARS and refuses longer or non-string text', () => { + expect(TRANSLATE_MAX_CHARS).toBe(5000); + expect(translationUrl('x'.repeat(TRANSLATE_MAX_CHARS), 'en')).not.toBeNull(); + expect(translationUrl('x'.repeat(TRANSLATE_MAX_CHARS + 1), 'en')).toBeNull(); + for (const text of [undefined, null, 42, { text: 'x' }, ['x']]) expect(translationUrl(text, 'en')).toBeNull(); + }); + + // Breaks: the target language smuggles more parameters (`en&u=…`) or an + // address into the URL main builds. + it.each([undefined, '', 'EN', 'english', 'en&u=https://evil.example', 'en-', 'en-US-x', 'https://evil.example', 7])( + 'refuses the target language %s', + (target) => { + expect(translationUrl('hello', target)).toBeNull(); + }, + ); + + // Breaks: the Translate page joins the no-warning list, so a translate.google.com + // link in a message (a proxy to any site) opens without a word. + it('is not an app link: only main\'s own call opens it without the warning', () => { + expect(isAppLink(translationUrl('hello', 'en')!.href)).toBe(false); + }); +}); diff --git a/packages/core/test/unit/utils/link-wrappers.test.ts b/packages/core/test/unit/utils/link-wrappers.test.ts new file mode 100644 index 00000000..4cd249e1 --- /dev/null +++ b/packages/core/test/unit/utils/link-wrappers.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest'; + +import { isLinkWrapper, LINK_WRAPPERS, MAX_UNWRAP_HOPS, unwrappedDestination } from '../../../src/utils/link-wrappers'; + +/** + * The known link forwarders main's external-link gate never lets the user + * "trust" (CASA 5.1.2). What breaks if this file fails: + * - one "Don't ask again" on a Safe Links / Google redirect / Translate / + * shortener / click-tracker link silences the warning for every site + * behind it (in a Safe Links tenant: for all mail); + * - a look-alike of a forwarder's domain is treated as the forwarder (or an + * ordinary google.com page as a redirector); + * - the warning names a destination that is not the one in the link, or one + * that is not an http(s) URL. + */ + +const u = (url: string) => new URL(url); + +describe('isLinkWrapper', () => { + // Breaks: the list loses a forwarder real mail is full of. + it('names the agreed forwarders', () => { + expect(LINK_WRAPPERS.map((rule) => rule.domain)).toEqual([ + 'safelinks.protection.outlook.com', + 'google.com', + 'translate.google.com', + 'translate.goog', + 'urldefense.com', + 'urldefense.proofpoint.com', + 't.co', + 'lnkd.in', + 'list-manage.com', + 'sendgrid.net', + 'mandrillapp.com', + ]); + }); + + // Breaks: a forwarder link can be remembered, trusting everything behind it. + it.each([ + 'https://nam02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fevil.example%2F&data=x', + 'https://eur03.safelinks.protection.outlook.com/ap/w-59584e83/?url=https%3A%2F%2Fevil.example', + 'https://www.google.com/url?q=https://evil.example/&sa=D', + 'https://google.com/url?url=https://evil.example/', + 'https://translate.google.com/translate?sl=auto&tl=en&u=https://evil.example/', + 'https://translate.google.com/?sl=auto&tl=en&text=hello', + 'https://evil-example.translate.goog/login?_x_tr_sl=auto', + 'https://urldefense.com/v3/__https://evil.example/__;!!abc$', + 'https://urldefense.proofpoint.com/v2/url?u=https-3A__evil.example_&d=x', + 'https://t.co/AbCdEf', + 'https://lnkd.in/eXyZ', + 'https://brand.us1.list-manage.com/track/click?u=1&id=2', + 'https://u123.ct.sendgrid.net/ls/click?upn=abc', + 'https://mandrillapp.com/track/click/1/evil.example?p=abc', + 'https://T.CO./x', + ])('treats %s as a forwarder', (url) => { + expect(isLinkWrapper(u(url))).toBe(true); + }); + + // Breaks: a look-alike host passes for a forwarder (harmless alone, but it + // means the match is a substring one), or every Google page is a redirector. + it.each([ + 'https://t.co.evil.example/x', + 'https://notlnkd.in/x', + 'https://safelinks.protection.outlook.com.evil.example/?url=https://x.example', + 'https://www.google.com/search?q=https://evil.example', + 'https://www.google.com/url/extra?q=https://evil.example', + 'https://mail.google.com/mail/u/0/', + 'https://evil.example/url?q=https://other.example', + 'https://outlook.com/?url=https://evil.example', + ])('does not treat %s as a forwarder', (url) => { + expect(isLinkWrapper(u(url))).toBe(false); + }); +}); + +describe('unwrappedDestination', () => { + // Breaks: the Safe Links warning names only Microsoft's host, never where + // the link goes — every link in a protected tenant looks the same. + it('reads the destination out of Safe Links, Google and Translate links', () => { + expect(unwrappedDestination(u('https://nam02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fevil.example%2Flogin&data=05'))?.href) + .toBe('https://evil.example/login'); + expect(unwrappedDestination(u('https://www.google.com/url?q=https://evil.example/a&sa=D'))?.hostname).toBe('evil.example'); + expect(unwrappedDestination(u('https://www.google.com/url?sa=D&url=http://evil.example/'))?.hostname).toBe('evil.example'); + expect(unwrappedDestination(u('https://translate.google.com/translate?sl=auto&u=https://evil.example/'))?.hostname).toBe('evil.example'); + }); + + // Breaks: a look-alike Unicode destination is named as the brand it imitates. + it('gives the destination host in punycode', () => { + const wrapped = `https://nam02.safelinks.protection.outlook.com/?url=${encodeURIComponent('https://pаypal.com/')}`; + expect(unwrappedDestination(u(wrapped))?.hostname).toBe('xn--pypal-4ve.com'); + }); + + // Breaks: nested wrappers (Safe Links around a Google redirect) name the + // inner wrapper instead of the real destination — or the loop is unbounded. + it('follows nested wrappers, at most MAX_UNWRAP_HOPS deep', () => { + const google = `https://www.google.com/url?q=${encodeURIComponent('https://evil.example/x')}`; + const safe = `https://nam02.safelinks.protection.outlook.com/?url=${encodeURIComponent(google)}`; + expect(unwrappedDestination(u(safe))?.hostname).toBe('evil.example'); + + let deep = 'https://final.example/'; + for (let i = 0; i < MAX_UNWRAP_HOPS + 2; i++) deep = `https://www.google.com/url?q=${encodeURIComponent(deep)}`; + const shown = unwrappedDestination(u(deep)); + expect(shown?.hostname).toBe('www.google.com'); + }); + + // Breaks: a destination that is not a web address (javascript:, a file, an + // id, Proofpoint's encoding) is named, or the first param shadows a valid second. + it('names nothing that is not an http(s) URL', () => { + expect(unwrappedDestination(u('https://www.google.com/url?q=javascript:alert(1)'))).toBeNull(); + expect(unwrappedDestination(u('https://www.google.com/url?q=file:///etc/passwd'))).toBeNull(); + expect(unwrappedDestination(u('https://www.google.com/url?q=not%20a%20url'))).toBeNull(); + expect(unwrappedDestination(u('https://www.google.com/url?q=&url=https://evil.example/'))?.hostname).toBe('evil.example'); + expect(unwrappedDestination(u('https://urldefense.proofpoint.com/v2/url?u=https-3A__evil.example_'))).toBeNull(); + expect(unwrappedDestination(u('https://t.co/AbCdEf'))).toBeNull(); + expect(unwrappedDestination(u('https://nam02.safelinks.protection.outlook.com/?data=05'))).toBeNull(); + }); + + // Breaks: an ordinary link with a url= parameter is "unwrapped". + it('names nothing for a link that is not a forwarder', () => { + expect(unwrappedDestination(u('https://shop.example/redirect?url=https://evil.example/'))).toBeNull(); + }); +}); diff --git a/packages/core/test/unit/utils/truncate-middle.test.ts b/packages/core/test/unit/utils/truncate-middle.test.ts new file mode 100644 index 00000000..5e15d729 --- /dev/null +++ b/packages/core/test/unit/utils/truncate-middle.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; + +import { truncateMiddle } from '../../../src/utils/truncate-middle'; + +/** + * The one "cut the middle out" helper, shared by the AI thread excerpts and the + * external-link warning. What breaks if this file fails: a long address in the + * warning loses its host (the start) or its last segment (the end), or grows + * past the dialog's limit; or the AI excerpts change shape under the prompts. + */ +describe('truncateMiddle', () => { + // Breaks: short text is altered. + it('returns text at or under the limit unchanged', () => { + expect(truncateMiddle('abc', 3)).toBe('abc'); + expect(truncateMiddle('', 0)).toBe(''); + }); + + // Breaks: the AI excerpts' default marker or their whitespace trimming changes. + it('keeps the head and the tail around the default marker, trimming the cut', () => { + const out = truncateMiddle(`${'a'.repeat(10)} ${'b'.repeat(10)}`, 15); + expect(out).toBe(`aaaaa […] bbbbb`); + expect(out.length).toBeLessThanOrEqual(15); + }); + + // Breaks: a long URL in the link warning is not bounded, or loses either end. + it('bounds a long URL with a one-character marker, keeping both ends', () => { + const url = `https://evil.example/${'x'.repeat(500)}/last-segment`; + const out = truncateMiddle(url, 200, '…'); + expect(out).toHaveLength(200); + expect(out.startsWith('https://evil.example/')).toBe(true); + expect(out.endsWith('/last-segment')).toBe(true); + expect(out).toContain('…'); + }); + + // Breaks: a limit smaller than the marker yields nothing usable. + it('keeps at least one character on each side when the limit is tiny', () => { + expect(truncateMiddle('abcdefghij', 1, '…')).toBe('a…j'); + }); +}); From 02c319acf5248c6d6533a47b7b94104f124e8db0 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Wed, 2 Dec 2026 22:44:05 +0530 Subject: [PATCH 08/13] fix(security): trust only the certificate the user approved CASA 4.1.2 (TAC review of 25 Nov): "allow self-signed" turned certificate checking off for the account, so any certificate was accepted for it. - resolveTlsOptions always verifies (rejectUnauthorized: true, TLS 1.2 floor). A password account may instead trust exactly one approved leaf certificate per account, transport, host and port: the approved PEM is the only trust anchor (ca + allowPartialTrustChain, which Electron's BoringSSL needs) and checkServerIdentity accepts only its SHA-256. Every other certificate is refused inside the handshake, before LOGIN or AUTH is sent. OAuth accounts never use a pin. - Main applies the pin before every dial (imap:connect, the add-account probe, background sync, smtp:connect/connectFor, the Inbox Agent download) and always replaces any pin the window sent. - Approval happens only in main's native dialog (subject, issuer, validity, SHA-256; Cancel is the default) and only for a connect the user just started: the form arms a review for that account and transport (used once, 60 s, rate-limited). Automatic reconnects and background sync never ask; they refuse and the banner points to Settings -> Accounts. The retry after approval goes to the account that asked, or nowhere. Wording comes from main's own records. An existing pin is named when a new one would replace it. Expired certificates cannot be approved. - Pins live in the vault and are written with a throwing core-DB write (writeBlob); the vault is read with the strict read, so an unreadable store is an error, never an empty vault. - Accounts saved with "allow self-signed" are refused on their next automatic connect and review their server's certificate once from Settings. The checkbox is gone; account settings show the trusted certificate with Remove. - The only socket with verification off fetches a certificate to show it and carries no credential; a guard test fails on any other rejectUnauthorized, NODE_TLS_REJECT_UNAUTHORIZED or checkServerIdentity in product code. Pre-existing tests changed deliberately (the old setting is retired): tls.test.ts and smtp-client.test.ts (allowInsecureTLS no longer turns checks off), connection-security.test.ts (transport opt-ins cover encryption only), imapflow-client-starttls.test.ts (a certificate error is its own refusal); secure-credential-store, vault-credentials and helpers tests (the setting is no longer written or bound); imap-vault-password, smtp-vault-password, imap-connect-security, imap-oauth-host-binding and assistant-mailbox-download (old-setting cases become verified connections; the security event carries a code); reset-and-reconnect (its partial core mock gained the real TLS module); connection-security-ui, EmailSetupStep and IMAPStep (no checkbox; the probe passes an account id). --- CHANGELOG.md | 24 + CLAUDE.md | 33 +- README.md | 5 +- .../electron/ipc/certificate-handlers.ts | 74 +++ apps/desktop/electron/ipc/index.ts | 2 + apps/desktop/electron/ipc/smtp-handlers.ts | 75 ++- apps/desktop/electron/ipc/sync-handlers.ts | 102 +++- apps/desktop/electron/preload.ts | 62 +- .../services/__testing__/fake-core-db.ts | 7 + .../services/assistant-mailbox-download.ts | 9 +- .../electron/services/certificate-trust.ts | 562 ++++++++++++++++++ apps/desktop/electron/services/core-db.ts | 22 +- .../services/secure-credential-store.ts | 121 +++- .../electron/services/vault-credentials.ts | 60 +- apps/desktop/src/App.tsx | 12 +- .../src/components/ConnectionDialog.tsx | 13 +- .../components/ConnectionSecurityBanner.tsx | 36 +- .../desktop/src/components/SmtpConfigForm.tsx | 22 +- .../src/components/TrustedCertificate.tsx | 122 ++++ .../components/onboarding/EmailSetupStep.tsx | 32 +- .../src/components/onboarding/IMAPStep.tsx | 15 +- .../src/components/security/Security.tsx | 2 +- .../src/components/settings/AccountsTab.tsx | 20 +- apps/desktop/src/store/helpers.ts | 17 +- .../src/store/slices/connection-slice.ts | 36 +- apps/desktop/src/store/types.ts | 10 + apps/desktop/src/utils/certificate-review.ts | 30 + .../electron/ipc/certificate-approval.test.ts | 446 ++++++++++++++ .../electron/ipc/certificate-handlers.test.ts | 120 ++++ .../ipc/imap-connect-security.test.ts | 57 +- .../ipc/imap-oauth-host-binding.test.ts | 13 +- .../electron/ipc/imap-vault-password.test.ts | 71 ++- .../electron/ipc/reset-and-reconnect.test.ts | 2 + .../electron/ipc/smtp-vault-password.test.ts | 89 +-- .../assistant-mailbox-download.test.ts | 41 +- .../services/certificate-trust.test.ts | 547 +++++++++++++++++ .../services/core-db-write-blob.test.ts | 47 ++ .../services/secure-credential-store.test.ts | 171 +++++- .../services/vault-credentials.test.ts | 137 +++-- .../components/TrustedCertificate.test.tsx | 96 +++ .../connection-security-ui.test.tsx | 93 ++- .../onboarding/EmailSetupStep.test.tsx | 44 +- .../components/onboarding/IMAPStep.test.tsx | 6 +- .../test/unit/src/store/helpers.test.ts | 18 +- .../slices/connection-security-issue.test.ts | 55 ++ .../unit/src/utils/certificate-review.test.ts | 49 ++ docs/TESTING.md | 11 + packages/core/src/imap/connection-manager.ts | 13 +- packages/core/src/imap/connection-pool.ts | 10 +- packages/core/src/imap/imap-errors.ts | 14 + packages/core/src/imap/imapflow-client.ts | 17 +- packages/core/src/imap/index.ts | 1 + packages/core/src/imap/sync-engine.ts | 13 +- packages/core/src/smtp/smtp-client.ts | 25 +- .../core/src/test-support/tls-test-servers.ts | 279 +++++++++ packages/core/src/types/imap.ts | 17 +- packages/core/src/types/smtp.ts | 18 +- .../core/src/utils/certificate-inspection.ts | 245 ++++++++ .../core/src/utils/connection-security.ts | 60 +- packages/core/src/utils/index.ts | 1 + packages/core/src/utils/tls.ts | 210 ++++++- .../utils/certificate-pin.integration.test.ts | 360 +++++++++++ .../core/test/unit/imap/imap-errors.test.ts | 20 + .../imap/imapflow-client-starttls.test.ts | 66 +- .../core/test/unit/smtp/smtp-client.test.ts | 40 +- .../unit/utils/certificate-inspection.test.ts | 130 ++++ .../unit/utils/connection-security.test.ts | 43 +- .../core/test/unit/utils/tls-guard.test.ts | 97 +++ packages/core/test/unit/utils/tls.test.ts | 189 ++++-- 69 files changed, 4935 insertions(+), 571 deletions(-) create mode 100644 apps/desktop/electron/ipc/certificate-handlers.ts create mode 100644 apps/desktop/electron/services/certificate-trust.ts create mode 100644 apps/desktop/src/components/TrustedCertificate.tsx create mode 100644 apps/desktop/src/utils/certificate-review.ts create mode 100644 apps/desktop/test/unit/electron/ipc/certificate-approval.test.ts create mode 100644 apps/desktop/test/unit/electron/ipc/certificate-handlers.test.ts create mode 100644 apps/desktop/test/unit/electron/services/certificate-trust.test.ts create mode 100644 apps/desktop/test/unit/electron/services/core-db-write-blob.test.ts create mode 100644 apps/desktop/test/unit/src/components/TrustedCertificate.test.tsx create mode 100644 apps/desktop/test/unit/src/utils/certificate-review.test.ts create mode 100644 packages/core/src/test-support/tls-test-servers.ts create mode 100644 packages/core/src/utils/certificate-inspection.ts create mode 100644 packages/core/test/integration/utils/certificate-pin.integration.test.ts create mode 100644 packages/core/test/unit/utils/certificate-inspection.test.ts create mode 100644 packages/core/test/unit/utils/tls-guard.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8215ded3..d8230072 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 account pages it points you to), the message menu's **Translate** command and email addresses open as before; other pages on Sarv's sites ask like any other link. +- **A mail server with its own certificate is trusted only for that exact + certificate.** The "Allow self-signed / invalid certificates" box is gone: it + made Sarv Inbox accept any certificate at all for that account. Now, when you + add a password account, test it, or reconnect it or verify sending in + Settings → Accounts, and its server presents a certificate your system does + not trust (a self-signed certificate, or one from your company's own + authority), Sarv Inbox shows it to you before sending anything: the server, + who issued it, its dates and its SHA-256 fingerprint. Choose **Trust this + certificate** only if it matches what your administrator gave you. From then + on that account accepts exactly that certificate from that server and port, + and refuses every other one, including a renewed certificate. An expired + certificate cannot be approved. The account's settings show the trusted + certificate's fingerprint and when you approved it, with **Remove**. +- **Sarv Inbox never asks about a certificate on its own.** A reconnect after + waking, a change of network or background syncing that meets a certificate it + does not trust stops before sending your password and shows a banner instead; + you review the certificate by reconnecting the account in Settings → + Accounts. So someone on a public network cannot make a trust question pop up + for you to click. Accounts that signed in with Google, Microsoft or Sarv are + not affected: their certificates are always checked as before. +- **Accounts set up with "allow self-signed" need one review.** After this + update they stop connecting until you open Settings → Accounts and reconnect + them; you then see the certificate their server presents, once. Approve it and + they carry on as before. ## [1.5.0] - 2026-11-25 diff --git a/CLAUDE.md b/CLAUDE.md index a3066b72..f2783ad8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -243,7 +243,34 @@ Established shared helpers (extend this list as you add more): (renderer: `@sarvinbox/core/connection-security`). The one rule for how an IMAP/SMTP connection is secured: 'ssl' | 'starttls' (upgrade REQUIRED) | 'none' (explicit opt-out); legacy configs resolve from `secure`, OAuth never to 'none'. - Use it in clients and account forms instead of reading `secure`. + Use it in clients and account forms instead of reading `secure`. Its + `TransportOptIns` is encryption only (`allowPlaintext`): the old + `allowInsecureTLS` ("allow self-signed") is retired and ignored everywhere. +- `resolveTlsOptions(config)` — `packages/core/src/utils/tls.ts`. The ONLY place + a mail connection's TLS options are built: always `rejectUnauthorized: true` + with a TLS 1.2 floor; with a `certificatePin` (password accounts only) the + approved leaf is the sole trust anchor (`ca` + `allowPartialTrustChain`, which + Electron's BoringSSL needs) and `checkServerIdentity` accepts only that exact + SHA-256. Never set `rejectUnauthorized` anywhere else — + `test/unit/utils/tls-guard.test.ts` fails if you do; the one exception is + `inspectServerCertificate` (`certificate-inspection.ts`), which fetches a + certificate to SHOW and carries no credential. `isCertificateUntrustedError` / + `CERTIFICATE_UNTRUSTED` classify a refused handshake. +- `applyCertificatePin(config, kind, ids)` / `withCertificateApproval(attempt, request, { sameTarget })` — + `apps/desktop/electron/services/certificate-trust.ts`. Every main connect path + puts the account's approved certificate (or none) on the config right before + dialling — replacing any pin the window sent. The trust question is NEVER + asked automatically: only a connect the user started from a form, which the + form arms first with `certificates:review` (`allowCertificateReview(id, kind)` + in the renderer; one account+kind, used by the next connect, 60 s, rate- + limited), may ask in main's own dialog and retry once — for the same + `sameTarget` (the account on screen) or not at all. Reconnect ladders, + background sync, the pool and the Inbox Agent get the refusal at once. Use + `applyCertificatePin` for any new IMAP/SMTP connect path, and the wrapper only + for a user-started one; OAuth never gets a pin. Pins live in the vault + (`AccountSecrets.certificates`), written only by `setAccountCertificatePin` + with the throwing `writeBlob`. The renderer's `connectAccountId(accounts, + email, host)` (store/helpers.ts) is the id a connect runs as — arm with it. - `createLogBudget()` / `writeExtensionLog(logger, budget, line)` / `extensionDebugEnabled()` — `packages/core/src/extensions/runtime/log-budget.ts`. How many lines a stranger's code may have the main process write, and the one @@ -378,7 +405,9 @@ Established shared helpers (extend this list as you add more): - `readBlob(key)` — `apps/desktop/electron/services/core-db.ts`. A core-DB blob, or null when there is none; THROWS when the store cannot be read, where `getBlob` answers null. Use it for any store whose readers decide what is gone or what to - overwrite (the OAuth token store does). + overwrite (the OAuth token store and the credential vault do). Its twin + `writeBlob(key, data)` THROWS on a failed write, where `setBlob` only logs: + use it for any write the user is told succeeded (an approved certificate). - `trimChars` / `trimCharsStart` / `trimCharsEnd(value, set)` — `packages/core/src/utils/trim-chars.ts` (and `trimTrailingSlashes(value)` in `trailing-slash.ts`, built on it). Trim a set of characters (a string, or a diff --git a/README.md b/README.md index 1281909c..ca84518d 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,9 @@ product, or removing the Sarv branding needs our written permission — see - **Smart categorization** — AI labels (Important, Needs Response, Meetings, Invoices, …) with a customizable, section-based inbox. - **Privacy-first** — mail is stored encrypted on your device, message text - reaches an AI provider only once you connect one, and TLS verification is on - by default. + reaches an AI provider only once you connect one, and mail servers' + certificates are always verified (a server with its own certificate is + trusted only for the exact certificate you approve). - **Cross-platform** — macOS, Windows and Linux (Electron). ## Getting started diff --git a/apps/desktop/electron/ipc/certificate-handlers.ts b/apps/desktop/electron/ipc/certificate-handlers.ts new file mode 100644 index 00000000..39573685 --- /dev/null +++ b/apps/desktop/electron/ipc/certificate-handlers.ts @@ -0,0 +1,74 @@ +/** + * IPC surface for approved mail-server certificates (CASA 4.1.2). + * + * The window can SEE an account's approved certificates (fingerprint, server, + * date — no PEM) and REMOVE one, and it can say the user just started a connect + * from a form (`certificates:review`): only such an armed connect may ask about + * an untrusted certificate, once, rate-limited. It can never approve one: + * approval happens only in main's own dialog, during that connect + * (certificate-trust.ts). + */ +import { createLogger, failureCause } from '@sarvinbox/core'; +import { ipcMain } from 'electron'; + +import { + armCertificateReview, + listAccountCertificates, + removeAccountCertificate, +} from '../services/certificate-trust'; +import { getCurrentAccountId, getSmtpClient, getSmtpClientFor, getSyncEngineFor } from '../shared'; + +const logger = createLogger('certificate-handlers'); + +const isKind = (value: unknown): value is 'imap' | 'smtp' => value === 'imap' || value === 'smtp'; +const isAccountId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 512; + +/** + * Close the account's live connections of `kind`, which were opened while the + * removed certificate was trusted: the removal takes effect now, not at the + * next network blip. Best-effort. + */ +async function closeConnections(accountId: string, kind: 'imap' | 'smtp'): Promise { + try { + if (kind === 'imap') { + await getSyncEngineFor(accountId)?.disconnect(); + return; + } + await getSmtpClientFor(accountId)?.disconnect(); + if (getCurrentAccountId() === accountId) await getSmtpClient()?.disconnect(); + } catch (error) { + logger.warn(`[Certificates] closing the ${kind} connections after a removal failed (${failureCause(error)})`); + } +} + +export function registerCertificateHandlers(): void { + ipcMain.handle('certificates:list', async (_event, accountId: unknown) => { + if (!isAccountId(accountId)) return { success: false, error: 'An account is required.' }; + try { + return { success: true, data: await listAccountCertificates(accountId) }; + } catch (error) { + logger.warn(`[Certificates] could not list approved certificates (${failureCause(error)})`); + return { success: false, error: 'Approved certificates could not be read. Try again in a moment.' }; + } + }); + + ipcMain.handle('certificates:remove', async (_event, accountId: unknown, kind: unknown) => { + if (!isAccountId(accountId) || !isKind(kind)) return { success: false, error: 'An account and a server kind are required.' }; + try { + const removed = await removeAccountCertificate(accountId, kind); + if (removed) await closeConnections(accountId, kind); + return { success: true, data: { removed } }; + } catch (error) { + logger.warn(`[Certificates] could not remove an approved certificate (${failureCause(error)})`); + return { success: false, error: 'The approved certificate could not be removed. Try again in a moment.' }; + } + }); + + // The user just started a connect for this account's `kind` server from a + // form: that connect (the next one, within a minute) may ask about an + // untrusted certificate. Rate-limited per account+kind and overall. + ipcMain.handle('certificates:review', async (_event, accountId: unknown, kind: unknown) => { + if (!isAccountId(accountId) || !isKind(kind)) return { success: false, error: 'An account and a server kind are required.' }; + return { success: true, data: { armed: armCertificateReview(accountId, kind) === 'armed' } }; + }); +} diff --git a/apps/desktop/electron/ipc/index.ts b/apps/desktop/electron/ipc/index.ts index e32c9140..a93e491f 100644 --- a/apps/desktop/electron/ipc/index.ts +++ b/apps/desktop/electron/ipc/index.ts @@ -13,6 +13,7 @@ import { registerAIHandlers } from './ai-handlers'; import { registerAntivirusHandlers } from './antivirus-handlers'; import { registerAppHandlers } from './app-handlers'; import { registerCalendarHandlers } from './calendar-handlers'; +import { registerCertificateHandlers } from './certificate-handlers'; import { registerContactEnrichmentHandlers } from './contact-enrichment-handlers'; import { registerContactsHandlers } from './contacts-handlers'; import { registerDefaultAppHandlers } from './default-app-handlers'; @@ -75,6 +76,7 @@ export function registerAllHandlers(): void { registerLabelHandlers(); registerAccountsHandlers(); registerSecureCredentialsHandlers(); + registerCertificateHandlers(); registerNotificationHandlers(); registerStorageHandlers(); registerIdentityHandlers(); diff --git a/apps/desktop/electron/ipc/smtp-handlers.ts b/apps/desktop/electron/ipc/smtp-handlers.ts index f9e56e33..34ac83be 100644 --- a/apps/desktop/electron/ipc/smtp-handlers.ts +++ b/apps/desktop/electron/ipc/smtp-handlers.ts @@ -7,7 +7,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { folderLogLabel, SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, withFolderSelected, messageIdKey, parseAddresses, STARTTLS_UNAVAILABLE, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; +import { folderLogLabel, SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, isCertificateUntrustedError, withFolderSelected, messageIdKey, parseAddresses, resolveConnectionSecurity, STARTTLS_UNAVAILABLE, CERTIFICATE_UNTRUSTED, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; import { PGP_ENCRYPTED_PLACEHOLDER, PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, bodyLengthFromParam, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, dialog } from 'electron'; @@ -15,6 +15,7 @@ import { ipcMain, dialog } from 'electron'; import { registryAccountEmail } from '../services/accounts-registry'; import { ensureAccountRuntime } from '../services/accounts-runtime'; import { seedAttachmentCache } from '../services/attachment-cache'; +import { applyCertificatePin, requestingWindow, withCertificateApproval, type CertificateTrustRequest } from '../services/certificate-trust'; import { CalendarInvitationValidationError, getLocalCalendarInvitationService } from '../services/local-calendar-invitations'; import { getAccessTokenForMailHost } from '../services/oauth-service'; import { getOutboxQueue, drainOutbox, getOutboxQueueForAccount, drainOutboxForAccount, notifyOutboxChanged } from '../services/outbox-service'; @@ -67,34 +68,59 @@ function getMimeType(filename: string): string { } /** - * A password-auth SMTP config with its password filled in from the vault. + * A password-auth SMTP config with its password filled in from the vault, and + * the certificate this account approved for its sending server (or none). * The renderer never holds stored passwords, so a saved account's config * arrives without one; main injects it — but only for the host it was saved * for, and no more loosely than it was saved for (vault-credentials.ts), since * the config comes from the renderer. `saved` is the vault hit, for * `narrowSavedTransport` once the connection works. - * Configs that already carry a password (the user just typed it) or use - * OAuth pass through unchanged. + * A config that already carries a password (the user just typed it) keeps it; + * OAuth gets no password and no pin. Every config leaves with exactly main's + * pin — the one SMTP entry point for both connect handlers. */ export async function withVaultSmtpPassword( config: SMTPConfig, accountId: string | undefined, ): Promise<{ config: SMTPConfig; saved?: VaultPasswordFound }> { - if (config.authMethod === 'oauth2' || config.password) return { config }; - const vaulted = await resolveVaultPassword(vaultIdCandidates(accountId, config.username, config.host), 'smtp', config.host); + const ids = vaultIdCandidates(accountId, config.username, config.host); + if (config.authMethod === 'oauth2' || config.password) return { config: await applyCertificatePin(config, 'smtp', ids) }; + const vaulted = await resolveVaultPassword(ids, 'smtp', config.host); if (vaulted.status !== 'found') { throw new Error(vaultRefusalMessage('smtp', config.host, vaulted) ?? `No sending password saved for ${config.host} — set up sending for this account.`); } const applied = withSavedPassword(config, 'smtp', vaulted); if ('refusal' in applied) throw new Error(applied.refusal); - return { config: applied.config, saved: vaulted }; + return { config: await applyCertificatePin(applied.config, 'smtp', ids), saved: vaulted }; +} + +/** + * Whom to ask when an ARMED SMTP connect was refused over its certificate, or + * null for OAuth. What the dialog says about the account comes from main's own + * records, never from this config. + */ +function smtpCertificateRequest(event: unknown, config: SMTPConfig, accountId: string | undefined): CertificateTrustRequest | null { + if (!config || config.authMethod === 'oauth2' || !config.host) return null; + return { + kind: 'smtp', + ids: vaultIdCandidates(accountId, config.username, config.host), + host: config.host, + port: config.port, + security: resolveConnectionSecurity(config), + window: requestingWindow(event), + }; } export function registerSmtpHandlers(): void { /** * Connect to SMTP server */ - ipcMain.handle('smtp:connect', async (_event, config: SMTPConfig, accountId?: string) => { + // Refused over the certificate (CASA 4.1.2): only a connect the user started + // from a form (armed) asks, in main's dialog, and on approval connects once + // more with the new pin — on the client of the account still on screen, or + // not at all. Startup and lazy-send connects get the refusal at once. + ipcMain.handle('smtp:connect', (event, original: SMTPConfig, accountId?: string) => withCertificateApproval(async () => { + let config = original; try { const vaulted = await withVaultSmtpPassword(config, accountId); config = vaulted.config; @@ -117,9 +143,9 @@ export function registerSmtpHandlers(): void { }; } - // Certificate checks are decided in core (resolveTlsOptions): on unless a - // password account opted out, and the opt-out of a saved password is the - // one saved with it (withVaultSmtpPassword). + // Certificate checks are decided in core (resolveTlsOptions): always on, + // and a pinned password account accepts exactly its approved certificate + // (withVaultSmtpPassword). await smtpClient.connect(config); logger.info('[SMTP] Connected successfully'); if (vaulted.saved) await narrowSavedTransport('smtp', vaulted.saved, config); @@ -133,13 +159,18 @@ export function registerSmtpHandlers(): void { if (isStarttlsRefusedError(error)) { return { success: false, error: (error as Error).message, code: STARTTLS_UNAVAILABLE }; } + // The sending server's certificate is not trusted (CASA 4.1.2); the + // client already said so in one line, before AUTH. + if (isCertificateUntrustedError(error)) { + return { success: false, error: (error as Error).message, code: CERTIFICATE_UNTRUSTED }; + } logger.error('SMTP connect error:', error); return { success: false, error: (error as Error).message, }; } - }); + }, () => smtpCertificateRequest(event, original, accountId), { sameTarget: () => getCurrentAccountId() })); /** * Disconnect from SMTP server @@ -186,11 +217,16 @@ export function registerSmtpHandlers(): void { // Connect a SPECIFIC account's SMTP on demand (multi-account send-as). The // renderer supplies the target account's SMTPConfig (main doesn't store it). // Idempotent: no-op if that account's client is already connected. - ipcMain.handle('smtp:connectFor', async (_event, accountId: string, config: SMTPConfig) => { + ipcMain.handle('smtp:connectFor', (event, accountId: string, config: SMTPConfig) => withCertificateApproval(async () => { try { if (!accountId || !config) return { success: false, error: 'accountId + config required' }; if (getSmtpClientFor(accountId)?.isConnected()) return { success: true }; - await ensureAccountRuntime(accountId); // ensure the runtime slot exists + // The runtime slot the client is stored in. Registry-checked: no slot + // (and no database) for an account that is not configured — and nothing + // connected or vault password read for it either. + if (!(await ensureAccountRuntime(accountId))) { + return { success: false, error: `Account ${accountId} is not available` }; + } const vaulted = await withVaultSmtpPassword(config, accountId); let cfg = vaulted.config; if (cfg.authMethod === 'oauth2') { @@ -205,10 +241,13 @@ export function registerSmtpHandlers(): void { drainOutboxForAccount(accountId).catch((e) => logger.warn('[SMTP] connectFor drain failed:', e)); return { success: true }; } catch (error) { + if (isCertificateUntrustedError(error)) { + return { success: false, error: (error as Error).message, code: CERTIFICATE_UNTRUSTED }; + } logger.error('[SMTP] connectFor error:', error); return { success: false, error: (error as Error).message }; } - }); + }, () => (accountId ? smtpCertificateRequest(event, config, accountId) : null))); ipcMain.handle('smtp:send', async (_event, options: SendEmailOptions) => { try { @@ -512,6 +551,10 @@ export async function sendEmailFromMain( } } const scoped = !!acctId && acctId !== getCurrentAccountId(); + // Whose storage `scopedStorage` is, fixed NOW: the post-send draft cleanup + // runs after the network round-trip, and an account switch in between must + // not re-point it at whichever account became active meanwhile. + const sendingAccountId = scoped ? acctId! : getCurrentAccountId(); const smtpClient = scoped ? getSmtpClientFor(acctId!) : getSmtpClient(); const scopedStorage = scoped ? getStorageFor(acctId!) : getStorage(); const scopedSyncEngine = scoped ? getSyncEngineFor(acctId!) : getSyncEngine(); @@ -606,7 +649,7 @@ export async function sendEmailFromMain( try { const answeredThreadId = await markThreadRepliesAnswered(scopedStorage, options.inReplyTo); if (answeredThreadId) { - await deleteDraftsForThread(acctId, answeredThreadId); + await deleteDraftsForThread(sendingAccountId, answeredThreadId); } } catch (err) { logger.warn('[SMTP] Post-send thread cleanup (proposals/drafts) failed (non-fatal):', err); diff --git a/apps/desktop/electron/ipc/sync-handlers.ts b/apps/desktop/electron/ipc/sync-handlers.ts index bc199411..5177760f 100644 --- a/apps/desktop/electron/ipc/sync-handlers.ts +++ b/apps/desktop/electron/ipc/sync-handlers.ts @@ -5,7 +5,7 @@ */ import type { IMAPConfig, SyncEngineOptions } from '@sarvinbox/core'; -import { failureCause, folderLogLabel, accountLogLabel, withTimeout, transportOptInsOf, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, STARTTLS_UNAVAILABLE } from '@sarvinbox/core'; +import { failureCause, folderLogLabel, accountLogLabel, withTimeout, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isCertificateUntrustedError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, resolveConnectionSecurity, STARTTLS_UNAVAILABLE, CERTIFICATE_UNTRUSTED } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { identifyClient } from '../sentry'; @@ -14,6 +14,7 @@ import { ensureAccountRuntime, accountInboxUnread, accountDbExists } from '../se // file, so a runtime require() throws "Cannot find module". import { kickBackfillScheduler } from '../services/backfill-scheduler'; import { kickBodyPrefetchScheduler } from '../services/body-prefetch-scheduler'; +import { applyCertificatePin, requestingWindow, withCertificateApproval, type CertificateTrustRequest } from '../services/certificate-trust'; import { markConnectionUnstable } from '../services/connection-health'; import { saveImapAccount, loadImapAccount, clearImapAccount, forgetImapAccountFor } from '../services/imap-account-store'; import { getAccessTokenForMailHost, attachImapBearer } from '../services/oauth-service'; @@ -78,6 +79,25 @@ function resolveVaultImapPassword( return resolveVaultPassword(vaultIdCandidates(accountId, username, host), 'imap', host); } +/** + * Whom to ask when an ARMED IMAP connect was refused over its certificate (CASA + * 4.1.2), or null for OAuth, which never uses pins. The server and port are the + * ones the connect dialled, and a pin approved is bound to exactly them; what + * the dialog says about the account comes from main's own records, never from + * this config. + */ +function imapCertificateRequest(event: unknown, config: IMAPConfig, accountId: string | undefined): CertificateTrustRequest | null { + if (!config || config.authMethod === 'oauth2' || !config.host) return null; + return { + kind: 'imap', + ids: vaultIdCandidates(accountId, config.username, config.host), + host: config.host, + port: config.port, + security: resolveConnectionSecurity(config), + window: requestingWindow(event), + }; +} + /** * Resolve the vault password as a PROMISE that settles the instant the data is * available, then the caller proceeds — no fixed delay. At app launch the connect @@ -123,7 +143,7 @@ function resolveVaultImapPasswordWaiting( * Shared by the `imap:probeCredentials` IPC (gating account overwrites) and the * oauth2→password self-heal in `imap:connect`. */ -async function probeImapCredentials(config: IMAPConfig): Promise<{ success: boolean; error?: string }> { +async function probeImapCredentials(config: IMAPConfig): Promise<{ success: boolean; error?: string; code?: string }> { const client = new ImapFlowClient(); // A probe reports its outcome purely through connect()'s resolve/reject, so // silence the client's own error channel BEFORE connecting. This is not @@ -144,7 +164,8 @@ async function probeImapCredentials(config: IMAPConfig): Promise<{ success: bool } catch (error) { // Expected outcome for bad credentials — log at info, not error. logger.info('[Main] probeCredentials rejected:', (error as Error).message); - return { success: false, error: (error as Error).message }; + // An untrusted certificate is tagged, so the caller can offer it for review. + return { success: false, error: (error as Error).message, ...(isCertificateUntrustedError(error) ? { code: CERTIFICATE_UNTRUSTED } : {}) }; } finally { // Never leave the probe socket open, even when connect() threw midway. try { await client.disconnect(); } catch { /* nothing to tear down */ } @@ -372,7 +393,18 @@ export function registerSyncHandlers(): void { /** * Connect to IMAP server */ - ipcMain.handle('imap:connect', async (_event, config: IMAPConfig, accountId?: string) => { + // A connect refused over the server's certificate (CASA 4.1.2): when the + // user started it from a form (armed via certificates:review), main asks in + // its own dialog and, on approval, connects once more with the new pin — for + // the account still on screen, or not at all. Focus/online reconnects are not + // armed: they get the refusal at once, and the window points to the settings. + ipcMain.handle('imap:connect', (event, config: IMAPConfig, accountId?: string) => withCertificateApproval( + () => connectImap(config, accountId), + () => imapCertificateRequest(event, config, accountId), + { sameTarget: () => getCurrentAccountId() }, + )); + + async function connectImap(config: IMAPConfig, accountId?: string) { // App is shutting down — refuse to (re)establish connections. The renderer's // periodic timers keep firing during teardown; without this they resurrect // the IMAP connection AFTER we disconnected it, so the process can't settle. @@ -508,6 +540,11 @@ export function registerSyncHandlers(): void { } } + // The certificate this account approved for this server, or none (normal + // verification) — never one the config arrived with. Applied to the ONE + // config that the primary, the pool and every reconnect dial with. + config = await applyCertificatePin(config, 'imap', vaultIdCandidates(accountId, config.username, config.host)); + // Never connect a password-auth account with no password. It fails with // "No password configured" AND connection-manager latches the config, so // every subsequent auto-reconnect re-hammers the same password-less config @@ -518,9 +555,9 @@ export function registerSyncHandlers(): void { return { success: false, error: 'Credentials not ready — will retry', retryable: true }; } - // Certificate checks are decided in core (resolveTlsOptions): on unless a - // password account opted out, and a saved password's opt-out is the one - // saved with it (above). attachImapBearer wires a fresh-token resolver for + // Certificate checks are decided in core (resolveTlsOptions): always on, + // and a pinned password account accepts exactly its approved certificate + // (above). attachImapBearer wires a fresh-token resolver for // OAuth so the pool + reconnects never authenticate with a token that // expired after pool init (no-op for password auth). This single config // flows into both connect() and initializePool(), and is what @@ -670,13 +707,14 @@ export function registerSyncHandlers(): void { } }); // The server stopped encrypting a STARTTLS account mid-session (CASA - // M-5): reconnects have stopped. Tell the renderer what to change. The + // M-5), or now presents a certificate the account does not trust (CASA + // 4.1.2): reconnects have stopped. Tell the renderer what to change. The // saved config is KEPT — the credentials were never rejected. syncEngine.onSecurityError((error) => { if (!isActiveEngine()) return; const win = getMainWindow(); if (win && !win.isDestroyed()) { - win.webContents.send('imap:security-error', error.message); + win.webContents.send('imap:security-error', error.message, isCertificateUntrustedError(error) ? CERTIFICATE_UNTRUSTED : STARTTLS_UNAVAILABLE); } }); } @@ -717,12 +755,12 @@ export function registerSyncHandlers(): void { password: (config as any).password ?? '', authMethod: config.authMethod, oauthProvider: config.oauthProvider, - // Connection security and the self-signed opt-in are part of the - // account: dropping them here made a recovered 'none' account dial - // as STARTTLS-required, and a self-signed one fail verification. - // What was actually used, not what the request asked for. + // Connection security is part of the account: dropping it here made + // a recovered 'none' account dial as STARTTLS-required. What was + // actually used, not what the request asked for. An approved + // certificate is not kept here: it lives with the saved credentials + // and is applied by main on every connect. security: config.security, - allowInsecureTLS: transportOptInsOf(config).allowInsecureTLS, }).catch((e) => logger.error('[Main] saveImapAccount failed:', e)); } @@ -748,6 +786,13 @@ export function registerSyncHandlers(): void { logger.warn(`[Main] connect refused — STARTTLS is required for ${config.host} but the server did not encrypt the session`); return { success: false, error: (error as Error).message, retryable: false, code: STARTTLS_UNAVAILABLE }; } + // The server's certificate is not trusted (CASA 4.1.2): settled until the + // user approves one, never parked as a blip; the password was never sent. + // The wrapper around this handler offers the certificate for review. + if (isCertificateUntrustedError(error)) { + logger.warn(`[Main] connect refused — the incoming server's certificate is not trusted for ${accountLogLabel(accountId ?? getCurrentAccountId() ?? undefined)}`); + return { success: false, error: (error as Error).message, retryable: false, code: CERTIFICATE_UNTRUSTED }; + } logger.error('IMAP connect error:', error); const quotaKey = accountId ?? getCurrentAccountId(); // Quota ("too many simultaneous connections"): tear our engine down so a @@ -772,7 +817,7 @@ export function registerSyncHandlers(): void { retryable: parked.reason !== null, }; } - }); + } /** * Prove a candidate set of credentials can actually authenticate, WITHOUT @@ -788,7 +833,12 @@ export function registerSyncHandlers(): void { * "can THESE credentials connect?". OAuth is the one exception: the renderer * never holds tokens, so we resolve it from the main-process store here. */ - ipcMain.handle('imap:probeCredentials', async (_event, config: IMAPConfig) => { + // + // A password probe dials with the certificate approved for the account it is + // about to become (`accountId`, from the add-account flow), and an untrusted + // certificate is offered for review here — the probe is a new account's first + // connect, so this is where a self-signed server is first approved. + ipcMain.handle('imap:probeCredentials', (event, config: IMAPConfig, accountId?: string) => withCertificateApproval(async () => { let probeConfig = config; if (config.authMethod === 'oauth2') { if (!config.oauthProvider) { @@ -803,8 +853,9 @@ export function registerSyncHandlers(): void { return { success: false, error: (error as Error).message }; } } + probeConfig = await applyCertificatePin(probeConfig, 'imap', vaultIdCandidates(accountId, config.username, config.host)); return probeImapCredentials(probeConfig); - }); + }, () => imapCertificateRequest(event, config, accountId))); /** * Disconnect from IMAP server @@ -1283,7 +1334,12 @@ export function registerSyncHandlers(): void { // The active account is untouched (it has its own IDLE). New-email events from // this sync flow through the shared emitter but are filtered out by the active // idle-bridge's belongsToActive guard, so they never disturb the active view. - ipcMain.handle('accounts:backgroundSync', async (_event, opts: { accountId: string; config: IMAPConfig }) => { + // Background sync never asks about a certificate (CASA 4.1.2): a refusal + // comes back at once, tagged, and is reviewed from Settings → Accounts. An + // unanswered dialog can never hold a background cycle either. + ipcMain.handle('accounts:backgroundSync', (_event, opts: { accountId: string; config: IMAPConfig }) => backgroundSync(opts)); + + async function backgroundSync(opts: { accountId: string; config: IMAPConfig }) { if (getIsQuitting()) return { success: true, data: { skipped: true } }; const { accountId, config } = opts ?? ({} as { accountId: string; config: IMAPConfig }); // Unread for the "All Inboxes" badge / account switcher — INBOX distinct-thread @@ -1377,6 +1433,8 @@ export function registerSyncHandlers(): void { bgSaved = vaulted; } } + // The account's approved certificate for this server, or none. + cfg = await applyCertificatePin(cfg, 'imap', vaultIdCandidates(accountId, cfg.username, cfg.host)); // Don't connect password-less (fails "No password configured" and latches // that config for auto-reconnect to hammer). Skip this cycle; the next // background tick retries once the vault is readable. @@ -1448,6 +1506,12 @@ export function registerSyncHandlers(): void { // aborts/closes it so it releases back to the server instead of leaking. try { await getSyncEngineFor(accountId)?.disconnect?.(); } catch { /* best effort */ } + // An untrusted certificate (CASA 4.1.2): settled, never parked as a blip. + if (isCertificateUntrustedError(error)) { + logger.warn(`[Accounts] backgroundSync: the incoming server's certificate is not trusted for ${accountLogLabel(accountId)}`); + return { success: false, error: (error as Error).message, retryable: false, code: CERTIFICATE_UNTRUSTED }; + } + // "Too many simultaneous connections" (or a connect timeout, usually the // same saturated condition) — park this account via the shared back-off so // the next cycles (and the active-account path) don't keep hammering the @@ -1464,5 +1528,5 @@ export function registerSyncHandlers(): void { logger.warn('[Accounts] backgroundSync failed for', accountLogLabel(accountId), (error as Error).message); return { success: false, error: (error as Error).message }; } - }); + } } diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index 84be92ec..292b5012 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -53,6 +53,21 @@ interface SecureAccountSecrets { smtp?: { password?: string; accessToken?: string; refreshToken?: string; host?: string }; } +/** An approved mail-server certificate as the account settings show it (CASA 4.1.2). */ +interface ApprovedCertificate { + host: string; + port: number; + /** SHA-256 fingerprint, Node's colon-separated form. */ + sha256: string; + approvedAt: number; + subject: string; + issuer: string; + validTo: string; +} + +/** Why a connect was refused before any credential was sent. */ +type SecurityRefusalCode = 'STARTTLS_UNAVAILABLE' | 'CERTIFICATE_UNTRUSTED'; + interface AntivirusConfigureRequest { challenge: string; allowedAccountIds: string[]; @@ -263,7 +278,7 @@ contextBridge.exposeInMainWorld('electronAPI', { // IMAP operations imap: { connect: (config: IMAPConfig, accountId?: string) => ipcRenderer.invoke('imap:connect', config, accountId), - probeCredentials: (config: IMAPConfig) => ipcRenderer.invoke('imap:probeCredentials', config), + probeCredentials: (config: IMAPConfig, accountId?: string) => ipcRenderer.invoke('imap:probeCredentials', config, accountId), disconnect: () => ipcRenderer.invoke('imap:disconnect'), getSavedConfig: () => ipcRenderer.invoke('imap:getSavedConfig'), clearSavedConfig: () => ipcRenderer.invoke('imap:clearSavedConfig'), @@ -330,9 +345,10 @@ contextBridge.exposeInMainWorld('electronAPI', { removeAuthErrorListener: () => { ipcRenderer.removeAllListeners('imap:auth-error'); }, - /** A STARTTLS account's server stopped encrypting mid-session (CASA M-5). */ - onSecurityError: (callback: (message: string) => void) => { - ipcRenderer.on('imap:security-error', (_e, message: string) => callback(message)); + /** Reconnects stopped before sending anything: a STARTTLS account's server + * stopped encrypting (CASA M-5), or its certificate is not trusted (4.1.2). */ + onSecurityError: (callback: (message: string, code: SecurityRefusalCode) => void) => { + ipcRenderer.on('imap:security-error', (_e, message: string, code?: SecurityRefusalCode) => callback(message, code ?? 'STARTTLS_UNAVAILABLE')); }, removeSecurityErrorListener: () => { ipcRenderer.removeAllListeners('imap:security-error'); @@ -927,6 +943,15 @@ contextBridge.exposeInMainWorld('electronAPI', { requestAccess: () => ipcRenderer.invoke('secureCreds:requestAccess'), }, + // Approved mail-server certificates (CASA 4.1.2). Read and remove only: + // approving one happens in main's own dialog, during a connect the user + // started from a form (which the form announces with `review`). + certificates: { + list: (accountId: string) => ipcRenderer.invoke('certificates:list', accountId), + remove: (accountId: string, kind: 'imap' | 'smtp') => ipcRenderer.invoke('certificates:remove', accountId, kind), + review: (accountId: string, kind: 'imap' | 'smtp') => ipcRenderer.invoke('certificates:review', accountId, kind), + }, + // New-mail OS notifications. The renderer pushes the live config (mode, sound, // per-account notify flags, current view); the main process owns the firing. // onOpenEmail wires a notification CLICK back to open that mail. @@ -1419,11 +1444,15 @@ export interface ElectronAPI { /** `healedAuthMethod` is set when main repaired an account that was marked * oauth2 but whose server rejected the token; persist it to make it stick. */ /** `code` 'STARTTLS_UNAVAILABLE': a STARTTLS account's server would not - * encrypt; `error` says what the user can change. */ - connect: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; healedAuthMethod?: 'password'; code?: 'STARTTLS_UNAVAILABLE' }>; + * encrypt; 'CERTIFICATE_UNTRUSTED': its certificate is not approved (main + * asked only if the connect was armed with certificates.review). `error` + * says what the user can do. */ + connect: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; healedAuthMethod?: 'password'; code?: SecurityRefusalCode }>; /** Verify credentials against the server without touching the active - * connection or any stored account. Used to gate account overwrites. */ - probeCredentials: (config: IMAPConfig) => Promise<{ success: boolean; error?: string }>; + * connection or any stored account. Used to gate account overwrites. + * `accountId` is the account these settings are for (or will be), whose + * approved certificate the probe uses. */ + probeCredentials: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; disconnect: () => Promise<{ success: boolean; error?: string }>; getSavedConfig: () => Promise<{ success: boolean; data?: any; error?: string }>; clearSavedConfig: () => Promise<{ success: boolean; error?: string }>; @@ -1456,7 +1485,7 @@ export interface ElectronAPI { removeReconnectingListener: () => void; onAuthError: (callback: () => void) => void; removeAuthErrorListener: () => void; - onSecurityError: (callback: (message: string) => void) => void; + onSecurityError: (callback: (message: string, code: SecurityRefusalCode) => void) => void; removeSecurityErrorListener: () => void; }; folders: { @@ -1685,9 +1714,10 @@ export interface ElectronAPI { }; smtp: { /** `code` 'STARTTLS_UNAVAILABLE': the sending server would not encrypt a - * STARTTLS account; `error` says what the user can change. */ - connect: (config: SMTPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: 'STARTTLS_UNAVAILABLE' }>; - connectFor: (accountId: string, config: SMTPConfig) => Promise<{ success: boolean; error?: string }>; + * STARTTLS account; 'CERTIFICATE_UNTRUSTED': its certificate is not + * approved. `error` says what the user can do. */ + connect: (config: SMTPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; + connectFor: (accountId: string, config: SMTPConfig) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; disconnect: () => Promise<{ success: boolean; error?: string }>; isConnected: () => Promise<{ success: boolean; data?: boolean; error?: string }>; send: (options: SendEmailOptions) => Promise<{ success: boolean; queued?: boolean; messageId?: string; error?: string }>; @@ -1918,6 +1948,14 @@ export interface ElectronAPI { status: () => Promise<{ success: boolean; data?: SecureStorageStatus; error?: string }>; requestAccess: () => Promise<{ success: boolean; data?: SecureStorageAccessResult; error?: string }>; }; + certificates: { + list: (accountId: string) => Promise<{ success: boolean; data?: { imap?: ApprovedCertificate; smtp?: ApprovedCertificate }; error?: string }>; + remove: (accountId: string, kind: 'imap' | 'smtp') => Promise<{ success: boolean; data?: { removed: boolean }; error?: string }>; + /** The user just started a connect for this account's `kind` server from a + * form: that connect may ask (in main) about an untrusted certificate. + * Rate-limited; `armed` false when asked again too soon. */ + review: (accountId: string, kind: 'imap' | 'smtp') => Promise<{ success: boolean; data?: { armed: boolean }; error?: string }>; + }; notifications: { setConfig: (config: unknown) => Promise<{ success: boolean; error?: string }>; /** `supported: false` = the OS reports notifications unavailable for the app. */ diff --git a/apps/desktop/electron/services/__testing__/fake-core-db.ts b/apps/desktop/electron/services/__testing__/fake-core-db.ts index c9fc0b87..4eb0d5dd 100644 --- a/apps/desktop/electron/services/__testing__/fake-core-db.ts +++ b/apps/desktop/electron/services/__testing__/fake-core-db.ts @@ -214,6 +214,13 @@ export function setBlob(key: string, data: Buffer): void { state.blobs.set(key, Buffer.from(data)); } +/** The throwing write (core-db's `writeBlob`); fails like setBlob under `failBlobWrite`. */ +export function writeBlob(key: string, data: Buffer): void { + if (!key) throw new Error('A blob needs a key'); + if (state.failBlobWrite) throw new Error('fake core-db: writeBlob failed'); + state.blobs.set(key, Buffer.from(data)); +} + export function deleteBlob(key: string): void { state.blobs.delete(key); } diff --git a/apps/desktop/electron/services/assistant-mailbox-download.ts b/apps/desktop/electron/services/assistant-mailbox-download.ts index 7f468161..83d01296 100644 --- a/apps/desktop/electron/services/assistant-mailbox-download.ts +++ b/apps/desktop/electron/services/assistant-mailbox-download.ts @@ -8,6 +8,7 @@ import { getIsQuitting, getSystemSuspended } from '../shared'; import { requireAccountStorage, requireTargetAccountId, resolveNamedOrActiveAccountTarget } from './account-target'; import { readRegistryAccounts } from './accounts-registry'; +import { applyCertificatePin } from './certificate-trust'; import { attachImapBearer, getAccessTokenForMailHost } from './oauth-service'; import { narrowSavedTransport, resolveVaultPassword, vaultIdCandidates, vaultRefusalMessage, @@ -53,8 +54,12 @@ async function credentials(accountId: string, signal: AbortSignal): Promise<{ co config = applied.config; saved = vaulted; } - // Core owns certificate/encryption checks. OAuth's refresh closure retains - // the same host binding for subsequent reconnects and pool connections. + // Core owns certificate/encryption checks; the certificate this account + // approved for its server (or none) is main's, never the registry's. OAuth's + // refresh closure retains the same host binding for subsequent reconnects and + // pool connections. No approval question from here: an agent's download is not + // the user reconnecting, so an untrusted certificate just fails it. + config = await waitForAbortableOperation(applyCertificatePin(config, 'imap', vaultIdCandidates(accountId, config.username, config.host)), signal); return { config: attachImapBearer(config), saved }; } diff --git a/apps/desktop/electron/services/certificate-trust.ts b/apps/desktop/electron/services/certificate-trust.ts new file mode 100644 index 00000000..9b17e0a7 --- /dev/null +++ b/apps/desktop/electron/services/certificate-trust.ts @@ -0,0 +1,562 @@ +/** + * Which certificate a password account's mail server may present (CASA 4.1.2). + * + * Every mail connection verifies its certificate (resolveTlsOptions in core). + * A server with its own certificate — self-signed, or from a private CA — is + * reachable only once the user has approved that exact certificate, and then + * ONLY that certificate is accepted for that account, transport, host and port: + * a pin. This module owns the pins on the main-process side: + * + * - `applyCertificatePin` puts the account's pin (or none) on a connect config + * right before it is dialled, replacing whatever the config arrived with — + * the window cannot supply or change a pin. + * - The trust question is NEVER asked automatically. A focus/online + * reconnect, a background sync, the pool or the Inbox Agent meeting an + * untrusted certificate gets the refusal at once (the window shows a banner + * pointing to Settings → Accounts). Otherwise anyone on a café network could + * make "Trust this certificate?" pop up unprompted, and one click would hand + * them the password on the retry. + * - Only a connect the USER just started asks: the window arms it with + * `certificates:review` (`armCertificateReview`) right before the connect — + * the add-account test, Settings → Reconnect / Save / Verify, the + * re-enter-password dialog, the onboarding submit. An arm is bound to one + * account and transport, is used by the next connect of that pair, lapses + * after a minute, and is rate-limited so a compromised window cannot raise + * the dialog over and over. The dialog is main's own and native: the window + * cannot click it. + * - The dialog shows the certificate the server presents (fetched by main), the + * account (from main's registry) and why it asks (from main's vault — an + * account saved with the retired "allow self-signed" switch is told so). An + * expired or not-yet-valid certificate cannot be approved. "Trust" stores the + * pin with the account's saved credentials (a write that fails loudly) and + * dials once more — for the same account, or not at all. + * - OAuth connections never use pins and never ask. + * + * A vault that cannot be read gives no pin (the connection verifies against the + * system trust store, which refuses the self-signed server) and approves nothing. + * + * Logs name the account (accountLogLabel), the transport and the outcome — never + * a host, a fingerprint or anything from the certificate. + */ +import { + accountLogLabel, + CERTIFICATE_UNTRUSTED, + CertificateInspectionError, + certificateOutsideValidity, + createLogger, + failureCause, + inspectServerCertificate, + normalizeFingerprint, + type CertificateInspection, + type CertificatePin, + type ConnectionSecurity, + type PresentedCertificate, +} from '@sarvinbox/core'; +import { BrowserWindow, dialog, type MessageBoxOptions, type WebContents } from 'electron'; + +import { readRegistryAccounts } from './accounts-registry'; +import { + getAccountSecrets, + removeAccountCertificatePin, + setAccountCertificatePin, + type CertificateKind, + type CertificatePinRecord, +} from './secure-credential-store'; +import { normalizeHost } from './vault-credentials'; + +const logger = createLogger('certificate-trust'); + +/** The parts of an IMAP/SMTP config a pin is bound to and applied on. */ +export interface PinnableConfig { + host: string; + port: number; + authMethod?: string; + certificatePin?: CertificatePin; +} + +const hasUsablePin = (pin: CertificatePinRecord | undefined): pin is CertificatePinRecord => + !!pin && !!normalizeFingerprint(pin.sha256) && typeof pin.pem === 'string' && !!pin.pem; + +/** + * The certificate approved for this connection — account (any of `ids`), + * transport, host and port all matching — or null. Throws when the vault + * cannot be read, so a caller can never mistake "unreadable" for "none". + */ +export async function findCertificatePin( + ids: readonly string[], + kind: CertificateKind, + host: string, + port: number, +): Promise { + const wanted = normalizeHost(host); + if (!wanted) return null; + for (const id of new Set(ids)) { + if (!id) continue; + const pin = (await getAccountSecrets(id))?.certificates?.[kind]; + if (!hasUsablePin(pin) || normalizeHost(pin.host) !== wanted || pin.port !== port) continue; + return pin; + } + return null; +} + +/** Any certificate this account approved for `kind`, whatever its server. Throws when the vault cannot be read. */ +async function anyCertificatePin(ids: readonly string[], kind: CertificateKind): Promise { + for (const id of new Set(ids)) { + if (!id) continue; + const pin = (await getAccountSecrets(id))?.certificates?.[kind]; + if (pin) return pin; + } + return null; +} + +/** + * `config` with exactly the pin main has for it: the stored one for a password + * account's host and port, else none. A pin the config arrived with (from the + * window) is always dropped, and OAuth never gets one. A vault that cannot be + * read gives none — normal verification, which refuses any certificate the + * system does not trust — never "trusted". + */ +export async function applyCertificatePin(config: C, kind: CertificateKind, ids: readonly string[]): Promise { + const { certificatePin: _fromTheWindow, ...rest } = config; + if (config.authMethod === 'oauth2') return rest as C; + let pin: CertificatePinRecord | null = null; + try { + pin = await findCertificatePin(ids, kind, config.host, config.port); + } catch (error) { + logger.warn(`[Certificates] approved certificates unreadable for a ${kind} connection of ${accountLogLabel(ids[0])} (${failureCause(error)}); verifying against the system trust store only`); + } + return (pin ? { ...rest, certificatePin: { sha256: pin.sha256, pem: pin.pem } } : rest) as C; +} + +export interface CertificateTrustRequest { + kind: CertificateKind; + /** The account's vault ids; a new pin is stored under the first, and the review arm is matched on it. */ + ids: readonly string[]; + host: string; + port: number; + security: ConnectionSecurity; + /** The window that asked; the dialog is modal to it. May be null. */ + window?: BrowserWindow | null; +} + +export type CertificateTrustOutcome = + /** Something changed (a certificate was approved, or a pin removed): dial again. */ + | { outcome: 'retry' } + | { outcome: 'refused'; message: string; retryable: boolean }; + +const KIND_LABEL: Record = { imap: 'incoming mail (IMAP)', smtp: 'outgoing mail (SMTP)' }; + +/** The user chose Cancel: the account stays refused until they review it from the settings. */ +export function certificateDeclinedMessage(host: string, port: number): string { + return `Sarv Inbox did not connect to ${host}:${port} because the certificate it presents has not been approved. ` + + 'To review the certificate again, open Settings → Accounts and reconnect the account.'; +} + +function certificateDateMessage(host: string, port: number, problem: 'expired' | 'not-yet-valid'): string { + return problem === 'expired' + ? `The certificate ${host}:${port} presents has expired, so it cannot be trusted. Ask the server's administrator to renew it.` + : `The certificate ${host}:${port} presents is not valid yet, so it cannot be trusted. Check this computer's date and time, or ask the server's administrator.`; +} + +function certificateUnavailableMessage(host: string, port: number): string { + return `Sarv Inbox could not fetch the certificate ${host}:${port} presents, so it cannot be reviewed right now. Try reconnecting the account again.`; +} + +function certificateNotSavedMessage(host: string, port: number): string { + return `Sarv Inbox could not save the certificate you approved for ${host}:${port}, so it is not trusted yet. Try again.`; +} + +/** The retry after an approval would not reach the account that asked. */ +export const ACCOUNT_CHANGED_DURING_REVIEW = 'The account on screen changed while the certificate was being reviewed, so Sarv Inbox did not connect. Reconnect the account to try again.'; + +/** What main's own records say about the account asking: its address (registry) and whether it used the retired switch (vault). */ +interface AccountFacts { + label: string | null; + legacyInsecureTLS: boolean; +} + +async function accountFacts(ids: readonly string[], kind: CertificateKind): Promise { + let label: string | null = null; + try { + label = readRegistryAccounts().find((account) => ids.includes(account.id))?.email || null; + } catch { /* wording only: no account line */ } + let legacyInsecureTLS = false; + try { + for (const id of new Set(ids)) { + if (id && (await getAccountSecrets(id))?.[kind]?.allowInsecureTLS === true) { + legacyInsecureTLS = true; + break; + } + } + } catch { /* wording only */ } + return { label, legacyInsecureTLS }; +} + +const describeLines = (req: CertificateTrustRequest, leaf: PresentedCertificate, facts: AccountFacts): string[] => [ + ...(facts.label ? [`Account: ${facts.label}`] : []), + `Server: ${req.host}:${req.port} (${KIND_LABEL[req.kind]})`, + `Issued to: ${oneLine(leaf.subject)}`, + `Issued by: ${oneLine(leaf.issuer)}`, + `Valid from: ${leaf.validFrom}`, + `Valid until: ${leaf.validTo}`, + 'SHA-256 fingerprint:', + leaf.sha256, +]; + +/** A certificate's distinguished name (Node prints one field per line) on one line. */ +function oneLine(name: string): string { + return name.split('\n').map((part) => part.trim()).filter(Boolean).join(', '); +} + +const NO_FACTS: AccountFacts = { label: null, legacyInsecureTLS: false }; + +/** + * The approval dialog: Cancel is the default, and the only other choice trusts + * exactly this certificate. `replacing` is ANY certificate the account already + * trusts for this transport: trusting a new one replaces it, so the dialog says + * so — "CHANGED" when it is the same server, the old server otherwise. + */ +export function trustDialogOptions( + req: CertificateTrustRequest, + leaf: PresentedCertificate, + replacing: CertificatePinRecord | null, + facts: AccountFacts = NO_FACTS, +): MessageBoxOptions { + const sameServer = !!replacing && normalizeHost(replacing.host) === normalizeHost(req.host) && replacing.port === req.port; + const intro = replacing + ? (sameServer + ? `The certificate for ${req.host} has CHANGED since you approved it.` + : `This account already trusts a certificate for ${replacing.host}:${replacing.port}. Trusting this one REPLACES it.`) + + ' If you did not expect this, someone may be intercepting the connection — choose Cancel.' + : facts.legacyInsecureTLS + ? `This account was set to accept any certificate from its server. Sarv Inbox now accepts only a certificate you approve, so it asks you once.` + : `${req.host} presented a certificate that your system does not trust.`; + return { + type: 'warning', + title: 'Untrusted certificate', + message: replacing ? `Trust the new certificate for ${req.host}?` : `Trust the certificate for ${req.host}?`, + detail: [ + intro, + '', + ...describeLines(req, leaf, facts), + ...(replacing ? ['', `Currently trusted (${replacing.host}:${replacing.port}):`, replacing.sha256] : []), + '', + 'Trust it only if you know this server uses its own certificate and the fingerprint matches the one your administrator gave you. ' + + 'Sarv Inbox will then accept exactly this certificate for this server, and refuse every other one.', + ].join('\n'), + buttons: ['Trust this certificate', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }; +} + +/** For a certificate that cannot be approved: no trust button at all. */ +export function untrustableDialogOptions(req: CertificateTrustRequest, leaf: PresentedCertificate, problem: 'expired' | 'not-yet-valid', facts: AccountFacts = NO_FACTS): MessageBoxOptions { + return { + type: 'error', + title: 'Certificate cannot be trusted', + message: problem === 'expired' ? `The certificate for ${req.host} has expired.` : `The certificate for ${req.host} is not valid yet.`, + detail: [ + `${certificateDateMessage(req.host, req.port, problem)} Sarv Inbox did not connect and did not send your password.`, + '', + ...describeLines(req, leaf, facts), + ].join('\n'), + buttons: ['OK'], + defaultId: 0, + cancelId: 0, + noLink: true, + }; +} + +/** For a pin that now blocks a certificate the system trusts. */ +export function systemTrustedDialogOptions(req: CertificateTrustRequest, leaf: PresentedCertificate, facts: AccountFacts = NO_FACTS): MessageBoxOptions { + return { + type: 'warning', + title: 'Certificate changed', + message: `${req.host} now presents a certificate your system trusts.`, + detail: [ + 'It is not the certificate you approved for this account, so Sarv Inbox refused it. If the server has switched to a certificate from a public authority, ' + + 'stop using the approved certificate and Sarv Inbox will check this server like any other.', + '', + ...describeLines(req, leaf, facts), + ].join('\n'), + buttons: ['Stop using the approved certificate', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }; +} + +/** The window an IPC request came from — the approval dialog's parent — or null. */ +export function requestingWindow(event: unknown): BrowserWindow | null { + const sender = (event as { sender?: unknown } | null | undefined)?.sender; + if (!sender) return null; + try { + return BrowserWindow.fromWebContents(sender as WebContents) ?? null; + } catch { + return null; + } +} + +/** Test seam: the network inspection, the dialog and the clock. */ +export interface CertificateTrustDeps { + inspect: typeof inspectServerCertificate; + showMessageBox: (window: BrowserWindow | null, options: MessageBoxOptions) => Promise<{ response: number }>; + now: () => number; +} + +const defaultDeps: CertificateTrustDeps = { + inspect: (target) => inspectServerCertificate(target), + showMessageBox: (window, options) => (window && !window.isDestroyed() ? dialog.showMessageBox(window, options) : dialog.showMessageBox(options)), + now: () => Date.now(), +}; +let deps: CertificateTrustDeps = defaultDeps; + +/** Replace the inspection / dialog / clock for a test; returns a restore function. */ +export function setCertificateTrustDepsForTest(overrides: Partial): () => void { + deps = { ...defaultDeps, ...overrides }; + return () => { deps = defaultDeps; }; +} + +// ===== The review arm: only a connect the user just started may ask ========== + +/** How long an arm waits for its connect. */ +export const REVIEW_ARM_TTL_MS = 60_000; +/** One arm per account+transport per this long: the window cannot raise the dialog over and over. */ +export const REVIEW_ARM_INTERVAL_MS = 10_000; +/** And at most this many arms a minute across all accounts (fabricated ids included). */ +export const REVIEW_ARMS_PER_MINUTE = 10; + +const armKey = (accountId: string, kind: CertificateKind): string => `${accountId}\u0000${kind}`; +const armedUntil = new Map(); +const lastArmedAt = new Map(); +let recentArms: number[] = []; + +/** + * The user just asked to (re)connect this account's `kind` server from a form: + * its next connect may ask about an untrusted certificate. Refused ('too-soon') + * within REVIEW_ARM_INTERVAL_MS of the last arm for the same pair, or past the + * per-minute cap. + */ +export function armCertificateReview(accountId: string, kind: CertificateKind): 'armed' | 'too-soon' { + const now = deps.now(); + recentArms = recentArms.filter((at) => at > now - 60_000); + for (const [key, at] of lastArmedAt) if (at <= now - REVIEW_ARM_TTL_MS) lastArmedAt.delete(key); + for (const [key, until] of armedUntil) if (until < now) armedUntil.delete(key); + const key = armKey(accountId, kind); + const last = lastArmedAt.get(key); + if ((last !== undefined && now - last < REVIEW_ARM_INTERVAL_MS) || recentArms.length >= REVIEW_ARMS_PER_MINUTE) { + logger.info(`[Certificates] ${kind} review for ${accountLogLabel(accountId)}: not armed (too soon after the last one)`); + return 'too-soon'; + } + lastArmedAt.set(key, now); + recentArms.push(now); + armedUntil.set(key, now + REVIEW_ARM_TTL_MS); + return 'armed'; +} + +/** Use up the arm for this account+transport: true when the user armed it and it has not lapsed. */ +export function takeCertificateReview(accountId: string | undefined, kind: CertificateKind): boolean { + if (!accountId) return false; + const key = armKey(accountId, kind); + const until = armedUntil.get(key); + armedUntil.delete(key); + return until !== undefined && until >= deps.now(); +} + +// ===== The question ========================================================== + +const keyOf = (owner: string, kind: CertificateKind, host: string, port: number): string => [owner, kind, normalizeHost(host), port].join('\u0000'); + +/** Questions on screen or about to be, per account+transport+host+port: concurrent armed connects share one. */ +const inFlight = new Map>(); + +/** + * Ask the user whether to trust the certificate this server presents, after + * an ARMED connect was refused over it. Only `withCertificateApproval` calls + * this, and only for a connect that took a review arm. + */ +export function requestCertificateTrust(req: CertificateTrustRequest): Promise { + const owner = req.ids[0] ?? ''; + const key = keyOf(owner, req.kind, req.host, req.port); + const running = inFlight.get(key); + if (running) return running; + const decision = decide(req, owner).finally(() => inFlight.delete(key)); + inFlight.set(key, decision); + return decision; +} + +async function decide(req: CertificateTrustRequest, owner: string): Promise { + const label = `${req.kind} certificate for ${accountLogLabel(owner)}`; + let inspection: CertificateInspection; + try { + inspection = await deps.inspect({ host: req.host, port: req.port, security: req.security, protocol: req.kind }); + } catch (error) { + const reason = error instanceof CertificateInspectionError ? error.reason : failureCause(error); + logger.warn(`[Certificates] ${label}: could not be fetched for review (${reason})`); + return { outcome: 'refused', message: certificateUnavailableMessage(req.host, req.port), retryable: true }; + } + const { leaf } = inspection; + + let exact: CertificatePinRecord | null; + let anyForKind: CertificatePinRecord | null; + try { + exact = await findCertificatePin(req.ids, req.kind, req.host, req.port); + anyForKind = exact ?? await anyCertificatePin(req.ids, req.kind); + } catch (error) { + // Nothing can be approved into a store that cannot be read. + logger.warn(`[Certificates] ${label}: approved certificates unreadable (${failureCause(error)}); not asking`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + const facts = await accountFacts(req.ids, req.kind); + + const dateProblem = certificateOutsideValidity(leaf, deps.now()); + if (dateProblem) { + logger.warn(`[Certificates] ${label}: presented certificate is ${dateProblem}; cannot be approved`); + await deps.showMessageBox(req.window ?? null, untrustableDialogOptions(req, leaf, dateProblem, facts)); + return { outcome: 'refused', message: certificateDateMessage(req.host, req.port, dateProblem), retryable: false }; + } + + if (inspection.systemTrusted) { + if (!exact) { + // The certificate verifies now: the refusal was for a certificate this + // server no longer presents. Dial again; nothing to approve. + logger.info(`[Certificates] ${label}: now verified by the system trust store; retrying without a question`); + return { outcome: 'retry' }; + } + const { response } = await deps.showMessageBox(req.window ?? null, systemTrustedDialogOptions(req, leaf, facts)); + if (response !== 0) { + logger.info(`[Certificates] ${label}: kept the approved certificate; refused the system-trusted one`); + return { outcome: 'refused', message: certificateDeclinedMessage(req.host, req.port), retryable: false }; + } + try { + await removeAccountCertificatePin(req.ids, req.kind); + } catch (error) { + logger.warn(`[Certificates] ${label}: could not remove the approved certificate (${failureCause(error)})`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + logger.info(`[Certificates] ${label}: approved certificate removed; the system trust store decides`); + return { outcome: 'retry' }; + } + + // Any certificate already trusted for this transport is named as replaced, + // never silently overwritten (a re-approval of the very same one is not a change). + const replacing = anyForKind && (anyForKind.sha256 !== leaf.sha256 || !exact) ? anyForKind : null; + const { response } = await deps.showMessageBox(req.window ?? null, trustDialogOptions(req, leaf, replacing, facts)); + if (response !== 0) { + logger.info(`[Certificates] ${label}: declined${facts.legacyInsecureTLS ? ' (account had accepted any certificate before)' : ''}`); + return { outcome: 'refused', message: certificateDeclinedMessage(req.host, req.port), retryable: false }; + } + try { + await setAccountCertificatePin(owner, req.kind, { + host: normalizeHost(req.host), + port: req.port, + sha256: leaf.sha256, + pem: leaf.pem, + approvedAt: deps.now(), + subject: leaf.subject, + issuer: leaf.issuer, + validFrom: leaf.validFrom, + validTo: leaf.validTo, + }); + } catch (error) { + logger.warn(`[Certificates] ${label}: approved, but could not be saved (${failureCause(error)})`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + logger.info(`[Certificates] ${label}: approved${replacing ? ' (replaced the earlier one)' : ''}${facts.legacyInsecureTLS ? ' (account had accepted any certificate before)' : ''}`); + return { outcome: 'retry' }; +} + +/** What a connect handler answers: success, or a failure that may carry the certificate code. */ +export interface ConnectAnswer { + success: boolean; + error?: string; + code?: string; + retryable?: boolean; +} + +export interface ApprovalOptions { + /** + * What the retry must still be connecting for — e.g. the account on screen, + * whose engine or SMTP client the handler resolves when it runs. Read right + * after the first attempt and again before the retry; if it changed (the user + * switched accounts while the dialog was open), there is no retry. + */ + sameTarget?: () => unknown; +} + +/** + * Run a connect. The review arm for its account+transport is used up FIRST + * (whether or not anything goes wrong), so only the connect the user started + * can ask. When it was refused over the certificate: + * - not armed (every automatic path), or OAuth (`request` null): the refusal + * is returned at once — no inspection, no dialog; + * - armed: main asks, and on approval runs the connect once more, for the + * same target (`options.sameTarget`) or not at all. A second certificate + * refusal is returned as it is (the server changed its certificate between + * the question and the retry: no second question). + */ +export async function withCertificateApproval( + attempt: () => Promise, + request: () => CertificateTrustRequest | null, + options: ApprovalOptions = {}, +): Promise { + const req = request(); + const armed = req ? takeCertificateReview(req.ids[0], req.kind) : false; + const first = await attempt(); + if (first.success || first.code !== CERTIFICATE_UNTRUSTED || !req || !armed) return first; + const target = options.sameTarget?.(); + const decision = await requestCertificateTrust(req); + if (decision.outcome === 'refused') { + return { success: false, error: decision.message, retryable: decision.retryable, code: CERTIFICATE_UNTRUSTED }; + } + if (options.sameTarget && options.sameTarget() !== target) { + logger.warn(`[Certificates] ${req.kind} review for ${accountLogLabel(req.ids[0])}: the account changed during the question; not retrying`); + return { success: false, error: ACCOUNT_CHANGED_DURING_REVIEW, retryable: true, code: CERTIFICATE_UNTRUSTED }; + } + return attempt(); +} + +/** What the account settings show about an approved certificate (no PEM). */ +export interface CertificatePinSummary { + host: string; + port: number; + sha256: string; + approvedAt: number; + subject: string; + issuer: string; + validTo: string; +} + +/** The approved certificates of one account, per transport. Throws when the vault cannot be read. */ +export async function listAccountCertificates(accountId: string): Promise>> { + const certificates = (await getAccountSecrets(accountId))?.certificates ?? {}; + const out: Partial> = {}; + for (const kind of ['imap', 'smtp'] as const) { + const pin = certificates[kind]; + if (!pin) continue; + out[kind] = { host: pin.host, port: pin.port, sha256: pin.sha256, approvedAt: pin.approvedAt, subject: pin.subject, issuer: pin.issuer, validTo: pin.validTo }; + } + return out; +} + +/** + * Stop trusting the approved certificate for `kind` of this account. Automatic + * reconnects then meet the refusal (no question); reconnecting from the account + * settings asks again. Answers whether one was removed; throws when the vault + * cannot be read or written. + */ +export async function removeAccountCertificate(accountId: string, kind: CertificateKind): Promise { + const removed = await removeAccountCertificatePin([accountId], kind); + logger.info(`[Certificates] ${kind} certificate for ${accountLogLabel(accountId)}: ${removed ? 'removed by the user' : 'nothing to remove'}`); + return removed; +} + +/** Test seam: forget every question and arm. */ +export function resetCertificateTrustForTest(): void { + inFlight.clear(); + armedUntil.clear(); + lastArmedAt.clear(); + recentArms = []; +} diff --git a/apps/desktop/electron/services/core-db.ts b/apps/desktop/electron/services/core-db.ts index 53f04706..1ec019b1 100644 --- a/apps/desktop/electron/services/core-db.ts +++ b/apps/desktop/electron/services/core-db.ts @@ -225,15 +225,25 @@ export function getBlob(key: string): Buffer | null { } } +/** + * Store a blob. THROWS when the store cannot be written, which `setBlob` only + * logs. A writer that tells the user something was saved (an approved + * certificate) writes with this, so a failed write is reported, not believed. + */ +export function writeBlob(key: string, data: Buffer): void { + if (!key) throw new Error('A blob needs a key'); + getCoreDb() + .prepare( + `INSERT INTO core_blobs (key, data, updated_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at`, + ) + .run(key, data, Date.now()); +} + export function setBlob(key: string, data: Buffer): void { if (!key) return; try { - getCoreDb() - .prepare( - `INSERT INTO core_blobs (key, data, updated_at) VALUES (?, ?, ?) - ON CONFLICT(key) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at`, - ) - .run(key, data, Date.now()); + writeBlob(key, data); } catch (e) { logger.error('[CoreDB] setBlob failed:', key, e); } diff --git a/apps/desktop/electron/services/secure-credential-store.ts b/apps/desktop/electron/services/secure-credential-store.ts index f1117a7a..4b9d5d41 100644 --- a/apps/desktop/electron/services/secure-credential-store.ts +++ b/apps/desktop/electron/services/secure-credential-store.ts @@ -21,7 +21,7 @@ import { join } from 'path'; import { createLogger } from '@sarvinbox/core'; import { app } from 'electron'; -import { getBlob, setBlob } from './core-db'; +import { readBlob, setBlob, writeBlob } from './core-db'; import { isOsBackedEncryption } from './os-encryption'; import { sealJson, openJson, type EnvelopeErrors } from './safe-storage-envelope'; import { createWriteQueue } from './write-queue'; @@ -32,29 +32,60 @@ const BLOB_KEY = 'secure-credentials'; /** * One credential kind. `host` is the server the secret was saved FOR: main only - * ever sends the secret to that host (see vault-credentials.ts). The two - * transport relaxations are the ones the user chose WITH the secret: main only - * sends it over a connection that is at least that strict. Entries written - * before either binding lack those fields and are bound on first use. + * ever sends the secret to that host (see vault-credentials.ts). The transport + * relaxation is the one the user chose WITH the secret: main only sends it over + * a connection that is at least that strict. Entries written before either + * binding lack those fields and are bound on first use. */ export interface VaultCredential { password?: string; accessToken?: string; refreshToken?: string; host?: string; - /** Accept a certificate nobody vouches for (a self-signed server). */ + /** + * RETIRED "accept any certificate" switch, still present on entries saved + * before certificate pinning (CASA 4.1.2). Never written, never obeyed: read + * only so the approval dialog can tell the user why it is asking once. + */ allowInsecureTLS?: boolean; /** Connect without requiring encryption (security 'none'). */ allowPlaintext?: boolean; } /** The relaxations a vault entry may record. */ -export type VaultTransportField = 'allowInsecureTLS' | 'allowPlaintext'; -const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowInsecureTLS', 'allowPlaintext']; +export type VaultTransportField = 'allowPlaintext'; +const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowPlaintext']; + +/** + * A certificate the user approved, in main's own dialog, for one server of this + * account (CASA 4.1.2). Bound to the transport (the `certificates` key), host + * and port: it is used only for a connection to exactly that host and port, and + * then that connection accepts exactly this certificate. Written only by main's + * approval flow (certificate-trust.ts) — `setAccountSecrets`, which the window + * reaches, never copies it. + */ +export interface CertificatePinRecord { + host: string; + port: number; + /** SHA-256 of the leaf's DER, Node's fingerprint256 form. */ + sha256: string; + /** The approved leaf certificate, PEM. */ + pem: string; + /** When the user approved it (epoch ms). */ + approvedAt: number; + subject: string; + issuer: string; + validFrom: string; + validTo: string; +} + +export type CertificateKind = 'imap' | 'smtp'; export interface AccountSecrets { imap?: VaultCredential; smtp?: VaultCredential; + /** Approved certificates, per transport. */ + certificates?: Partial>; } type Vault = Record; @@ -100,7 +131,12 @@ async function migrateLegacyFile(): Promise { } async function readVault(): Promise { - const blob = getBlob(BLOB_KEY); + // The LOUD read (readBlob): a core DB that cannot be read throws here rather + // than reading as "no vault". Writes are read-modify-write of the whole + // vault, so an unreadable store taken for an empty one would be overwritten + // with just the new entry — every other account's password and approved + // certificate gone. Readers already treat a throw as "not readable yet". + const blob = readBlob(BLOB_KEY); if (blob) { // A present-but-undecryptable vault must NOT read as empty (that would let a // later write clobber every other account's secret) — deserialize throws. @@ -111,7 +147,7 @@ async function readVault(): Promise { // Re-check: a concurrent call may have migrated + renamed the file between our // getBlob and here — don't conclude "empty vault" (which a later write would // then persist, clobbering the real secrets). - const blob2 = getBlob(BLOB_KEY); + const blob2 = readBlob(BLOB_KEY); return blob2 ? (deserialize(blob2) || {}) : {}; } @@ -119,11 +155,16 @@ async function readVault(): Promise { // (read-modify-write on the whole vault). const writeQueue = createWriteQueue(); -async function writeVault(mutate: (vault: Vault) => void): Promise { +/** + * Read-modify-write the whole vault, serialised. `strict` writes with the + * throwing `writeBlob`, for a change the user is told was saved (an approved or + * removed certificate): `setBlob` only logs a failed write. + */ +async function writeVault(mutate: (vault: Vault) => void, { strict = false }: { strict?: boolean } = {}): Promise { return writeQueue.enqueue(async () => { const vault = await readVault(); mutate(vault); - setBlob(BLOB_KEY, serialize(vault)); + (strict ? writeBlob : setBlob)(BLOB_KEY, serialize(vault)); }); } @@ -145,9 +186,11 @@ export async function setAccountSecrets(accountId: string, secrets: AccountSecre // The host travels WITH a secret, never alone: a call carrying only a host // must not be able to re-point an existing password at another server. if (typeof o.host === 'string' && o.host.trim()) out.host = o.host.trim(); - // So do the transport relaxations, and always as booleans: a call carrying - // only "allow self-signed" must not loosen how an existing password is - // sent, and a new secret is bound to exactly what was chosen with it. + // So does the transport relaxation, and always as a boolean: a call + // carrying only "None" must not loosen how an existing password is sent, + // and a new secret is bound to exactly what was chosen with it. The retired + // "allow self-signed" switch is never copied, and neither is a certificate + // pin: only main's own approval dialog writes one (setAccountCertificatePin). for (const k of TRANSPORT_FIELDS) out[k] = o[k] === true; return out; }; @@ -156,7 +199,8 @@ export async function setAccountSecrets(accountId: string, secrets: AccountSecre if (!imap && !smtp) return; await writeVault((v) => { const existing = v[accountId] ?? {}; - // Only overwrite the kind(s) actually supplied; keep the other kind intact. + // Only overwrite the kind(s) actually supplied; keep the other kind intact, + // and the approved certificates (each is bound to its own host and port). v[accountId] = { ...existing, ...(imap ? { imap } : {}), @@ -247,9 +291,50 @@ export async function deleteAccountSecrets(accountId: string): Promise { } /** True if we have any secret on file for this account (renderer can skip a - * re-login prompt when secrets already live in the vault). */ + * re-login prompt when secrets already live in the vault). An approved + * certificate alone is not a secret to sign in with. */ export async function hasAccountSecrets(accountId: string): Promise { - return (await getAccountSecrets(accountId)) !== null; + const secrets = await getAccountSecrets(accountId); + return !!(secrets?.imap || secrets?.smtp); +} + +/** + * Store the certificate the user approved for `kind` of this account, + * replacing any earlier one for that transport. MAIN ONLY — called by the + * approval flow after the user chose "Trust this certificate" in main's own + * dialog. Throws when the vault cannot be read OR written (a strict write: + * nothing is then trusted, and the user is told it was not saved). + */ +export async function setAccountCertificatePin(accountId: string, kind: CertificateKind, pin: CertificatePinRecord): Promise { + if (!accountId) throw new Error('No account to store the approved certificate for'); + await writeVault((v) => { + const account = v[accountId] ?? {}; + account.certificates = { ...account.certificates, [kind]: { ...pin } }; + // The retired "accept any certificate" switch has done its last job (it + // worded the dialog); drop it so nothing reads it again. + if (account[kind]) delete account[kind]!.allowInsecureTLS; + v[accountId] = account; + }, { strict: true }); +} + +/** + * Forget the approved certificate for `kind` under each of `accountIds`. + * Answers whether one was removed. Throws when the vault cannot be read. + */ +export async function removeAccountCertificatePin(accountIds: readonly string[], kind: CertificateKind): Promise { + let removed = false; + await writeVault((v) => { + for (const id of accountIds) { + const certificates = v[id]?.certificates; + if (!certificates?.[kind]) continue; + delete certificates[kind]; + if (!Object.keys(certificates).length) delete v[id]!.certificates; + // An entry that held only certificates leaves no empty shell behind. + if (!Object.keys(v[id]!).length) delete v[id]; + removed = true; + } + }, { strict: true }); + return removed; } /** True if the legacy secure-credentials.json (or its rename) still exists — diff --git a/apps/desktop/electron/services/vault-credentials.ts b/apps/desktop/electron/services/vault-credentials.ts index 277d7492..252cd0f1 100644 --- a/apps/desktop/electron/services/vault-credentials.ts +++ b/apps/desktop/electron/services/vault-credentials.ts @@ -9,16 +9,22 @@ * the user's real password. Each vault entry therefore carries the host it was * saved for, and a password is only ever injected for that exact host. * - * The same goes for HOW it is sent. A self-signed server needs certificate - * checks off ("allow self-signed"), and a server without encryption needs - * connection security 'none'. Either one hands the password to anyone on the - * network path, and both used to come in with the config. So each entry also - * records the relaxations the user chose when typing that password, and main - * sends it over a connection at least that strict: a config may tighten them, - * never loosen them (a looser one is refused with "re-enter your password"). - * When a stricter connection works, the relaxations it did without are - * switched off for good. OAuth needs none of this: core always verifies an - * OAuth connection and never sends a token unencrypted. + * The same goes for HOW it is sent. A server without encryption needs + * connection security 'none', which hands the password to anyone on the + * network path, and that used to come in with the config. So each entry also + * records the relaxation the user chose when typing that password, and main + * sends it over a connection at least that strict: a config may tighten it, + * never loosen it (a looser one is refused with "re-enter your password"). + * When a stricter connection works, the relaxation it did without is switched + * off for good. OAuth needs none of this: core always verifies an OAuth + * connection and never sends a token unencrypted. + * + * Certificates are not a relaxation any more (CASA 4.1.2): every connection + * verifies, and a server with its own certificate is trusted only for the + * certificate the user approved in main, stored with these credentials and + * applied by certificate-trust.ts. `withSavedPassword` drops any certificate a + * config arrives with, so a saved password never goes out under a pin the + * window chose. * * Entries saved before either binding existed lack those fields. They are bound * on first use, from what main's account registry recorded for that account @@ -60,10 +66,16 @@ export type VaultCredentialKind = 'imap' | 'smtp'; export interface VaultPasswordFound { status: 'found'; password: string; - /** The relaxations saved with it — the most a connection using it may have. */ + /** The relaxation saved with it — the most a connection using it may have. */ transport: TransportOptIns; /** The vault id it was found under. */ id: string; + /** + * The entry still carries the retired "accept any certificate" switch: the + * account was set up for a self-signed server before pinning. Only words the + * approval dialog ("asked once"); it relaxes nothing. + */ + legacyInsecureTLS?: boolean; } export type VaultPasswordResult = @@ -79,7 +91,7 @@ export type VaultPasswordResult = | { status: 'none' }; /** Lower-cased, trimmed, one trailing root dot removed. */ -function normalizeHost(host: string | undefined | null): string { +export function normalizeHost(host: string | undefined | null): string { const h = (host ?? '').trim().toLowerCase(); return h.endsWith('.') ? h.slice(0, -1) : h; } @@ -228,7 +240,7 @@ function legacyHostDecision(id: string, kind: VaultCredentialKind, wanted: strin return sameSite ? { outcome: 'bind', because: `same site as ${sameSite} in the account registry` } : { outcome: 'unknown-server' }; } -const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowInsecureTLS', 'allowPlaintext']; +const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowPlaintext']; /** * The relaxations an entry saved before transport binding should be bound to: what @@ -250,16 +262,15 @@ function legacyTransportFor(id: string, kind: VaultCredentialKind, host: string) /** The relaxations saved with `entry`, binding a legacy entry on first use. */ async function savedTransport(id: string, kind: VaultCredentialKind, entry: VaultCredential, host: string): Promise { if (TRANSPORT_FIELDS.every((k) => typeof entry[k] === 'boolean')) { - return { allowInsecureTLS: entry.allowInsecureTLS === true, allowPlaintext: entry.allowPlaintext === true }; + return { allowPlaintext: entry.allowPlaintext === true }; } const legacy = legacyTransportFor(id, kind, host); if (!legacy) return undefined; const bound: TransportOptIns = { - allowInsecureTLS: typeof entry.allowInsecureTLS === 'boolean' ? entry.allowInsecureTLS : legacy.allowInsecureTLS, allowPlaintext: typeof entry.allowPlaintext === 'boolean' ? entry.allowPlaintext : legacy.allowPlaintext, }; await bindAccountSecretTransport(id, kind, bound); - logger.info(`[Vault] bound how the saved ${kind} password for ${accountLogLabel(id)} is sent: self-signed ${bound.allowInsecureTLS ? 'allowed' : 'refused'}, unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); + logger.info(`[Vault] bound how the saved ${kind} password for ${accountLogLabel(id)} is sent: unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); return bound; } @@ -307,7 +318,7 @@ export async function resolveVaultPassword( } const transport = await savedTransport(id, kind, entry, wanted); if (!transport) continue; - return { status: 'found', password: entry.password, transport, id }; + return { status: 'found', password: entry.password, transport, id, ...(entry.allowInsecureTLS === true ? { legacyInsecureTLS: true } : {}) }; } if (mismatch) { logger.warn(`[Vault] refused the saved ${kind} password for host "${wanted}" — it was saved for "${mismatch}"`); @@ -336,27 +347,28 @@ export function vaultRefusalMessage(kind: VaultCredentialKind, host: string, res } /** User-facing reason a connect could not use the saved password the way it asked to. */ -export function transportMismatchMessage(kind: VaultCredentialKind, host: string, beyond: 'insecure-tls' | 'plaintext'): string { +export function transportMismatchMessage(kind: VaultCredentialKind, host: string, _beyond: 'plaintext'): string { const what = kind === 'imap' ? 'mailbox' : 'sending'; - return beyond === 'insecure-tls' - ? `Your saved ${what} password was saved for a connection that checks ${host}'s certificate. Re-enter your password to connect without checking it.` - : `Your saved ${what} password was saved for an encrypted connection to ${host}. Re-enter your password to connect without encryption.`; + return `Your saved ${what} password was saved for an encrypted connection to ${host}. Re-enter your password to connect without encryption.`; } /** * `config` with the saved password in it, sent no more loosely than it was * saved for — or, when the config asks for a relaxation the password was not * saved with, the message telling the user to re-enter it. Never dial on a - * refusal: retrying can't change it. + * refusal: retrying can't change it. Any certificate pin the config carries is + * dropped: only main's own store supplies one (applyCertificatePin), so a + * caller that forgets to apply it gets normal verification, never the window's. */ -export function withSavedPassword( +export function withSavedPassword( config: C, kind: VaultCredentialKind, saved: VaultPasswordFound, ): { config: C } | { refusal: string } { const beyond = transportOptInBeyond(transportOptInsOf(config), saved.transport); if (beyond) return { refusal: transportMismatchMessage(kind, config.host, beyond) }; - return { config: limitTransport({ ...config, password: saved.password }, saved.transport) }; + const { certificatePin: _fromTheWindow, ...rest } = config; + return { config: limitTransport({ ...rest, password: saved.password } as C, saved.transport) }; } /** diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 1a8d6b23..c56294bd 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -72,6 +72,7 @@ import { setImageTrustAccount } from './utils/remote-images'; // provider here, and a provider's error can carry its response body, which can // quote that mail. Lines name the request and the failure's class, never text. const aiBridgeLog = createLogger('AIBridge'); +const connectionLog = createLogger('Connection'); function App() { const attachmentActions = useAttachmentActions(); @@ -590,14 +591,17 @@ function App() { useEmailStore.setState({ needsReauth: true }); }); } - // The server stopped encrypting a STARTTLS account mid-session (CASA M-5): + // The server stopped encrypting a STARTTLS account mid-session (CASA M-5), + // or now presents a certificate the account does not trust (CASA 4.1.2): // reconnects stopped. Show what to change — NOT the re-auth prompt, the // password was never sent or rejected. if (window.electronAPI?.imap?.onSecurityError) { - window.electronAPI.imap.onSecurityError((message) => { - console.warn('[App] IMAP server would not encrypt a STARTTLS account'); + window.electronAPI.imap.onSecurityError((message, code) => { + connectionLog.warn(code === 'CERTIFICATE_UNTRUSTED' + ? 'IMAP server presented a certificate the account does not trust' + : 'IMAP server would not encrypt a STARTTLS account'); useEmailStore.getState().handleDisconnection?.(); - useEmailStore.setState({ connectionSecurityIssue: message }); + useEmailStore.setState({ connectionSecurityIssue: message, connectionSecurityCode: code ?? 'STARTTLS_UNAVAILABLE' }); }); } diff --git a/apps/desktop/src/components/ConnectionDialog.tsx b/apps/desktop/src/components/ConnectionDialog.tsx index 885d789e..2bd05c61 100644 --- a/apps/desktop/src/components/ConnectionDialog.tsx +++ b/apps/desktop/src/components/ConnectionDialog.tsx @@ -3,6 +3,8 @@ import { Loader2, Mail, X } from 'lucide-react'; import { useState } from 'react'; import { useEmailStore } from '../store/email-store'; +import { connectAccountId } from '../store/helpers'; +import { allowCertificateReview } from '../utils/certificate-review'; import { VaultPasswordField } from './VaultPasswordField'; @@ -31,11 +33,13 @@ export function ConnectionDialog({ onClose }: { onClose?: () => void } = {}) { // Remove all spaces from password (Google App Passwords have spaces for readability) const cleanPassword = password.replace(/\s+/g, ''); - // Keep the account's own connection security and self-signed choice: a - // re-entered password is not a reason to change them. This used to send - // `secure: true`, which turned a STARTTLS or None account into implicit - // TLS on its old port (and saved that), so it could not reconnect. + // Keep the account's own connection security: a re-entered password is + // not a reason to change it. This used to send `secure: true`, which + // turned a STARTTLS or None account into implicit TLS on its old port + // (and saved that), so it could not reconnect. The user asked to + // reconnect: this connect may ask (in main) about an untrusted certificate. const security = resolveConnectionSecurity(imapConfig ?? {}); + allowCertificateReview(connectAccountId(accounts, username, host), 'imap'); await connect({ host, port: parseInt(port), @@ -43,7 +47,6 @@ export function ConnectionDialog({ onClose }: { onClose?: () => void } = {}) { password: cleanPassword, security, secure: security === 'ssl', - allowInsecureTLS: (imapConfig as { allowInsecureTLS?: boolean } | null)?.allowInsecureTLS, }); onClose?.(); // reconnected — close the on-demand dialog } catch (err) { diff --git a/apps/desktop/src/components/ConnectionSecurityBanner.tsx b/apps/desktop/src/components/ConnectionSecurityBanner.tsx index 65c3b0c2..c7f0abcd 100644 --- a/apps/desktop/src/components/ConnectionSecurityBanner.tsx +++ b/apps/desktop/src/components/ConnectionSecurityBanner.tsx @@ -7,19 +7,33 @@ import { BannerBar } from './BannerBar'; /** * Non-blocking banner shown when the ACTIVE account's mail server would not - * encrypt a STARTTLS session (CASA M-5) — the incoming (IMAP) server, the - * sending (SMTP) server, or both. Sarv Inbox stopped before sending the - * password, so this is not a sign-in problem: the remedy is the account's - * Connection security — or a different network, if someone on this one is - * stripping encryption. The local mailbox stays readable meanwhile, and - * outgoing mail waits in the Outbox. + * encrypt a STARTTLS session (CASA M-5), or presents a certificate the account + * has not approved (CASA 4.1.2) — the incoming (IMAP) server, the sending + * (SMTP) server, or both. Sarv Inbox stopped before sending the password, so + * this is not a sign-in problem: the remedy is the account's Connection + * security, or reviewing the certificate by reconnecting from the account + * settings — or a different network, if someone on this one is interfering. + * The local mailbox stays readable meanwhile, and outgoing mail waits in the + * Outbox. * - * "Account settings" deep-links to Settings → Accounts, where the security can - * be changed. + * "Account settings" deep-links to Settings → Accounts. */ +const HEADLINES = { + STARTTLS_UNAVAILABLE: { + incoming: 'Not connected: the mail server would not use encryption.', + outgoing: "Can't send: the outgoing mail server would not use encryption.", + }, + CERTIFICATE_UNTRUSTED: { + incoming: "Not connected: the mail server's certificate is not trusted.", + outgoing: "Can't send: the outgoing mail server's certificate is not trusted.", + }, +} as const; + export function ConnectionSecurityBanner({ onFix }: { onFix: () => void }) { const issue = useEmailStore((s) => s.connectionSecurityIssue); const smtpIssue = useEmailStore((s) => s.smtpSecurityIssue); + const incomingCode = useEmailStore((s) => s.connectionSecurityCode) ?? 'STARTTLS_UNAVAILABLE'; + const outgoingCode = useEmailStore((s) => s.smtpSecurityCode) ?? 'STARTTLS_UNAVAILABLE'; const connected = useEmailStore((s) => s.connected); const [dismissed, setDismissed] = useState(false); @@ -51,13 +65,13 @@ export function ConnectionSecurityBanner({ onFix }: { onFix: () => void }) { > {incoming ? ( <> - Not connected: the mail server would not use encryption.{' '} + {HEADLINES[incomingCode].incoming}{' '} {incoming} Your existing mail is still available. - {smtpIssue && Sending is refused the same way.} + {smtpIssue && {outgoingCode === incomingCode ? 'Sending is refused the same way.' : smtpIssue}} ) : ( <> - Can't send: the outgoing mail server would not use encryption.{' '} + {HEADLINES[outgoingCode].outgoing}{' '} {smtpIssue} Your messages wait in the Outbox until it can. )} diff --git a/apps/desktop/src/components/SmtpConfigForm.tsx b/apps/desktop/src/components/SmtpConfigForm.tsx index 78c6c108..cd529081 100644 --- a/apps/desktop/src/components/SmtpConfigForm.tsx +++ b/apps/desktop/src/components/SmtpConfigForm.tsx @@ -6,6 +6,7 @@ import { useState } from 'react'; import { defaultPort } from '../config/email-providers'; import { useEmailStore } from '../store/email-store'; import { deriveSmtpFromImap, accountIdFor } from '../store/helpers'; +import { allowCertificateReview } from '../utils/certificate-review'; import { ConnectionSecuritySelect } from './ConnectionSecuritySelect'; import { VaultPasswordField } from './VaultPasswordField'; @@ -50,7 +51,6 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con // `secure` only, so None came back as STARTTLS and was never kept). const [security, setSecurity] = useState(initial ? resolveConnectionSecurity(initial) : 'ssl'); const [port, setPort] = useState(String(initial?.port ?? 465)); - const [allowInsecure, setAllowInsecure] = useState(!!initial?.allowInsecureTLS); const [username, setUsername] = useState(initial?.username ?? accountEmail); // The SMTP password lives in the vault; the field starts empty and is revealed // only on an explicit OS-authenticated request (VaultPasswordField handles the @@ -77,9 +77,10 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con from: accountEmail || username.trim(), authMethod: imapConfig?.authMethod, oauthProvider: imapConfig?.oauthProvider, - // OAuth always verifies (core resolveTlsOptions), so it never asks. - allowInsecureTLS: (!isOAuth && allowInsecure) || undefined, }; + // The user asked to verify: this connect (only) may ask about an + // untrusted certificate, in main's dialog. Not for OAuth: never asks. + if (!isOAuth) allowCertificateReview(vaultAccountId, 'smtp'); await connectSmtp(config); // verifies via nodemailer transporter.verify() markSmtpConfigured(true); onVerified(); @@ -128,17 +129,12 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con className={inputCls} /> - {/* Not offered for OAuth: the provider's certificate is always checked. */} + {/* There is no "allow self-signed" switch any more (CASA 4.1.2): a server + with its own certificate is shown to the user, by main, to approve. */} {!isOAuth && ( - +

+ If this server uses its own (self-signed) certificate, Sarv Inbox shows it to you to approve when it connects. +

)} {error && ( diff --git a/apps/desktop/src/components/TrustedCertificate.tsx b/apps/desktop/src/components/TrustedCertificate.tsx new file mode 100644 index 00000000..8d4aba0c --- /dev/null +++ b/apps/desktop/src/components/TrustedCertificate.tsx @@ -0,0 +1,122 @@ +import { ShieldCheck } from 'lucide-react'; +import { useEffect, useState } from 'react'; + +import { formatFingerprint } from '../utils/certificate-review'; + +type Kind = 'imap' | 'smtp'; + +interface ApprovedCertificate { + host: string; + port: number; + sha256: string; + approvedAt: number; + validTo: string; +} + +interface TrustedCertificateProps { + /** The account whose approved certificate to show. */ + accountId: string | null | undefined; + kind: Kind; + /** The server the account uses now; a certificate approved for another host or port is not shown. */ + host?: string; + port?: number; +} + +/** Lower-cased, trimmed, one trailing root dot removed — main's own host rule. */ +const normalizeHost = (host: string): string => { + const h = host.trim().toLowerCase(); + return h.endsWith('.') ? h.slice(0, -1) : h; +}; +const sameHost = (a: string, b: string): boolean => normalizeHost(a) === normalizeHost(b); + +/** + * The certificate the user approved for this account's server (CASA 4.1.2): + * its SHA-256 fingerprint and when it was approved, with Remove. Shows nothing + * when there is none — the server is then checked against the system's trusted + * authorities like any other. Approving happens only in main's own dialog, + * during a connect; removing one here stops trusting it at once (main closes + * the connections that used it), and the next reconnect from the account + * settings asks again. + */ +export function TrustedCertificate({ accountId, kind, host, port }: TrustedCertificateProps) { + const [certificate, setCertificate] = useState(null); + const [removing, setRemoving] = useState(false); + const [removed, setRemoved] = useState(false); + const [error, setError] = useState(''); + + useEffect(() => { + let cancelled = false; + setCertificate(null); + setRemoved(false); + setError(''); + if (!accountId) return; + void (async () => { + try { + const res = await window.electronAPI?.certificates?.list(accountId); + if (cancelled || !res?.success) return; + const found = res.data?.[kind]; + const matches = found && (!host || sameHost(found.host, host)) && (port === undefined || found.port === port); + setCertificate(matches ? found : null); + } catch { + // Nothing to show: the server is then checked like any other. + } + })(); + return () => { cancelled = true; }; + }, [accountId, kind, host, port]); + + const remove = async () => { + if (!accountId) return; + setRemoving(true); + setError(''); + try { + const res = await window.electronAPI.certificates.remove(accountId, kind); + if (!res?.success) throw new Error(res?.error || 'The approved certificate could not be removed.'); + setCertificate(null); + setRemoved(true); + } catch (err) { + setError((err as Error).message); + } finally { + setRemoving(false); + } + }; + + if (removed) { + return ( +

+ Certificate removed. Sarv Inbox will ask about this server's certificate when you reconnect the account. +

+ ); + } + if (!certificate) return null; + + const approved = new Date(certificate.approvedAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); + return ( +
+
+ ); +} diff --git a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx index 7bd1302f..bc339c56 100644 --- a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx +++ b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx @@ -7,7 +7,8 @@ import { EMAIL_PROVIDERS, defaultPort, type ConnectionSecurity } from '../../con import { getOnboardingEmailProgress, isOnboardingPending } from '../../services/onboarding-progress'; import { requestConfirm } from '../../store/confirm-service'; import { useEmailStore } from '../../store/email-store'; -import { findAccountByEmailHost } from '../../store/helpers'; +import { connectAccountId, findAccountByEmailHost } from '../../store/helpers'; +import { allowCertificateReview } from '../../utils/certificate-review'; import { GmailPrivacyNotice } from '../GmailPrivacyNotice'; import { Tooltip } from '../Tooltip'; @@ -49,9 +50,12 @@ interface FormValues { smtpHost: string; smtpPort: string; smtpSecurity: ConnectionSecurity; - allowInsecure: boolean; skipSending: boolean; } +/** The id these settings are (or will be) saved under — addAccount's own rule. */ +const accountIdOf = (config: { username: string; host: string }): string => + connectAccountId(useEmailStore.getState().accounts, config.username, config.host); + interface ConnectedEmail { result: EmailSetupResult; smtp: SMTPConfig; @@ -92,7 +96,6 @@ function savedForm(connection: ConnectedEmail): FormValues { smtpHost: connection.smtp.host, smtpPort: String(connection.smtp.port), // The saved choice, None included (resolveConnectionSecurity). smtpSecurity: resolveConnectionSecurity(connection.smtp), - allowInsecure: Boolean(imap?.allowInsecureTLS), }; } @@ -108,7 +111,7 @@ function initialForm(providerId: string): FormValues { imapPort: String(preset?.imapPort ?? 993), imapSecurity: preset?.imapSecurity ?? 'ssl', smtpHost: preset?.smtpHost ?? '', smtpPort: String(preset?.smtpPort ?? 465), smtpSecurity: preset?.smtpSecurity ?? 'ssl', - allowInsecure: false, skipSending: false, + skipSending: false, }; } @@ -242,6 +245,9 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp } setLoading('sending'); try { + // Reached only from the user's Connect / Retry: the sending check may ask + // (in main) about an untrusted certificate. OAuth never asks. + if (connection.smtp.authMethod !== 'oauth2') allowCertificateReview(connection.result.accountId, 'smtp'); await useEmailStore.getState().connectSmtp(connection.smtp); if (!isCurrent(id)) return; if (useEmailStore.getState().activeAccountId !== connection.result.accountId) throw new Error('The active email account changed. Retry the sending check.'); @@ -264,7 +270,9 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp if (purpose === 'add-account') { // Probe in isolation before replacing a working account. OAuth identity // alone does not prove that the receiving server accepts its token. - const probe = await window.electronAPI.imap.probeCredentials(config as IMAPConfig); + // For the account these settings will be saved as: the certificate + // approved for it (main asks during the probe) is the one it dials with. + const probe = await window.electronAPI.imap.probeCredentials(config as IMAPConfig, accountIdOf(config)); if (!isCurrent(id)) return; if (!probe.success) throw new Error(probe.error || 'Receiving authentication failed. Check your connection details and retry.'); const existing = findAccountByEmailHost(useEmailStore.getState().accounts, config.username, config.host); @@ -356,14 +364,18 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp host: form.smtpHost.trim(), port: form.skipSending ? Number(form.smtpPort) || defaultPort('smtp', form.smtpSecurity) : validPort(form.smtpPort), security: form.smtpSecurity, secure: form.smtpSecurity === 'ssl', username: email, from: email, // Password whitespace can be meaningful. Never silently rewrite it. - password: form.password, authMethod: 'password', allowInsecureTLS: form.allowInsecure || undefined, + password: form.password, authMethod: 'password', }; if (!form.skipSending && !smtp.host) throw new Error('Enter the sending server or choose to set up sending later.'); - await connectMailbox({ + const imap: MailConfig = { host: form.imapHost.trim(), port: validPort(form.imapPort), security: form.imapSecurity, secure: form.imapSecurity === 'ssl', username: form.username.trim() || email, password: form.password, - authMethod: 'password', allowInsecureTLS: form.allowInsecure || undefined, - }, smtp, id, form.skipSending); + authMethod: 'password', + }; + // The user asked to connect: this test (only) may ask, in main's dialog, + // about an untrusted certificate; this form never approves one. + allowCertificateReview(accountIdOf(imap), 'imap'); + await connectMailbox(imap, smtp, id, form.skipSending); } catch (failure) { if (isCurrent(id)) setError(errorMessage(failure)); } finally { @@ -463,7 +475,7 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp

Sending uses the same email and password. Separate sending credentials can be added in Settings.

- +

If a server uses its own (self-signed) certificate, Sarv Inbox shows it to you to approve when it connects.

diff --git a/apps/desktop/src/components/onboarding/IMAPStep.tsx b/apps/desktop/src/components/onboarding/IMAPStep.tsx index 457700b5..aace434a 100644 --- a/apps/desktop/src/components/onboarding/IMAPStep.tsx +++ b/apps/desktop/src/components/onboarding/IMAPStep.tsx @@ -3,6 +3,8 @@ import { useEffect, useState } from 'react'; import { EMAIL_PROVIDERS } from '../../config/email-providers'; import { useEmailStore } from '../../store/email-store'; +import { connectAccountId } from '../../store/helpers'; +import { allowCertificateReview } from '../../utils/certificate-review'; import { GmailPrivacyNotice } from '../GmailPrivacyNotice'; import { Tooltip } from '../Tooltip'; @@ -20,7 +22,7 @@ type OAuthProviderId = 'gmail' | 'microsoft' | 'yahoo'; const PROVIDER_HINTS = EMAIL_PROVIDERS.map((p) => ({ name: p.name, host: p.imapHost, port: String(p.imapPort) })); export function IMAPStep({ onNext, onBack, onSyncStarted }: IMAPStepProps) { - const { addAccount } = useEmailStore(); + const { addAccount, accounts } = useEmailStore(); const [host, setHost] = useState('imap.sarv.com'); const [port, setPort] = useState('9993'); @@ -31,7 +33,6 @@ export function IMAPStep({ onNext, onBack, onSyncStarted }: IMAPStepProps) { const [error, setError] = useState(''); const [showManual, setShowManual] = useState(false); const [security, setSecurity] = useState<'ssl' | 'starttls' | 'none'>('ssl'); - const [allowInsecure, setAllowInsecure] = useState(false); const [oauthProviders, setOauthProviders] = useState< Array<{ id: OAuthProviderId; label: string; configured: boolean }> >([]); @@ -99,6 +100,8 @@ export function IMAPStep({ onNext, onBack, onSyncStarted }: IMAPStepProps) { try { const cleanPassword = password.replace(/\s+/g, ''); + // A certificate declined on an earlier try is offered again (main asks). + allowCertificateReview(connectAccountId(accounts ?? [], username, host), 'imap'); await addAccount({ host, port: parseInt(port), @@ -108,7 +111,6 @@ export function IMAPStep({ onNext, onBack, onSyncStarted }: IMAPStepProps) { // were stored alike, and None was overruled by the required upgrade. security, secure: security === 'ssl', - allowInsecureTLS: allowInsecure || undefined, }); onSyncStarted(); @@ -292,10 +294,9 @@ export function IMAPStep({ onNext, onBack, onSyncStarted }: IMAPStepProps) { - +

+ If this server uses its own (self-signed) certificate, Sarv Inbox shows it to you to approve when it connects. +

{error && (
diff --git a/apps/desktop/src/components/security/Security.tsx b/apps/desktop/src/components/security/Security.tsx index 40490f29..076b9325 100644 --- a/apps/desktop/src/components/security/Security.tsx +++ b/apps/desktop/src/components/security/Security.tsx @@ -110,7 +110,7 @@ const PROTECTIONS: Array<{ title: string; detail: string }> = [ { title: 'Brand verification (BIMI)', detail: 'A sender domain’s published logo is shown only on mail that passed DMARC, and the blue verified tick only when its Verified Mark Certificate chains to a pinned Mark Verifying Authority for that exact logo and domain. Details per domain under Sender identity.' }, { title: 'Sender reputation', detail: 'As a message arrives, its sending server’s address and its sender domains are checked against spam blocklists through this computer’s DNS, and a listing adds to the spam score before the message is filed. The domains a message links to can be checked too, and how recently its domains were registered. All of it under Security → Blocklists.' }, { title: 'Spam filter', detail: 'Every arriving message is scored from its headers before the AI sees it — failed authentication, a spoofed sender name, a forged reply, missing or mis-dated headers, bulk mail with no unsubscribe, your mail server’s own spam verdict, and senders you have reported. A message over the line is filed as spam with its reasons shown on the shield.' }, - { title: 'Verified TLS to your mail server', detail: 'Certificates are verified and TLS 1.2 is the floor, unless you explicitly allow a self-signed server per account.' }, + { title: 'Verified TLS to your mail server', detail: 'Certificates are always verified and TLS 1.2 is the floor. A server with its own certificate is trusted only for the exact certificate you approve when you add or reconnect the account (Sarv Inbox never asks on its own), and every other certificate is refused.' }, ]; function HeaderBackfillStatus() { diff --git a/apps/desktop/src/components/settings/AccountsTab.tsx b/apps/desktop/src/components/settings/AccountsTab.tsx index cda57ed5..b60c9265 100644 --- a/apps/desktop/src/components/settings/AccountsTab.tsx +++ b/apps/desktop/src/components/settings/AccountsTab.tsx @@ -6,7 +6,8 @@ import { useOAuthSignIn } from '../../hooks/useOAuthSignIn'; import { useReauthSessions } from '../../hooks/useReauthSessions'; import { aiProvidersUsingSignIn } from '../../services/ai-service'; import { useEmailStore } from '../../store/email-store'; -import { accountHost, isAccountEmailDuplicated, effectiveSmtpConfig } from '../../store/helpers'; +import { accountHost, connectAccountId, isAccountEmailDuplicated, effectiveSmtpConfig } from '../../store/helpers'; +import { allowCertificateReview } from '../../utils/certificate-review'; import { findReauthSession } from '../../utils/reauth-sessions'; import { savedAccountSecurity } from '../../utils/saved-account-security'; import { AddAccountModal } from '../AddAccountModal'; @@ -14,6 +15,7 @@ import { ConnectionSecuritySelect } from '../ConnectionSecuritySelect'; import { GmailPrivacyNotice, openInboxPrivacyPolicy } from '../GmailPrivacyNotice'; import { SmtpConfigForm } from '../SmtpConfigForm'; import { Tooltip } from '../Tooltip'; +import { TrustedCertificate } from '../TrustedCertificate'; import { VaultPasswordField } from '../VaultPasswordField'; import { RemovalAccessNote, RevokeFailedNotice, revokeFailureWorthNoticing } from './AccountRemovalNotes'; @@ -96,6 +98,10 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco setImapError(''); setImapLoading(true); try { + // The user asked to reconnect: this connect may ask (in main) about an + // untrusted certificate — armed for the account id the connect runs as. + const host = imapForm.host.trim() || imapConfig.host; + allowCertificateReview(connectAccountId(accounts, imapConfig.username, host), 'imap'); await connect({ ...imapConfig, ...(imapForm.host.trim() ? { host: imapForm.host.trim() } : {}), @@ -235,6 +241,11 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco setImapLoading(true); setImapSuccess(false); try { + // The user asked to reconnect: this connect may ask (in main) about an + // untrusted certificate — armed for the account id the connect runs as. + if (savedAccount.authMethod !== 'oauth2') { + allowCertificateReview(connectAccountId(accounts, savedAccount.username, imapForm.host.trim() || savedAccount.host), 'imap'); + } await connect({ ...savedAccount, ...(imapForm.host.trim() ? { host: imapForm.host.trim() } : {}), @@ -714,6 +725,10 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco
+ {/* The certificate approved for this server, if any (never for OAuth). */} + {!dIsOAuth && detailAccount && ( + + )} {detailReauth && (
@@ -824,6 +839,9 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco
)} + {dSmtpConfigured && !showSmtpForm && !dIsOAuth && detailAccount && dSmtpConfig && ( + + )} {/* Gate on detailIsActive (stable), NOT detailLive — otherwise a transient connection flicker (connected→reconnecting) would unmount the form mid-entry and wipe what you typed. */} diff --git a/apps/desktop/src/store/helpers.ts b/apps/desktop/src/store/helpers.ts index 96b3424d..0808b4e9 100644 --- a/apps/desktop/src/store/helpers.ts +++ b/apps/desktop/src/store/helpers.ts @@ -595,10 +595,10 @@ export const extractSecrets = (config: Record | null | undefined): /** * The vault entry for a config: its secret fields plus the host they're for * (main only ever sends a saved secret to that host) and the transport - * relaxations chosen with them — "allow self-signed" and security 'none' (main - * never sends a saved secret more loosely than that). Undefined when the - * config carries no secret: neither a host nor a relaxation is ever written - * without one. + * relaxation chosen with them — security 'none' (main never sends a saved + * secret more loosely than that). Undefined when the config carries no secret: + * neither a host nor a relaxation is ever written without one. No certificate + * setting is written: an approved certificate is stored by main's own dialog. */ export const vaultEntryFor = ( config: Record | null | undefined, @@ -1061,6 +1061,15 @@ export const findAccountByEmailHost = ( ((a.imapConfig?.host as string) || '').toLowerCase() === (host || '').toLowerCase(), ); +/** + * The account id a connect for these settings runs as: the existing account + * with this email + IMAP host, else the id it will be created under. The ONE + * rule — connect(), addAccount() and the forms that arm main's certificate + * question for that connect (certificates:review) must agree on it. + */ +export const connectAccountId = (accounts: StoredAccount[], email: string, host: string): string => + findAccountByEmailHost(accounts, email, host)?.id ?? accountIdFor(email, host); + /** * Return the accounts registry, migrating the legacy single account into it on * first run. Persists the migrated list so subsequent loads are stable. diff --git a/apps/desktop/src/store/slices/connection-slice.ts b/apps/desktop/src/store/slices/connection-slice.ts index aedb1cf5..a7dfce23 100644 --- a/apps/desktop/src/store/slices/connection-slice.ts +++ b/apps/desktop/src/store/slices/connection-slice.ts @@ -9,8 +9,8 @@ import { isAIAssistEnabled } from '../../services/agent-settings'; import { getDefaultProvider, removeOAuthProvidersForAccount, reportAIUnhealthy, syncAIProviderToMain } from '../../services/ai-service'; import { isOnboardingPending } from '../../services/onboarding-progress'; import { forgetImageTrustAccount, setImageTrustAccount } from '../../utils/remote-images'; -import { loadSavedCredentials, loadSavedSmtpCredentials, saveCredentials, clearCredentials, saveSmtpCredentials, clearSmtpCredentials, deriveSmtpFromImap, forgetLegacySecretsFor, loadSmtpConfigured, saveSmtpConfigured, migrateAccounts, upsertAccount, removeAccount, saveAccounts, saveActiveAccountId, accountIdFor, normalizeAccount, findAccountByEmailHost, vaultEntryFor, vaultHasPassword, effectiveSmtpConfig, loadQuotaCache, saveQuotaCache } from '../helpers'; -import type { ConnectionSlice, EmailStore, SliceCreator, StoredAccount } from '../types'; +import { connectAccountId, loadSavedCredentials, loadSavedSmtpCredentials, saveCredentials, clearCredentials, saveSmtpCredentials, clearSmtpCredentials, deriveSmtpFromImap, forgetLegacySecretsFor, loadSmtpConfigured, saveSmtpConfigured, migrateAccounts, upsertAccount, removeAccount, saveAccounts, saveActiveAccountId, accountIdFor, normalizeAccount, vaultEntryFor, vaultHasPassword, effectiveSmtpConfig, loadQuotaCache, saveQuotaCache } from '../helpers'; +import type { ConnectionSlice, EmailStore, SecurityRefusalCode, SliceCreator, StoredAccount } from '../types'; // Concurrent connects to the SAME account join one run. // @@ -29,6 +29,9 @@ import type { ConnectionSlice, EmailStore, SliceCreator, StoredAccount } from '. // save, a registry upsert and a background sync per duplicate call. Keyed by // ACCOUNT id, so switching accounts still connects both. const connectInFlight = createSingleFlight(); + +/** A refusal made before any credential was sent: shown in the security banner. */ +const isSecurityRefusal = (code: unknown): code is SecurityRefusalCode => code === 'STARTTLS_UNAVAILABLE' || code === 'CERTIFICATE_UNTRUSTED'; const connectionLogger = createLogger('connection-store'); const initialAccounts = migrateAccounts(); @@ -204,8 +207,10 @@ async function doConnect( // Only while the account it was for is still the active one: a late // refusal from an account the user already switched away from must not // mark the account now shown as disconnected. - if (result.code === 'STARTTLS_UNAVAILABLE' && get().activeAccountId === activeAtStart) { - set({ connectionSecurityIssue: result.error ?? null, connected: false, connectionStatus: 'disconnected' }); + // An untrusted certificate (CASA 4.1.2) is shown the same way: main + // already asked about it, and the remedy is in the account settings. + if (isSecurityRefusal(result.code) && get().activeAccountId === activeAtStart) { + set({ connectionSecurityIssue: result.error ?? null, connectionSecurityCode: result.code, connected: false, connectionStatus: 'disconnected' }); } throw Object.assign(new Error(result.error || 'Failed to connect'), { code: result.code }); } @@ -245,8 +250,8 @@ export function followActiveAccount( setImageTrustAccount(after); const written = partial && typeof partial === 'object' ? partial : {}; const stale: Partial = {}; - if (!('connectionSecurityIssue' in written)) stale.connectionSecurityIssue = null; - if (!('smtpSecurityIssue' in written)) stale.smtpSecurityIssue = null; + if (!('connectionSecurityIssue' in written)) Object.assign(stale, { connectionSecurityIssue: null, connectionSecurityCode: null }); + if (!('smtpSecurityIssue' in written)) Object.assign(stale, { smtpSecurityIssue: null, smtpSecurityCode: null }); if (Object.keys(stale).length > 0) (set as (p: Partial) => void)(stale); }) as Parameters>[0]; } @@ -351,8 +356,7 @@ const connectionSlice = ( // on a DIFFERENT provider becomes a separate account. Resolved BEFORE the // single-flight join because it is this connect's identity — what decides // whether another caller is asking for the same thing. - const acctId = findAccountByEmailHost(get().accounts, config.username, config.host)?.id - ?? accountIdFor(config.username, config.host); + const acctId = connectAccountId(get().accounts, config.username, config.host); const pending = connectInFlight.pending(acctId); if (pending) { @@ -395,8 +399,7 @@ const connectionSlice = ( try { // Main injects the vaulted password for this account (see doConnect). - const reconnectAcctId = findAccountByEmailHost(get().accounts, imapConfig.username, imapConfig.host)?.id - ?? accountIdFor(imapConfig.username, imapConfig.host); + const reconnectAcctId = connectAccountId(get().accounts, imapConfig.username, imapConfig.host); const result = await window.electronAPI.imap.connect(imapConfig, reconnectAcctId); if (result.success) { console.log('[Store] Reconnection successful'); @@ -425,7 +428,7 @@ const connectionSlice = ( // Restart IDLE await get().startIdle('INBOX'); } else { - if (result.code === 'STARTTLS_UNAVAILABLE') set({ connectionSecurityIssue: result.error ?? null, connected: false }); + if (isSecurityRefusal(result.code)) set({ connectionSecurityIssue: result.error ?? null, connectionSecurityCode: result.code, connected: false }); throw new Error(result.error || 'Reconnection failed'); } } catch (error) { @@ -545,7 +548,7 @@ const connectionSlice = ( // The sending server would not encrypt (CASA M-5). Every caller but the // settings form swallows this error (startup, lazy send), so without // the flag mail just waits in the Outbox with no reason shown. - if (result.code === 'STARTTLS_UNAVAILABLE' && stillActive()) set({ smtpSecurityIssue: result.error ?? null }); + if (isSecurityRefusal(result.code) && stillActive()) set({ smtpSecurityIssue: result.error ?? null, smtpSecurityCode: result.code }); throw new Error(result.error || 'Failed to connect to SMTP server'); } } catch (error) { @@ -696,8 +699,7 @@ const connectionSlice = ( // Reuse the existing account if this exact email + IMAP host is already // connected (avoids a duplicate); otherwise mint an id keyed by email + host // so the same address on a different provider gets its own account + DB. - const id = findAccountByEmailHost(get().accounts, imapConfig.username, imapConfig.host)?.id - ?? accountIdFor(imapConfig.username, imapConfig.host); + const id = connectAccountId(get().accounts, imapConfig.username, imapConfig.host); // VERIFY BEFORE PERSISTING. Everything below mutates durable state (active // account, localStorage credentials, the main-process runtime) and — when @@ -708,7 +710,9 @@ const connectionSlice = ( // sign-in permanently converted a live app-password account and every sync // after it died at AUTH. if (!opts?.alreadyVerified) { - const probe = await window.electronAPI.imap.probeCredentials(imapConfig as any); + // For the account id it will be saved under: the certificate approved + // for it (or approved during this probe) is the one the probe dials with. + const probe = await window.electronAPI.imap.probeCredentials(imapConfig as any, id); if (!probe.success) { throw new Error(probe.error || 'Could not sign in with those settings'); } @@ -727,6 +731,8 @@ const connectionSlice = ( connectionStatus: get().connectionStatus, connectionSecurityIssue: get().connectionSecurityIssue, smtpSecurityIssue: get().smtpSecurityIssue, + connectionSecurityCode: get().connectionSecurityCode ?? null, + smtpSecurityCode: get().smtpSecurityCode ?? null, folders: get().folders, emails: get().emails, selectedFolderId: get().selectedFolderId, diff --git a/apps/desktop/src/store/types.ts b/apps/desktop/src/store/types.ts index 0ba9b8f2..9084a3ff 100644 --- a/apps/desktop/src/store/types.ts +++ b/apps/desktop/src/store/types.ts @@ -8,6 +8,9 @@ import type { LocalCalendarAvailability } from '../types/local-calendar'; import type { EmailThread } from '../utils/thread-utils'; // Compose email types +/** Why a connect was refused before any credential was sent. */ +export type SecurityRefusalCode = 'STARTTLS_UNAVAILABLE' | 'CERTIFICATE_UNTRUSTED'; + export type ComposeMode = 'new' | 'reply' | 'replyAll' | 'forward'; export interface ComposeState { @@ -161,6 +164,13 @@ export interface ConnectionSlice { * account switch. */ smtpSecurityIssue: string | null; + /** + * What kind of refusal each issue above is, for the banner's headline: + * 'CERTIFICATE_UNTRUSTED' = the server's certificate is not approved (CASA + * 4.1.2), else a STARTTLS refusal. Set with the issue; read only while it is. + */ + connectionSecurityCode?: SecurityRefusalCode | null; + smtpSecurityCode?: SecurityRefusalCode | null; handleDisconnection: () => void; handleReconnection: () => void; setConnectionStatus: (status: ConnectionStatus) => void; diff --git a/apps/desktop/src/utils/certificate-review.ts b/apps/desktop/src/utils/certificate-review.ts new file mode 100644 index 00000000..4e3cdb5e --- /dev/null +++ b/apps/desktop/src/utils/certificate-review.ts @@ -0,0 +1,30 @@ +/** + * The renderer's side of approved mail-server certificates (CASA 4.1.2). The + * window never approves a certificate, and main never asks about one on its + * own: only a connect the user just started from a form may ask, in main's own + * dialog. The form says so with this, right before its connect. + */ + +/** + * Arm main's certificate question for the next connect of this account's + * `kind` server (the user pressed Test / Reconnect / Verify / Connect). + * Fire-and-forget: this message is sent before the connect's own, and main + * handles one window's messages in order, so the arm is in place first. Main + * rate-limits it; without it the connect just reports the refusal. + */ +export function allowCertificateReview(accountId: string | null | undefined, kind: 'imap' | 'smtp'): void { + if (!accountId) return; + try { + void window.electronAPI?.certificates?.review(accountId, kind)?.catch(() => { /* best-effort */ }); + } catch { + // An older main without the channel: the connect only reports the refusal. + } +} + +/** "AB:CD:…" in groups of eight pairs, so a long fingerprint wraps where people compare it. */ +export function formatFingerprint(sha256: string): string[] { + const pairs = sha256.split(':'); + const groups: string[] = []; + for (let i = 0; i < pairs.length; i += 8) groups.push(pairs.slice(i, i + 8).join(':')); + return groups; +} diff --git a/apps/desktop/test/unit/electron/ipc/certificate-approval.test.ts b/apps/desktop/test/unit/electron/ipc/certificate-approval.test.ts new file mode 100644 index 00000000..338c6527 --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/certificate-approval.test.ts @@ -0,0 +1,446 @@ +import { accountIdFor, getLogLevel, setLogLevel, setLogSink, type IMAPConfig } from '@sarvinbox/core'; +import type { MessageBoxOptions } from 'electron'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * CASA 4.1.2 end to end, through main's REAL connect handlers, the REAL IMAP + * and SMTP clients and REAL TLS servers whose certificates the test controls. + * Only the native dialog is stubbed (it answers as the user would). What breaks + * if this file fails: + * - a password reaches a server whose certificate the user has not approved + * (each refusal asserts the server never received LOGIN/AUTH); + * - the trust question pops up for a connect the user did not start — a + * focus/online reconnect or a background sync — so an attacker on the + * network gets a one-click way to the password; + * - an approved self-signed server still cannot be used, by the primary + * connection, the pool, a background account, the add-account probe or SMTP; + * - Cancel connects anyway; + * - an account saved with the retired "allow self-signed" switch connects + * without being asked from its settings; + * - a switch of account during the question connects one account's + * credentials on the other's connection; + * - an unreadable vault approves or trusts anything; + * - the password reaches app.log on any of these paths. + */ + +const h = vi.hoisted(() => { + const on = () => vi.fn(); + const state = { connected: false, current: 'acct-active', clients: [] as Array<{ disconnect: () => Promise }>, pools: [] as Array<{ close: () => Promise }> }; + return { + handlers: new Map any>(), + state, + smtpClient: null as unknown, + smtpClients: new Map(), + engine: { + isConnected: vi.fn(() => state.connected), + // The engine's connect is the REAL client's: the handshake, the pin + // check and the LOGIN all happen for real against the test server. + connect: vi.fn(async (cfg: IMAPConfig) => { + const { ImapFlowClient: Client } = await import('@sarvinbox/core'); + const client = new Client(); + await client.connect(cfg); + state.clients.push(client); + state.connected = true; + }), + isConnectedWith: vi.fn((cfg: unknown) => state.connected && h.engine.connect.mock.calls.at(-1)?.[0] === cfg), + isRealTimeActive: vi.fn(() => false), + // The pool is real too: its sockets must carry the pin. + initializePool: vi.fn(async (cfg: IMAPConfig) => { + const { IMAPConnectionPool: Pool } = await import('@sarvinbox/core'); + const pool = new Pool({ maxConnections: 2, connectionTimeout: 5000, idleTimeout: 60_000 }); + state.pools.push(pool); + await pool.initialize(cfg); + }), + isConnecting: vi.fn(() => false), + isForceReconnecting: vi.fn(() => false), + forceReconnect: vi.fn(async () => {}), + disconnect: vi.fn(async () => { state.connected = false; }), + processPendingOps: vi.fn(async () => {}), + stopRealTime: vi.fn(async () => {}), + startRealTime: vi.fn(async () => 'idle'), + syncAll: vi.fn(async () => ({})), + onDisconnect: on(), onReconnect: on(), onReconnecting: on(), onReconnectFailed: on(), onAuthError: on(), onSecurityError: on(), + on: vi.fn(), removeListener: vi.fn(), + }, + }; +}); + +vi.mock('electron', () => ({ + ipcMain: { handle: (name: string, fn: (...a: any[]) => any) => h.handlers.set(name, fn) }, + app: { getPath: () => '/tmp/sarvinbox-cert-approval-test', getName: () => 'Sarv Inbox Test', isPackaged: false }, + safeStorage: { + isEncryptionAvailable: () => true, + getSelectedStorageBackend: () => 'gnome_libsecret', + encryptString: (s: string) => Buffer.from(`${process.platform === 'linux' ? 'v11' : ''}enc(${s})`, 'utf8'), + decryptString: (b: Buffer) => /^(?:v11)?enc\((.*)\)$/s.exec(b.toString('utf8'))![1], + }, + BrowserWindow: { fromWebContents: () => null }, + dialog: {}, +})); +vi.mock('../../../../electron/services/core-db', async () => await import('../../../../electron/services/__testing__/fake-core-db')); +vi.mock('../../../../electron/services/accounts-registry', () => ({ readRegistryAccounts: () => [], registryAccountEmail: () => null })); +vi.mock('../../../../electron/services/quota-backoff', () => ({ + createQuotaBackoff: () => ({ remainingMs: () => 0, park: vi.fn(), clear: vi.fn(), parkOnError: () => ({ reason: null }) }), +})); +vi.mock('../../../../electron/shared', () => ({ + getStorage: () => null, + requireStorage: () => ({}), + getStorageFor: () => null, + getSyncEngine: () => h.engine, + getSyncEngineFor: () => h.engine, + requireSyncEngine: () => h.engine, + getMainWindow: () => null, + sendToWindow: vi.fn(), + getCurrentAccountId: () => h.state.current, + setCurrentAccount: vi.fn(), + getIsQuitting: () => false, + getSystemSuspended: () => false, + getSmtpClient: () => h.smtpClient, + setSmtpClient: (client: unknown) => { h.smtpClient = client; }, + getSmtpClientFor: (id: string) => h.smtpClients.get(id) ?? null, + setSmtpClientFor: (id: string, client: unknown) => { h.smtpClients.set(id, client); }, + getAccountIdForStorage: () => null, +})); +vi.mock('../../../../electron/services/accounts-runtime', () => ({ + ensureAccountRuntime: vi.fn(async () => ({ storage: { getFolders: async () => [] }, syncEngine: h.engine })), + accountInboxUnread: vi.fn(() => 0), + accountDbExists: () => false, +})); +vi.mock('../../../../electron/services/oauth-service', () => ({ getAccessTokenForMailHost: vi.fn(), attachImapBearer: (c: unknown) => c })); +vi.mock('../../../../electron/services/body-prefetch-scheduler', () => ({ kickBodyPrefetchScheduler: vi.fn() })); +vi.mock('../../../../electron/services/backfill-scheduler', () => ({ kickBackfillScheduler: vi.fn() })); +vi.mock('../../../../electron/services/connection-health', () => ({ markConnectionUnstable: vi.fn() })); +vi.mock('../../../../electron/services/imap-account-store', () => ({ + saveImapAccount: vi.fn(async () => {}), loadImapAccount: vi.fn(), clearImapAccount: vi.fn(), forgetImapAccountFor: vi.fn(), +})); +vi.mock('../../../../electron/sentry', () => ({ identifyClient: vi.fn() })); +vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ + getPipelineUserEmail: () => 'me@office.lan', setPipelineUserProfile: vi.fn(), provisionCategoryLabelsOnConnect: vi.fn(), + retryPipelineInitOnConnect: vi.fn(), getPipelineUserName: vi.fn(() => 'Me'), +})); +vi.mock('../../../../electron/services/outbox-service', () => ({ + getOutboxQueue: vi.fn(), drainOutbox: vi.fn(async () => {}), getOutboxQueueForAccount: vi.fn(), + drainOutboxForAccount: vi.fn(async () => {}), notifyOutboxChanged: vi.fn(), +})); +vi.mock('../../../../electron/services/pgp-service', () => ({ sendTransformFor: vi.fn() })); +vi.mock('../../../../electron/ipc/follow-up-handlers', () => ({ recordFollowUpForSend: vi.fn() })); + +import { captureLogs, type CapturedLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { makeSelfSigned, startMailServer, type TestCertificate, type TestMailServer } from '../../../../../../packages/core/src/test-support/tls-test-servers'; +import { registerCertificateHandlers } from '../../../../electron/ipc/certificate-handlers'; +import { registerSmtpHandlers } from '../../../../electron/ipc/smtp-handlers'; +import { registerSyncHandlers } from '../../../../electron/ipc/sync-handlers'; +import { resetFakeCoreDb, state as dbState } from '../../../../electron/services/__testing__/fake-core-db'; +import { ACCOUNT_CHANGED_DURING_REVIEW, resetCertificateTrustForTest, REVIEW_ARM_INTERVAL_MS, setCertificateTrustDepsForTest } from '../../../../electron/services/certificate-trust'; +import { getAccountSecrets, setAccountCertificatePin, setAccountSecrets } from '../../../../electron/services/secure-credential-store'; + +const PASSWORD = 'e2e-sentinel-password-91c4'; +const USER = 'me@office.lan'; +const HOST = '127.0.0.1'; + +let approvedCert: TestCertificate; +let otherCert: TestCertificate; +let imapServer: TestMailServer; +let imapChanged: TestMailServer; +let smtpServer: TestMailServer; +const extraServers: TestMailServer[] = []; + +beforeAll(async () => { + approvedCert = await makeSelfSigned(); + otherCert = await makeSelfSigned(); + imapServer = await startMailServer({ protocol: 'imap', mode: 'ssl', chain: approvedCert.pem, key: approvedCert.key }); + imapChanged = await startMailServer({ protocol: 'imap', mode: 'ssl', chain: otherCert.pem, key: otherCert.key }); + smtpServer = await startMailServer({ protocol: 'smtp', mode: 'starttls', chain: approvedCert.pem, key: approvedCert.key }); +}); +afterAll(async () => { + await Promise.all([imapServer, imapChanged, smtpServer, ...extraServers].map((s) => s.close())); +}); + +const showMessageBox = vi.fn(async (_window: unknown, _options: MessageBoxOptions) => ({ response: 0 })); +const answers = (...responses: number[]) => { for (const response of responses) showMessageBox.mockResolvedValueOnce({ response }); }; +const dialogDetail = (call = 0) => (showMessageBox.mock.calls[call][1] as { detail: string }).detail; +let restoreDeps: () => void; +let clock = Date.now(); +/** The user pressed Test / Reconnect / Verify: the form arms main's question for this account+kind. */ +const arm = async (accountId: string, kind: 'imap' | 'smtp') => { + clock += REVIEW_ARM_INTERVAL_MS; // past the per-pair rate limit + expect(await h.handlers.get('certificates:review')!({}, accountId, kind)).toEqual({ success: true, data: { armed: true } }); +}; +let logs: CapturedLogs; +let baseline: { imap: number; changed: number; smtp: number }; +const logins = () => ({ imap: imapServer.credentialCommands - baseline.imap, changed: imapChanged.credentialCommands - baseline.changed, smtp: smtpServer.credentialCommands - baseline.smtp }); + +const imapConfig = (server: TestMailServer, extra: Record = {}): IMAPConfig => ({ + host: HOST, port: server.port, secure: true, security: 'ssl', username: USER, password: PASSWORD, + authMethod: 'password', connectionTimeout: 5000, ...extra, +} as IMAPConfig); +const smtpConfig = (extra: Record = {}) => ({ + host: HOST, port: smtpServer.port, secure: false, security: 'starttls', username: USER, password: PASSWORD, authMethod: 'password', ...extra, +}); +const imapId = () => accountIdFor(USER, HOST); + +beforeEach(async () => { + resetFakeCoreDb(); + resetCertificateTrustForTest(); + h.handlers.clear(); + h.state.connected = false; + h.state.current = 'acct-active'; + h.smtpClient = null; + h.smtpClients.clear(); + h.engine.connect.mockClear(); + h.engine.initializePool.mockClear(); + showMessageBox.mockReset().mockResolvedValue({ response: 1 }); + restoreDeps = setCertificateTrustDepsForTest({ showMessageBox, now: () => clock }); + registerSyncHandlers(); + registerSmtpHandlers(); + registerCertificateHandlers(); + baseline = { imap: imapServer.credentialCommands, changed: imapChanged.credentialCommands, smtp: smtpServer.credentialCommands }; + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(async () => { + logs.stop(); + restoreDeps(); + await Promise.all(h.state.clients.splice(0).map((c) => c.disconnect().catch(() => {}))); + await Promise.all(h.state.pools.splice(0).map((p) => p.close().catch(() => {}))); + // The password never reaches the log, on any path below. + expect(logs.containing(PASSWORD)).toEqual([]); +}); + +describe('adding an account on a self-signed IMAP server (the probe)', () => { + // Breaks: a new self-signed account can never be added (no question), or the + // probe sends the password before the user approved the certificate. + it('asks with the real certificate when the user tests, stores it on Trust, and only then logs in', async () => { + await arm(imapId(), 'imap'); + answers(0); + const res = await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId()); + expect(res).toEqual({ success: true }); + expect(showMessageBox).toHaveBeenCalledTimes(1); + expect(dialogDetail()).toContain(approvedCert.sha256); + expect(dialogDetail()).toContain(`${HOST}:${imapServer.port}`); + expect(logins().imap).toBe(1); // the retry with the pin; the first attempt sent nothing + expect((await getAccountSecrets(imapId()))?.certificates?.imap).toMatchObject({ host: HOST, port: imapServer.port, sha256: approvedCert.sha256 }); + }); + + // THE review finding, on the probe. Breaks: a probe the window sends on its + // own (or a compromised window) raises the question. + it('refuses an unarmed probe at once, with no question and no LOGIN', async () => { + const res = await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId()); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED', error: expect.stringContaining('Settings → Accounts') }); + expect(showMessageBox).not.toHaveBeenCalled(); + expect(logins().imap).toBe(0); + }); + + // Breaks: Cancel connects anyway, or the refusal reads as retryable; or a + // second press of Test cannot ask again. + it('refuses on Cancel without ever sending the password, and asks again on the next test', async () => { + await arm(imapId(), 'imap'); + answers(1); + const res = await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId()); + expect(res).toMatchObject({ success: false, retryable: false, code: 'CERTIFICATE_UNTRUSTED', error: expect.stringContaining('Settings → Accounts') }); + expect(logins().imap).toBe(0); + await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId()); + expect(showMessageBox).toHaveBeenCalledTimes(1); + + await arm(imapId(), 'imap'); + answers(0); + expect(await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId())).toEqual({ success: true }); + expect(showMessageBox).toHaveBeenCalledTimes(2); + }); + + // Breaks: a window arms the question as fast as it likes and keeps the + // modal dialog up. + it('will not arm the same account and transport twice within the rate limit', async () => { + await arm(imapId(), 'imap'); + expect(await h.handlers.get('certificates:review')!({}, imapId(), 'imap')).toEqual({ success: true, data: { armed: false } }); + }); + + // THE unreadable-store rule, end to end. Breaks: a vault that cannot be read + // lets the self-signed server through, or the user approves into it. + it('refuses, without a question or a LOGIN, while the vault cannot be read', async () => { + await arm(imapId(), 'imap'); + dbState.fail.add('blob-read'); + const res = await h.handlers.get('imap:probeCredentials')!({}, imapConfig(imapServer), imapId()); + dbState.fail.delete('blob-read'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED', retryable: true }); + expect(showMessageBox).not.toHaveBeenCalled(); + expect(logins().imap).toBe(0); + }); +}); + +describe('a saved IMAP account (imap:connect, the pool, background sync)', () => { + beforeEach(async () => { + await setAccountSecrets('acct-a', { imap: { password: PASSWORD, host: HOST } }); + }); + const saved = (server: TestMailServer, extra: Record = {}) => { + const { password: _typed, ...config } = imapConfig(server, extra); + return config; + }; + + // THE review finding. Breaks: a focus/online reconnect on a hostile network + // pops up "Trust …?" by itself; one click pins the attacker's certificate. + it('never asks on an automatic reconnect: refuses at once, tagged, without LOGIN', async () => { + const res = await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + expect(res).toMatchObject({ success: false, retryable: false, code: 'CERTIFICATE_UNTRUSTED', error: expect.stringContaining('Settings → Accounts') }); + expect(showMessageBox).not.toHaveBeenCalled(); + expect(logins().imap).toBe(0); + }); + + // Breaks: background sync raises the dialog (unprompted, and an unanswered + // dialog would hold the cycle) — even when the user just armed that account. + it('never asks from background sync, even with an arm waiting', async () => { + await arm('acct-a', 'imap'); + const config = saved(imapServer); + for (let i = 0; i < 2; i++) { + const res = await h.handlers.get('accounts:backgroundSync')!({}, { accountId: 'acct-a', config }); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED', retryable: false }); + } + expect(showMessageBox).not.toHaveBeenCalled(); + expect(logins().imap).toBe(0); + }); + + // Breaks: the approved certificate does not reach the primary connection or + // the pool's sockets (functions don't survive the config's travels; the pin + // is data and each socket builds its own check). + it('approves once from the settings, then the primary and the pool connect with the pin', async () => { + await arm('acct-a', 'imap'); + answers(0); + const res = await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + expect(res).toMatchObject({ success: true }); + const dialled = h.engine.connect.mock.calls.at(-1)![0]; + expect(dialled.certificatePin).toEqual({ sha256: approvedCert.sha256, pem: expect.stringContaining('BEGIN CERTIFICATE') }); + expect(h.engine.initializePool).toHaveBeenCalledWith(dialled, expect.anything()); + expect(logins().imap).toBe(2); // primary + the pool's warm-up socket + // A later automatic reconnect uses the pin and asks nothing. + h.state.connected = false; + expect(await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a')).toMatchObject({ success: true }); + expect(showMessageBox).toHaveBeenCalledTimes(1); + }); + + // Review item 3. Breaks: the user switches to account B while A's dialog is + // open, and the retry connects A's credentials on B's engine. + it('does not retry on another account\'s engine when the account changed during the question', async () => { + await arm('acct-a', 'imap'); + showMessageBox.mockImplementationOnce(async () => { h.state.current = 'acct-b'; return { response: 0 }; }); + const res = await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + expect(res).toEqual({ success: false, error: ACCOUNT_CHANGED_DURING_REVIEW, retryable: true, code: 'CERTIFICATE_UNTRUSTED' }); + expect(h.engine.connect).toHaveBeenCalledOnce(); + expect(logins().imap).toBe(0); + }); + + // THE finding, end to end. Breaks: after approval, a server presenting a + // different certificate (renewed, or someone intercepting) is sent the + // password — automatically without a word, or after a question that does not + // say it changed. + it('refuses a different certificate before LOGIN; from the settings it says it CHANGED', async () => { + await setAccountCertificatePin('acct-a', 'imap', { + host: HOST, port: imapChanged.port, sha256: approvedCert.sha256, pem: approvedCert.pem, approvedAt: 1, + subject: 'CN=mail.internal', issuer: 'CN=mail.internal', validFrom: 'a', validTo: 'b', + }); + expect(await h.handlers.get('imap:connect')!({}, saved(imapChanged), 'acct-a')).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED' }); + expect(showMessageBox).not.toHaveBeenCalled(); + await arm('acct-a', 'imap'); + answers(1); + const res = await h.handlers.get('imap:connect')!({}, saved(imapChanged), 'acct-a'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED', retryable: false }); + expect(dialogDetail()).toContain('CHANGED'); + expect(dialogDetail()).toContain(otherCert.sha256); + expect(logins().changed).toBe(0); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap?.sha256).toBe(approvedCert.sha256); + }); + + // CASA 4.1.2 migration. Breaks: an account saved with "allow self-signed" + // keeps connecting to any certificate, is asked unprompted on its first + // automatic reconnect, or is never asked from its settings. + it('refuses a migrated "allow self-signed" account automatically, and asks once from the settings', async () => { + dbState.blobs.set('secure-credentials', Buffer.from(`PLAIN1:${JSON.stringify({ 'acct-a': { imap: { password: PASSWORD, host: HOST, allowInsecureTLS: true, allowPlaintext: false } } })}`)); + const automatic = await h.handlers.get('imap:connect')!({}, saved(imapServer, { allowInsecureTLS: true }), 'acct-a'); + expect(automatic).toMatchObject({ success: false, retryable: false, code: 'CERTIFICATE_UNTRUSTED', error: expect.stringContaining('reconnect the account') }); + expect(showMessageBox).not.toHaveBeenCalled(); + + await arm('acct-a', 'imap'); + answers(0); + expect(await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a')).toMatchObject({ success: true }); + expect(dialogDetail()).toContain('was set to accept any certificate'); + expect((await getAccountSecrets('acct-a'))?.imap).not.toHaveProperty('allowInsecureTLS'); + }); + + // Multi-account. Breaks: account B on the same server rides on account A's + // approval (pins are per account + transport + host + port). + it('does not apply one account\'s approval to another account on the same server', async () => { + await arm('acct-a', 'imap'); + answers(0); + await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + await setAccountSecrets('acct-b', { imap: { password: PASSWORD, host: HOST } }); + h.state.connected = false; + const res = await h.handlers.get('imap:connect')!({}, { ...saved(imapServer), username: 'other@office.lan' }, 'acct-b'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED' }); + expect(showMessageBox).toHaveBeenCalledTimes(1); + }); + + // Breaks: removing the approval in the settings leaves it trusted, or the + // next automatic reconnect asks about it. + it('stops trusting a removed certificate, without asking', async () => { + await arm('acct-a', 'imap'); + answers(0); + await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + expect(await h.handlers.get('certificates:remove')!({}, 'acct-a', 'imap')).toEqual({ success: true, data: { removed: true } }); + expect(h.engine.disconnect).toHaveBeenCalled(); + const before = logins().imap; + const res = await h.handlers.get('imap:connect')!({}, saved(imapServer), 'acct-a'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED' }); + expect(logins().imap).toBe(before); + expect(showMessageBox).toHaveBeenCalledTimes(1); + }); +}); + +describe('SMTP on a self-signed sending server (STARTTLS)', () => { + beforeEach(async () => { + await setAccountSecrets('acct-a', { smtp: { password: PASSWORD, host: HOST } }); + }); + const saved = (extra: Record = {}) => { + const { password: _typed, ...config } = smtpConfig(extra); + return config; + }; + + // Breaks: startup's or a lazy send's SMTP connect raises the question by itself. + it('never asks on a connect the user did not start', async () => { + const res = await h.handlers.get('smtp:connect')!({}, saved(), 'acct-a'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED' }); + expect(showMessageBox).not.toHaveBeenCalled(); + expect(logins().smtp).toBe(0); + }); + + // Breaks: a self-signed sending server can never be used, or AUTH is sent + // before the certificate is approved. + it('asks when the user verifies, stores the pin for SMTP, and authenticates only with it', async () => { + await arm('acct-a', 'smtp'); + answers(0); + expect(await h.handlers.get('smtp:connect')!({}, saved(), 'acct-a')).toEqual({ success: true }); + expect(logins().smtp).toBe(1); + expect((await getAccountSecrets('acct-a'))?.certificates?.smtp).toMatchObject({ host: HOST, port: smtpServer.port, sha256: approvedCert.sha256 }); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toBeUndefined(); + // Send-as for the same account reuses the approval, unasked. + expect(await h.handlers.get('smtp:connectFor')!({}, 'acct-a', saved())).toEqual({ success: true }); + expect(showMessageBox).toHaveBeenCalledTimes(1); + }); + + // Review item 3. Breaks: the retry connects account A's sending password on + // the shared SMTP client after the user switched to account B. + it('does not retry on the shared client when the account changed during the question', async () => { + await arm('acct-a', 'smtp'); + showMessageBox.mockImplementationOnce(async () => { h.state.current = 'acct-b'; return { response: 0 }; }); + const res = await h.handlers.get('smtp:connect')!({}, saved(), 'acct-a'); + expect(res).toMatchObject({ success: false, retryable: true, error: ACCOUNT_CHANGED_DURING_REVIEW }); + expect(logins().smtp).toBe(0); + }); + + // Breaks: Cancel still sends the sending password, or the outbox drains to it. + it('refuses on Cancel before AUTH, tagged for the banner', async () => { + await arm('acct-a', 'smtp'); + answers(1); + const res = await h.handlers.get('smtp:connect')!({}, saved(), 'acct-a'); + expect(res).toMatchObject({ success: false, code: 'CERTIFICATE_UNTRUSTED', retryable: false }); + expect(logins().smtp).toBe(0); + expect(smtpServer.plaintext).not.toContain(PASSWORD); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/certificate-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/certificate-handlers.test.ts new file mode 100644 index 00000000..e77ffb92 --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/certificate-handlers.test.ts @@ -0,0 +1,120 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// The window's only handle on approved certificates (CASA 4.1.2): see, +// remove, and arm the question for a connect the user started — never approve. +// What breaks if this file fails: a removal does not take effect until the next +// network blip (live connections keep the removed certificate), a malformed +// request reaches the vault or the arm, or a vault error reaches the window as +// raw text (which can quote stored data). + +const h = vi.hoisted(() => ({ + handlers: new Map any>(), + list: vi.fn(), + remove: vi.fn(), + arm: vi.fn(), + engine: { disconnect: vi.fn(async () => {}) }, + smtpFor: { disconnect: vi.fn(async () => {}) }, + smtpActive: { disconnect: vi.fn(async () => {}) }, + current: 'acct-a', +})); + +vi.mock('electron', () => ({ ipcMain: { handle: (name: string, fn: (...a: any[]) => any) => h.handlers.set(name, fn) } })); +vi.mock('@sarvinbox/core', async () => ({ + ...(await import('../../../helpers/core-log-helpers')), + createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }), +})); +vi.mock('../../../../electron/services/certificate-trust', () => ({ + listAccountCertificates: h.list, + removeAccountCertificate: h.remove, + armCertificateReview: h.arm, +})); +vi.mock('../../../../electron/shared', () => ({ + getSyncEngineFor: () => h.engine, + getSmtpClientFor: () => h.smtpFor, + getSmtpClient: () => h.smtpActive, + getCurrentAccountId: () => h.current, +})); + +import { registerCertificateHandlers } from '../../../../electron/ipc/certificate-handlers'; + +beforeEach(() => { + h.handlers.clear(); + for (const fn of [h.list, h.remove, h.arm, h.engine.disconnect, h.smtpFor.disconnect, h.smtpActive.disconnect]) fn.mockReset(); + h.list.mockResolvedValue({ imap: { host: 'imap.office.lan', port: 993, sha256: 'AB' } }); + h.remove.mockResolvedValue(true); + h.current = 'acct-a'; + registerCertificateHandlers(); +}); +const call = (name: string, ...args: unknown[]) => h.handlers.get(name)!({}, ...args); + +describe('certificates:list', () => { + it('answers the account\'s approved certificates', async () => { + await expect(call('certificates:list', 'acct-a')).resolves.toEqual({ success: true, data: { imap: { host: 'imap.office.lan', port: 993, sha256: 'AB' } } }); + }); + + // Breaks: a vault error's text (which can quote stored data) reaches the window. + it('answers a fixed message when the vault cannot be read, and refuses a missing id', async () => { + h.list.mockRejectedValueOnce(new Error('decrypt failed for {"imap":{"password":"x"}}')); + await expect(call('certificates:list', 'acct-a')).resolves.toEqual({ success: false, error: 'Approved certificates could not be read. Try again in a moment.' }); + await expect(call('certificates:list', '')).resolves.toMatchObject({ success: false }); + await expect(call('certificates:list', { evil: true })).resolves.toMatchObject({ success: false }); + expect(h.list).toHaveBeenCalledTimes(1); + }); +}); + +describe('certificates:remove', () => { + // Breaks: connections opened under the removed certificate live on. + it('closes the account\'s IMAP connection after removing its certificate', async () => { + await expect(call('certificates:remove', 'acct-a', 'imap')).resolves.toEqual({ success: true, data: { removed: true } }); + expect(h.remove).toHaveBeenCalledWith('acct-a', 'imap'); + expect(h.engine.disconnect).toHaveBeenCalledOnce(); + expect(h.smtpFor.disconnect).not.toHaveBeenCalled(); + }); + + it('closes the account\'s sending connections — its own, and the shared one when it is the active account', async () => { + await call('certificates:remove', 'acct-a', 'smtp'); + expect(h.smtpFor.disconnect).toHaveBeenCalledOnce(); + expect(h.smtpActive.disconnect).toHaveBeenCalledOnce(); + h.current = 'acct-other'; + await call('certificates:remove', 'acct-a', 'smtp'); + expect(h.smtpActive.disconnect).toHaveBeenCalledOnce(); + }); + + // Breaks: nothing removed still tears down a working connection; a failing + // teardown turns a done removal into an error. + it('closes nothing when there was nothing to remove, and survives a failing teardown', async () => { + h.remove.mockResolvedValueOnce(false); + await expect(call('certificates:remove', 'acct-a', 'imap')).resolves.toEqual({ success: true, data: { removed: false } }); + expect(h.engine.disconnect).not.toHaveBeenCalled(); + h.engine.disconnect.mockRejectedValueOnce(new Error('socket gone')); + await expect(call('certificates:remove', 'acct-a', 'imap')).resolves.toEqual({ success: true, data: { removed: true } }); + }); + + // Breaks: a malformed kind reaches the vault, or a vault error's text the window. + it('refuses a bad kind or id, and answers a fixed message on a vault error', async () => { + await expect(call('certificates:remove', 'acct-a', 'pop3')).resolves.toMatchObject({ success: false }); + await expect(call('certificates:remove', 'x'.repeat(600), 'imap')).resolves.toMatchObject({ success: false }); + expect(h.remove).not.toHaveBeenCalled(); + h.remove.mockRejectedValueOnce(new Error('vault locked')); + await expect(call('certificates:remove', 'acct-a', 'imap')).resolves.toEqual({ success: false, error: 'The approved certificate could not be removed. Try again in a moment.' }); + }); +}); + +describe('certificates:review', () => { + // Breaks: a form's Reconnect / Verify can never ask about a self-signed + // server, or the window learns nothing when the arm was refused. + it('arms the question for that account and transport, and says whether it did', async () => { + h.arm.mockReturnValueOnce('armed').mockReturnValueOnce('too-soon'); + await expect(call('certificates:review', 'acct-a', 'smtp')).resolves.toEqual({ success: true, data: { armed: true } }); + await expect(call('certificates:review', 'acct-a', 'smtp')).resolves.toEqual({ success: true, data: { armed: false } }); + expect(h.arm).toHaveBeenCalledWith('acct-a', 'smtp'); + }); + + // Breaks: a malformed request arms something (every account, a bogus kind). + it('refuses a missing id or a bad kind without arming anything', async () => { + await expect(call('certificates:review', undefined, 'imap')).resolves.toMatchObject({ success: false }); + await expect(call('certificates:review', 'acct-a', 'pop3')).resolves.toMatchObject({ success: false }); + await expect(call('certificates:review', 'acct-a')).resolves.toMatchObject({ success: false }); + expect(h.arm).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts b/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts index e5412375..e9e3b8ab 100644 --- a/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts +++ b/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts @@ -2,8 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; // CASA M-5 in main's imap:connect. What breaks if this file fails: // - the last-good config is saved without the account's connection security, -// so a recovered "None" account (or a self-signed one) dials as -// STARTTLS-required and fails after a restart; +// so a recovered "None" account dials as STARTTLS-required and fails after a +// restart (or it records the retired "allow self-signed" switch, or a pin); // - a STARTTLS refusal is retried as a blip, or — worse — handled like a // rejected password, which forgets the saved account; // - an account that is already connected reconnects with its OLD settings @@ -19,7 +19,7 @@ const h = vi.hoisted(() => { return { handlers: new Map any>(), listeners, - sent: [] as Array<[string, unknown]>, + sent: [] as Array<[string, unknown] | [string, unknown, unknown]>, saveImapAccount: vi.fn(async () => {}), clearImapAccount: vi.fn(async () => {}), forgetImapAccountFor: vi.fn(async (_account: Record) => true), @@ -57,6 +57,8 @@ vi.mock('electron', () => ({ vi.mock('@sarvinbox/core', async () => ({ // The real transport rules (pure): which relaxations a config asks for and may have. ...(await import('@sarvinbox/core/connection-security')), + // The real certificate rules (pure): which failures are an untrusted certificate, and the pin options. + ...(await import('../../../../../../packages/core/src/utils/tls')), withTimeout: (p: Promise) => p, accountIdFor: (user: string, host?: string) => (host ? `acct-${user}--${host}` : `acct-${user}`), ImapFlowClient: class {}, @@ -82,7 +84,7 @@ vi.mock('../../../../electron/shared', () => ({ getSyncEngine: () => h.active ?? h.engine, getSyncEngineFor: () => h.engine, requireSyncEngine: () => h.engine, - getMainWindow: () => ({ isDestroyed: () => false, webContents: { send: (channel: string, payload?: unknown) => h.sent.push([channel, payload]) } }), + getMainWindow: () => ({ isDestroyed: () => false, webContents: { send: (channel: string, payload?: unknown, code?: unknown) => h.sent.push(code === undefined ? [channel, payload] : [channel, payload, code]) } }), sendToWindow: vi.fn(), getCurrentAccountId: () => 'acct-active', setCurrentAccount: vi.fn(), @@ -140,24 +142,32 @@ beforeEach(() => { }); describe('imap:connect — connection security (CASA M-5)', () => { - it('saves the account\'s connection security and self-signed choice with the last-good config', async () => { - expect(await connect(NONE_ACCOUNT)).toMatchObject({ success: true }); - expect(h.saveImapAccount).toHaveBeenCalledWith(expect.objectContaining({ security: 'none', allowInsecureTLS: true })); + // Changed deliberately (certificate pinning, CASA 4.1.2): this also used to + // pin that the "allow self-signed" choice was saved with the last-good + // config. The switch is retired; recovery reconnects through imap:connect, + // where main applies the account's approved certificate itself. + it('saves the account\'s connection security with the last-good config, and never the retired switch or a pin', async () => { + expect(await connect({ ...NONE_ACCOUNT, certificatePin: { sha256: 'AB', pem: 'FROM-THE-WINDOW' } })).toMatchObject({ success: true }); + expect(h.saveImapAccount).toHaveBeenCalledWith(expect.objectContaining({ security: 'none' })); + const saved = (h.saveImapAccount.mock.calls.at(-1) as unknown[])[0]; + expect(saved).not.toHaveProperty('allowInsecureTLS'); + expect(saved).not.toHaveProperty('certificatePin'); }); // The last-good config feeds startup recovery (imap:getSavedConfig). Breaks: // it records the relaxation the request asked for rather than the one the // saved password was actually sent with, and recovery asks for it again. - it('saves the self-signed choice that was used, not the one the request asked for', async () => { + // Changed deliberately (certificate pinning): this used to exercise the + // retired self-signed switch; it now exercises connection security. + it('saves the connection security that was used, not the one the request asked for', async () => { resetFakeCoreDb(); - await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'mail.example.org', allowInsecureTLS: true } }); + await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'mail.example.org', allowPlaintext: false } }); const { password: _typed, ...savedAccount } = NONE_ACCOUNT; - expect(await connect({ ...savedAccount, security: 'starttls', allowInsecureTLS: false })).toMatchObject({ success: true }); - expect(h.saveImapAccount).toHaveBeenLastCalledWith(expect.objectContaining({ allowInsecureTLS: false })); - // A typed password with a "true" that is not a boolean was verified (core - // only honours the boolean), so that is what is recorded. - expect(await connect({ ...NONE_ACCOUNT, allowInsecureTLS: 'true' })).toMatchObject({ success: true }); - expect(h.saveImapAccount).toHaveBeenLastCalledWith(expect.objectContaining({ allowInsecureTLS: false })); + // Asked for 'none', saved without it: refused, nothing saved. + expect(await connect(savedAccount)).toMatchObject({ success: false, retryable: false }); + expect(h.saveImapAccount).not.toHaveBeenCalled(); + expect(await connect({ ...savedAccount, security: 'starttls' })).toMatchObject({ success: true }); + expect(h.saveImapAccount).toHaveBeenLastCalledWith(expect.objectContaining({ security: 'starttls' })); }); it('reports a STARTTLS refusal with its code, not retryable, and keeps the saved account', async () => { @@ -188,10 +198,23 @@ describe('imap:connect — connection security (CASA M-5)', () => { expect(h.engine.connect).not.toHaveBeenCalled(); }); + // Changed deliberately (certificate pinning): the event now carries which + // refusal it is, so the banner can say "would not encrypt" or "certificate + // not trusted". it('tells the window when the server stops encrypting mid-session, without forgetting the account', async () => { await connect(NONE_ACCOUNT); - h.listeners.get('security-error')!(new Error('The incoming mail server … did not agree to encrypt')); - expect(h.sent).toContainEqual(['imap:security-error', 'The incoming mail server … did not agree to encrypt']); + h.listeners.get('security-error')!(Object.assign(new Error('The incoming mail server … did not agree to encrypt'), { code: 'STARTTLS_UNAVAILABLE' })); + expect(h.sent).toContainEqual(['imap:security-error', 'The incoming mail server … did not agree to encrypt', 'STARTTLS_UNAVAILABLE']); + expect(h.clearImapAccount).not.toHaveBeenCalled(); + }); + + // CASA 4.1.2. Breaks: a reconnect refused over a changed certificate reaches + // the window as a STARTTLS problem ("set security to None" — wrong advice), + // or forgets the account as if the password had been rejected. + it('tells the window when a reconnect meets a certificate the account does not trust', async () => { + await connect(NONE_ACCOUNT); + h.listeners.get('security-error')!(Object.assign(new Error('… presented a certificate Sarv Inbox does not trust …'), { code: 'CERTIFICATE_UNTRUSTED' })); + expect(h.sent).toContainEqual(['imap:security-error', '… presented a certificate Sarv Inbox does not trust …', 'CERTIFICATE_UNTRUSTED']); expect(h.clearImapAccount).not.toHaveBeenCalled(); }); }); diff --git a/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts b/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts index 98529cc6..7f0a5104 100644 --- a/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts +++ b/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts @@ -29,6 +29,8 @@ vi.mock('@sarvinbox/core', async () => ({ ...(await import('../../../helpers/core-log-helpers')), // The real transport rules (pure): which relaxations a config asks for and may have. ...(await import('@sarvinbox/core/connection-security')), + // The real certificate rules (pure): which failures are an untrusted certificate, and the pin options. + ...(await import('../../../../../../packages/core/src/utils/tls')), withTimeout: (p: Promise) => p, accountIdFor: (user: string, host?: string) => `acct-${user}-${host ?? ''}`, ImapFlowClient: class { @@ -162,12 +164,19 @@ describe('imap:connect', () => { // relaxations for the password. Breaks: a stale (or forged) "allow // self-signed" / 'none' on the OAuth config sends the vaulted password to a // man-in-the-middle the moment the account heals. + // + // Changed deliberately (certificate pinning, CASA 4.1.2): the dialled config + // used to carry `allowInsecureTLS: false`; the retired switch is now dropped, + // and a pin on the OAuth config is dropped too (only main's store has pins). it('sends the healed password no more loosely than it was saved for', async () => { h.getAccountSecrets.mockResolvedValue({ imap: SAVED_APP_PW }); - await h.handlers.get('imap:connect')!({}, { ...GMAIL, host: 'mail.example.org', port: 143, secure: false, security: 'none', allowInsecureTLS: true }, 'acct-1'); + await h.handlers.get('imap:connect')!({}, { ...GMAIL, host: 'mail.example.org', port: 143, secure: false, security: 'none', allowInsecureTLS: true, certificatePin: { sha256: 'AB', pem: 'FROM-THE-WINDOW' } }, 'acct-1'); expect(h.engine.connect).toHaveBeenCalledWith(expect.objectContaining({ - authMethod: 'password', password: 'app-pw', allowInsecureTLS: false, security: 'starttls', + authMethod: 'password', password: 'app-pw', security: 'starttls', })); + const dialled = (h.engine.connect.mock.calls.at(-1) as unknown[])[0]; + expect(dialled).not.toHaveProperty('allowInsecureTLS'); + expect(dialled).not.toHaveProperty('certificatePin'); }); // The fallback password is bound to its server too. Breaks: a refused token diff --git a/apps/desktop/test/unit/electron/ipc/imap-vault-password.test.ts b/apps/desktop/test/unit/electron/ipc/imap-vault-password.test.ts index c75949eb..01be1e38 100644 --- a/apps/desktop/test/unit/electron/ipc/imap-vault-password.test.ts +++ b/apps/desktop/test/unit/electron/ipc/imap-vault-password.test.ts @@ -44,6 +44,8 @@ vi.mock('@sarvinbox/core', async () => ({ ...(await import('../../../helpers/core-log-helpers')), // The real transport rules (pure): which relaxations a config asks for and may have. ...(await import('@sarvinbox/core/connection-security')), + // The real certificate rules (pure): which failures are an untrusted certificate, and the pin options. + ...(await import('../../../../../../packages/core/src/utils/tls')), withTimeout: (p: Promise) => p, accountIdFor: (user: string, host?: string) => (host ? `acct-${user}--${host}` : `acct-${user}`), ImapFlowClient: class {}, @@ -196,36 +198,48 @@ describe('accounts:backgroundSync (multi-account)', () => { // self-signed" (or picks 'none') for a saved account and main sends the real // password to a man-in-the-middle; a self-signed account stops connecting; or // unticking "allow self-signed" never sticks. +// Changed deliberately (certificate pinning, CASA 4.1.2): this block used to +// exercise the transport binding through "allow self-signed" +// (`allowInsecureTLS`). That switch is retired — certificates are approved per +// server in main (certificate-approval.test.ts) — so the binding is exercised +// through the remaining relaxation, security 'none', with the same intent, and +// the retired switch is checked to relax nothing. +const UNENCRYPTED = { ...SAVED, port: 143, secure: false, security: 'none' }; + describe('imap:connect — the transport saved with the password', () => { const dialled = () => h.engine.connect.mock.calls[0][0]; - it('refuses certificate checks off when the password was not saved that way, non-retryably, and never dials', async () => { + // Breaks: an old config's "allow self-signed" either refuses the saved + // password ("re-enter it") or reaches the dialled config, where anything + // still reading it would relax certificate checks. + it('ignores the retired allowInsecureTLS switch: dials verified, without it', async () => { const res = await h.handlers.get('imap:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a'); + expect(res).not.toMatchObject({ error: expect.stringContaining('Re-enter') }); + expect(dialled()).toMatchObject({ password: 'imap-pw' }); + expect(dialled()).not.toHaveProperty('allowInsecureTLS'); + }); + + it('refuses an unencrypted connection the password was not saved for, non-retryably, and never dials', async () => { + const res = await h.handlers.get('imap:connect')!({}, UNENCRYPTED, 'acct-a'); expect(res).toEqual({ success: false, - error: "Your saved mailbox password was saved for a connection that checks imap.x.com's certificate. Re-enter your password to connect without checking it.", + error: 'Your saved mailbox password was saved for an encrypted connection to imap.x.com. Re-enter your password to connect without encryption.', retryable: false, }); expect(h.engine.connect).not.toHaveBeenCalled(); }); - it('refuses an unencrypted connection the password was not saved for', async () => { - const res = await h.handlers.get('imap:connect')!({}, { ...SAVED, port: 143, secure: false, security: 'none' }, 'acct-a'); - expect(res).toMatchObject({ success: false, retryable: false, error: expect.stringContaining('without encryption') }); - expect(h.engine.connect).not.toHaveBeenCalled(); - }); - it('dials with the relaxation the password was saved with', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowInsecureTLS: true } }); - await h.handlers.get('imap:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a'); - expect(dialled()).toMatchObject({ password: 'imap-pw', allowInsecureTLS: true }); + await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowPlaintext: true } }); + await h.handlers.get('imap:connect')!({}, UNENCRYPTED, 'acct-a'); + expect(dialled()).toMatchObject({ password: 'imap-pw', security: 'none' }); }); it('switches an unused relaxation off for good once the stricter connection works', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowInsecureTLS: true } }); + await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowPlaintext: true } }); await h.handlers.get('imap:connect')!({}, SAVED, 'acct-a'); - expect(dialled()).toMatchObject({ password: 'imap-pw', allowInsecureTLS: false }); - expect((await getAccountSecrets('acct-a'))?.imap?.allowInsecureTLS).toBe(false); + expect(dialled()).toMatchObject({ password: 'imap-pw' }); + expect((await getAccountSecrets('acct-a'))?.imap?.allowPlaintext).toBe(false); }); // connect() returns without dialling when another connect is already in @@ -233,23 +247,23 @@ describe('imap:connect — the transport saved with the password', () => { // stricter config that was never dialled drops the saved choice, and the // account is refused "re-enter your password" though nothing stricter worked. it('keeps the relaxation when the connect did not dial this config', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowInsecureTLS: true } }); + await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowPlaintext: true } }); h.engine.isConnectedWith.mockReturnValue(false); await h.handlers.get('imap:connect')!({}, SAVED, 'acct-a'); expect(h.engine.connect).toHaveBeenCalled(); - expect((await getAccountSecrets('acct-a'))?.imap?.allowInsecureTLS).toBe(true); + expect((await getAccountSecrets('acct-a'))?.imap?.allowPlaintext).toBe(true); await h.handlers.get('accounts:backgroundSync')!({}, { accountId: 'acct-a', config: SAVED }); - expect((await getAccountSecrets('acct-a'))?.imap?.allowInsecureTLS).toBe(true); + expect((await getAccountSecrets('acct-a'))?.imap?.allowPlaintext).toBe(true); }); - // Breaks: one connect from a config that forgot the opt-in costs a - // self-signed account its saved choice. + // Breaks: one connect from a config that forgot the choice costs an + // unencrypted account its saved choice. it('keeps the relaxation when the stricter connection fails', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowInsecureTLS: true } }); - h.engine.connect.mockRejectedValue(new Error('self-signed certificate in certificate chain')); + await setAccountSecrets('acct-a', { imap: { password: 'imap-pw', host: 'imap.x.com', allowPlaintext: true } }); + h.engine.connect.mockRejectedValue(new Error('read ECONNRESET')); await h.handlers.get('imap:connect')!({}, SAVED, 'acct-a'); - expect((await getAccountSecrets('acct-a'))?.imap?.allowInsecureTLS).toBe(true); + expect((await getAccountSecrets('acct-a'))?.imap?.allowPlaintext).toBe(true); }); // A password saved by an older build records no transport. With no record @@ -260,23 +274,24 @@ describe('imap:connect — the transport saved with the password', () => { it('binds a legacy entry with no registry record strict, refusing a looser connect', async () => { captureRegistryForLegacyBinding(); dbState.blobs.set('secure-credentials', Buffer.from(`PLAIN1:${JSON.stringify({ 'acct-a': { imap: { password: 'imap-pw', host: 'imap.x.com' } } })}`)); - const res = await h.handlers.get('imap:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a'); + const res = await h.handlers.get('imap:connect')!({}, UNENCRYPTED, 'acct-a'); expect(res).toMatchObject({ success: false, error: expect.stringContaining('Re-enter your password') }); expect(h.engine.connect).not.toHaveBeenCalled(); - expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'imap-pw', host: 'imap.x.com', allowInsecureTLS: false, allowPlaintext: false }); + expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'imap-pw', host: 'imap.x.com', allowPlaintext: false }); }); // Typing the password IS the choice; the window already holds that secret. - it('dials a typed password however the config asks', async () => { - await h.handlers.get('imap:connect')!({}, { ...SAVED, password: 'typed', allowInsecureTLS: true, security: 'none' }, 'acct-a'); - expect(dialled()).toMatchObject({ password: 'typed', allowInsecureTLS: true, security: 'none' }); + // The retired switch still relaxes nothing (CASA 4.1.2). + it('dials a typed password however the config asks, without the retired switch', async () => { + await h.handlers.get('imap:connect')!({}, { ...UNENCRYPTED, password: 'typed', allowInsecureTLS: true }, 'acct-a'); + expect(dialled()).toMatchObject({ password: 'typed', security: 'none' }); }); }); describe('accounts:backgroundSync — the transport saved with the password', () => { // Breaks: the background path becomes the unguarded route to a loosened connection. it('refuses a relaxation the password was not saved with, non-retryably, and never dials', async () => { - const res = await h.handlers.get('accounts:backgroundSync')!({}, { accountId: 'acct-a', config: { ...SAVED, allowInsecureTLS: true } }); + const res = await h.handlers.get('accounts:backgroundSync')!({}, { accountId: 'acct-a', config: UNENCRYPTED }); expect(res).toMatchObject({ success: false, retryable: false, error: expect.stringContaining('Re-enter your password') }); expect(h.engine.connect).not.toHaveBeenCalled(); }); diff --git a/apps/desktop/test/unit/electron/ipc/reset-and-reconnect.test.ts b/apps/desktop/test/unit/electron/ipc/reset-and-reconnect.test.ts index 00819f6c..130a0542 100644 --- a/apps/desktop/test/unit/electron/ipc/reset-and-reconnect.test.ts +++ b/apps/desktop/test/unit/electron/ipc/reset-and-reconnect.test.ts @@ -42,6 +42,8 @@ vi.mock('electron', () => ({ vi.mock('@sarvinbox/core', async () => ({ // The real transport rules (pure): which relaxations a config asks for and may have. ...(await import('@sarvinbox/core/connection-security')), + // The real certificate rules (pure): which failures are an untrusted certificate, and the pin options. + ...(await import('../../../../../../packages/core/src/utils/tls')), withTimeout: (p: Promise) => p, accountIdFor: (user: string, host: string) => `acct-${user}-${host}`, ImapFlowClient: class {}, diff --git a/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts b/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts index 6553aa25..c606bb75 100644 --- a/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts +++ b/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts @@ -153,25 +153,40 @@ describe('smtp:connectFor (multi-account send-as)', () => { // How the saved password is sent is the user's choice saved WITH it, not the // config's: the config comes from the window, which also renders untrusted -// email. What breaks if these fail: a compromised window ticks "allow -// self-signed" (or picks 'none') for a saved account and main sends the real -// password to a man-in-the-middle; or a legitimately self-signed account stops -// sending; or unticking "allow self-signed" never sticks. +// email. What breaks if these fail: a compromised window picks 'none' for a +// saved account and main sends the real password in cleartext; or a +// legitimately unencrypted account stops sending; or switching back to +// encryption never sticks. +// +// Changed deliberately (certificate pinning, CASA 4.1.2): these used to +// exercise the binding through "allow self-signed" (`allowInsecureTLS`), and +// pinned that a password saved with it was sent WITHOUT certificate checks. +// The switch is retired: nothing is ever sent unverified. The binding is now +// exercised through security 'none', and the retired switch is checked to +// relax nothing. +const UNENCRYPTED = { ...SAVED, port: 587, secure: false, security: 'none' }; + describe('smtp:connect — the transport saved with the password', () => { - /** Whether the client was asked to check the certificate. */ - const verifies = () => resolveTlsOptions(h.connect.mock.calls[0][0] as never).rejectUnauthorized; + /** What the client was asked to check the certificate with. */ + const tls = () => resolveTlsOptions(h.connect.mock.calls[0][0] as never); - it('refuses to send it without certificate checks it was not saved with, and never dials', async () => { - const res = await h.handlers.get('smtp:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a'); - expect(res).toEqual({ - success: false, - error: "Your saved sending password was saved for a connection that checks smtp.x.com's certificate. Re-enter your password to connect without checking it.", - }); - expect(h.connect).not.toHaveBeenCalled(); + // Breaks: an old config's switch refuses the saved password or relaxes checks. + it('ignores the retired allowInsecureTLS switch: sends it verified', async () => { + expect(await h.handlers.get('smtp:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a')).toEqual({ success: true }); + expect(h.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'smtp-pw' })); + expect(tls()).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); + }); + + // Breaks: a password saved with the retired switch, by an older build, is + // still sent without certificate checks. + it('sends a password saved with the retired switch verified', async () => { + dbState.blobs.set('secure-credentials', Buffer.from(`PLAIN1:${JSON.stringify({ 'acct-a': { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: true, allowPlaintext: false } } })}`)); + expect(await h.handlers.get('smtp:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a')).toEqual({ success: true }); + expect(tls().rejectUnauthorized).toBe(true); }); it('refuses to send it unencrypted when it was not saved for that, and never dials', async () => { - const res = await h.handlers.get('smtp:connect')!({}, { ...SAVED, port: 587, secure: false, security: 'none' }, 'acct-a'); + const res = await h.handlers.get('smtp:connect')!({}, UNENCRYPTED, 'acct-a'); expect(res.error).toBe('Your saved sending password was saved for an encrypted connection to smtp.x.com. Re-enter your password to connect without encryption.'); expect(h.connect).not.toHaveBeenCalled(); }); @@ -179,14 +194,13 @@ describe('smtp:connect — the transport saved with the password', () => { // The old override is not a way round it either. it('checks the certificate whatever tlsOptions the config carries', async () => { await h.handlers.get('smtp:connect')!({}, { ...SAVED, tlsOptions: { rejectUnauthorized: false } }, 'acct-a'); - expect(verifies()).toBe(true); + expect(tls().rejectUnauthorized).toBe(true); }); - it('sends it without certificate checks when it was saved that way', async () => { - await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: true } }); - expect(await h.handlers.get('smtp:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a')).toEqual({ success: true }); - expect(h.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'smtp-pw' })); - expect(verifies()).toBe(false); + it('sends it unencrypted when it was saved that way', async () => { + await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowPlaintext: true } }); + expect(await h.handlers.get('smtp:connect')!({}, UNENCRYPTED, 'acct-a')).toEqual({ success: true }); + expect(h.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'smtp-pw', security: 'none' })); }); // A password saved by an older build records no transport. With no record @@ -197,46 +211,47 @@ describe('smtp:connect — the transport saved with the password', () => { it('binds a legacy entry with no registry record strict, refusing a looser connect', async () => { captureRegistryForLegacyBinding(); dbState.blobs.set('secure-credentials', Buffer.from(`PLAIN1:${JSON.stringify({ 'acct-a': { smtp: { password: 'smtp-pw', host: 'smtp.x.com' } } })}`)); - const res = await h.handlers.get('smtp:connect')!({}, { ...SAVED, allowInsecureTLS: true }, 'acct-a'); + const res = await h.handlers.get('smtp:connect')!({}, UNENCRYPTED, 'acct-a'); expect(res).toMatchObject({ success: false, error: expect.stringContaining('Re-enter your password') }); expect(h.connect).not.toHaveBeenCalled(); - expect((await getAccountSecrets('acct-a'))?.smtp).toEqual({ password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: false, allowPlaintext: false }); + expect((await getAccountSecrets('acct-a'))?.smtp).toEqual({ password: 'smtp-pw', host: 'smtp.x.com', allowPlaintext: false }); }); - // Typing the password IS the choice: the window already holds that secret. - it('lets a typed password be sent however the config asks', async () => { - await h.handlers.get('smtp:connect')!({}, { ...SAVED, password: 'typed', allowInsecureTLS: true }, 'acct-a'); - expect(verifies()).toBe(false); + // Typing the password IS the choice: the window already holds that secret — + // but it still never turns certificate checks off. + it('lets a typed password be sent however the config asks, always verified', async () => { + await h.handlers.get('smtp:connect')!({}, { ...UNENCRYPTED, password: 'typed', allowInsecureTLS: true }, 'acct-a'); + expect(h.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'typed', security: 'none' })); + expect(tls().rejectUnauthorized).toBe(true); }); - it('switches the relaxation off for good once a verified connection works', async () => { - await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: true } }); + it('switches the relaxation off for good once a stricter connection works', async () => { + await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowPlaintext: true } }); expect(await h.handlers.get('smtp:connect')!({}, SAVED, 'acct-a')).toEqual({ success: true }); - expect(verifies()).toBe(true); - expect((await getAccountSecrets('acct-a'))?.smtp?.allowInsecureTLS).toBe(false); + expect((await getAccountSecrets('acct-a'))?.smtp?.allowPlaintext).toBe(false); }); // A failed strict connect proves nothing. Breaks: one connect from a config - // that forgot the opt-in costs a self-signed account its saved choice. + // that forgot the choice costs an unencrypted account its saved choice. it('keeps the relaxation when the stricter connection fails', async () => { - await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: true } }); - h.connect.mockRejectedValue(new Error('self-signed certificate')); + await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowPlaintext: true } }); + h.connect.mockRejectedValue(new Error('read ECONNRESET')); expect((await h.handlers.get('smtp:connect')!({}, SAVED, 'acct-a')).success).toBe(false); - expect((await getAccountSecrets('acct-a'))?.smtp?.allowInsecureTLS).toBe(true); + expect((await getAccountSecrets('acct-a'))?.smtp?.allowPlaintext).toBe(true); }); }); describe('smtp:connectFor — the transport saved with the password', () => { // Breaks: send-as becomes the unguarded route to a loosened connection. it('refuses a relaxation the password was not saved with, and never dials', async () => { - const res = await h.handlers.get('smtp:connectFor')!({}, 'acct-a', { ...SAVED, allowInsecureTLS: true }); + const res = await h.handlers.get('smtp:connectFor')!({}, 'acct-a', UNENCRYPTED); expect(res).toMatchObject({ success: false, error: expect.stringContaining('Re-enter your password') }); expect(h.connect).not.toHaveBeenCalled(); }); it('switches an unused relaxation off once the connection works', async () => { - await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowInsecureTLS: true } }); + await setAccountSecrets('acct-a', { smtp: { password: 'smtp-pw', host: 'smtp.x.com', allowPlaintext: true } }); expect(await h.handlers.get('smtp:connectFor')!({}, 'acct-a', SAVED)).toEqual({ success: true }); - expect((await getAccountSecrets('acct-a'))?.smtp?.allowInsecureTLS).toBe(false); + expect((await getAccountSecrets('acct-a'))?.smtp?.allowPlaintext).toBe(false); }); }); diff --git a/apps/desktop/test/unit/electron/services/assistant-mailbox-download.test.ts b/apps/desktop/test/unit/electron/services/assistant-mailbox-download.test.ts index 14d19f9a..3464aea4 100644 --- a/apps/desktop/test/unit/electron/services/assistant-mailbox-download.test.ts +++ b/apps/desktop/test/unit/electron/services/assistant-mailbox-download.test.ts @@ -61,14 +61,19 @@ beforeEach(() => { }); describe('automatic account-safe assistant downloads', () => { + // Changed deliberately (certificate pinning, CASA 4.1.2): the dialled config + // used to carry `allowInsecureTLS: false`; the retired switch is now absent, + // and so is any pin when the account approved none. it('connects a fresh non-active account with its own vault credentials and preserves TLS validation', async () => { await ensureAssistantMailboxConnection('work'); expect(state.engine.connect).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ host: 'imap.example.test', username: 'rc@example.test', password: 'synthetic-secret', - allowInsecureTLS: false, })); - expect(transportOptInsOf(state.engine.connect.mock.calls[0][0])).toEqual({ allowInsecureTLS: false, allowPlaintext: false }); - expect(state.engine.connect.mock.calls[0][0]).not.toHaveProperty('tlsOptions'); + const dialled = state.engine.connect.mock.calls[0][0]; + expect(transportOptInsOf(dialled)).toEqual({ allowPlaintext: false }); + expect(dialled).not.toHaveProperty('tlsOptions'); + expect(dialled).not.toHaveProperty('allowInsecureTLS'); + expect(dialled).not.toHaveProperty('certificatePin'); expect(state.engine.ensureConnection).not.toHaveBeenCalled(); }); @@ -124,8 +129,10 @@ describe('automatic account-safe assistant downloads', () => { expect(state.engine.connect).not.toHaveBeenCalled(); }); + // Changed deliberately (certificate pinning, CASA 4.1.2): the "without + // checking" row (allowInsecureTLS) is gone — the switch is retired and + // relaxes nothing, so it is not refused either (next test). it.each([ - { allowInsecureTLS: true, message: 'without checking' }, { security: 'none', secure: false, port: 143, message: 'without encryption' }, ])('refuses to send a saved password over a newly relaxed transport ($message)', async ({ message, ...patch }) => { state.account.imapConfig = { ...state.account.imapConfig, ...patch }; @@ -133,24 +140,38 @@ describe('automatic account-safe assistant downloads', () => { expect(state.engine.connect).not.toHaveBeenCalled(); }); - it('preserves an explicitly saved self-signed opt-in while applying the bound password', async () => { + // Replaces 'preserves an explicitly saved self-signed opt-in' (certificate + // pinning): a registry config or saved password carrying the retired switch + // connects verified, without it. Breaks: an agent download becomes the one + // path that still dials an old self-signed account without checks. + it('ignores the retired self-signed switch on the registry config and the saved password', async () => { state.account.imapConfig = { ...state.account.imapConfig, allowInsecureTLS: true }; state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowInsecureTLS: true, allowPlaintext: false } }); await ensureAssistantMailboxConnection('work'); - expect(state.engine.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'synthetic-secret', allowInsecureTLS: true })); - expect(transportOptInsOf(state.engine.connect.mock.calls[0][0])).toEqual({ allowInsecureTLS: true, allowPlaintext: false }); + expect(state.engine.connect).toHaveBeenCalledWith(expect.objectContaining({ password: 'synthetic-secret' })); + expect(state.engine.connect.mock.calls[0][0]).not.toHaveProperty('allowInsecureTLS'); expect(state.narrowTransport).not.toHaveBeenCalled(); }); + // CASA 4.1.2. Breaks: an agent download dials an approved self-signed server + // without its pin (fails), or with a pin a registry write supplied. + it('dials with the certificate approved for this server, never one from the registry config', async () => { + const approved = { host: 'imap.example.test', port: 993, sha256: Array(32).fill('AB').join(':'), pem: 'APPROVED-PEM', approvedAt: 1, subject: 's', issuer: 'i', validFrom: 'f', validTo: 't' }; + state.account.imapConfig = { ...state.account.imapConfig, certificatePin: { sha256: 'CD', pem: 'REGISTRY-PEM' } }; + state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowPlaintext: false }, certificates: { imap: approved } }); + await ensureAssistantMailboxConnection('work'); + expect(state.engine.connect.mock.calls[0][0].certificatePin).toEqual({ sha256: approved.sha256, pem: 'APPROVED-PEM' }); + }); + it('narrows unused saved transport relaxations only after this exact configuration connected', async () => { - state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowInsecureTLS: true, allowPlaintext: true } }); + state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowPlaintext: true } }); await ensureAssistantMailboxConnection('work'); - expect(state.narrowTransport).toHaveBeenCalledExactlyOnceWith('work', 'imap', 'synthetic-secret', ['allowInsecureTLS', 'allowPlaintext']); + expect(state.narrowTransport).toHaveBeenCalledExactlyOnceWith('work', 'imap', 'synthetic-secret', ['allowPlaintext']); expect(state.engine.isConnectedWith).toHaveBeenCalledWith(state.engine.connect.mock.calls[0][0]); }); it('does not narrow transport for a concurrent connection that used another configuration', async () => { - state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowInsecureTLS: true, allowPlaintext: true } }); + state.secrets.mockResolvedValue({ imap: { password: 'synthetic-secret', host: 'imap.example.test', allowPlaintext: true } }); state.engine.isConnectedWith.mockReturnValue(false); await ensureAssistantMailboxConnection('work'); expect(state.narrowTransport).not.toHaveBeenCalled(); diff --git a/apps/desktop/test/unit/electron/services/certificate-trust.test.ts b/apps/desktop/test/unit/electron/services/certificate-trust.test.ts new file mode 100644 index 00000000..3651bdd8 --- /dev/null +++ b/apps/desktop/test/unit/electron/services/certificate-trust.test.ts @@ -0,0 +1,547 @@ +import { getLogLevel, setLogLevel, setLogSink, type CertificateInspection, type PresentedCertificate } from '@sarvinbox/core'; +import type { MessageBoxOptions } from 'electron'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * CASA 4.1.2 in main: which certificate a password account's server may + * present, who decides, and WHEN the question may be asked. What breaks if this + * file fails: + * - the trust question pops up for a connect the user did not start (a + * focus/online reconnect on café Wi-Fi), so one click pins an attacker's + * certificate and the retry sends the password; + * - the window can raise the dialog over and over, or arm it for another + * account or transport; + * - after the user switched accounts during the dialog, the retry connects + * one account's credentials on the other's connection; + * - the dialog's account name or "set to accept any certificate" wording comes + * from the window's config instead of main's records; + * - a new certificate silently replaces one already trusted for that transport; + * - an approval the vault could not write is reported as trusted; + * - a pin the window put on a config is dialled, or a pin applies to another + * account, transport, host or port; an unreadable vault reads as "trusted"; + * - an expired certificate can be approved; + * - the password, a fingerprint or a host reaches app.log. + * + * The vault is REAL (over the fake core DB, whose `setBlob` here swallows a + * failed write exactly as the real one does); the registry, the network + * inspection, the dialog and the clock are stubbed. + */ + +const h = vi.hoisted(() => ({ + registry: [] as Array<{ id: string; email: string }>, + registryThrows: false, +})); + +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/sarvinbox-cert-trust-test', getName: () => 'Sarv Inbox Test', isPackaged: false }, + safeStorage: { + isEncryptionAvailable: () => true, + getSelectedStorageBackend: () => 'gnome_libsecret', + encryptString: (s: string) => Buffer.from(`${process.platform === 'linux' ? 'v11' : ''}enc(${s})`, 'utf8'), + decryptString: (b: Buffer) => /^(?:v11)?enc\((.*)\)$/s.exec(b.toString('utf8'))![1], + }, + BrowserWindow: { fromWebContents: (sender: unknown) => ({ sender, isDestroyed: () => false }) }, + dialog: {}, +})); +vi.mock('../../../../electron/services/core-db', async () => { + const fake = await import('../../../../electron/services/__testing__/fake-core-db'); + // The real setBlob logs a failed write and returns; only writeBlob throws. + return { ...fake, setBlob: (key: string, data: Buffer) => { try { fake.setBlob(key, data); } catch { /* swallowed, like core-db */ } } }; +}); +vi.mock('../../../../electron/services/accounts-registry', () => ({ + readRegistryAccounts: () => { + if (h.registryThrows) throw new Error('registry unreadable'); + return h.registry; + }, +})); + +import { captureLogs, type CapturedLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { resetFakeCoreDb, state as dbState } from '../../../../electron/services/__testing__/fake-core-db'; +import { + ACCOUNT_CHANGED_DURING_REVIEW, + applyCertificatePin, + armCertificateReview, + certificateDeclinedMessage, + findCertificatePin, + listAccountCertificates, + removeAccountCertificate, + requestCertificateTrust, + requestingWindow, + resetCertificateTrustForTest, + REVIEW_ARM_INTERVAL_MS, + REVIEW_ARM_TTL_MS, + REVIEW_ARMS_PER_MINUTE, + setCertificateTrustDepsForTest, + takeCertificateReview, + trustDialogOptions, + withCertificateApproval, + type CertificateTrustRequest, +} from '../../../../electron/services/certificate-trust'; +import { getAccountSecrets, setAccountCertificatePin, setAccountSecrets } from '../../../../electron/services/secure-credential-store'; + +const FP = Array.from({ length: 32 }, (_, i) => (i + 16).toString(16).toUpperCase().padStart(2, '0')).join(':'); +const OTHER_FP = FP.replace(/^10/, 'EE'); +const START = Date.parse('2026-11-28T12:00:00Z'); +const PASSWORD = 'sentinel-password-7d1c'; + +const leaf = (over: Partial = {}): PresentedCertificate => ({ + pem: '-----BEGIN CERTIFICATE-----\nLEAF\n-----END CERTIFICATE-----\n', + sha256: FP, + subject: 'CN=imap.office.lan\nO=Office', + issuer: 'CN=imap.office.lan\nO=Office', + validFrom: 'Nov 1 00:00:00 2026 GMT', + validTo: 'Nov 1 00:00:00 2027 GMT', + notBefore: Date.parse('2026-11-01T00:00:00Z'), + notAfter: Date.parse('2027-11-01T00:00:00Z'), + ...over, +}); +const inspection = (over: Partial = {}): CertificateInspection => ({ leaf: leaf(), systemTrusted: false, systemError: 'DEPTH_ZERO_SELF_SIGNED_CERT', ...over }); +const PIN = (over: Record = {}) => ({ + host: 'imap.office.lan', port: 993, sha256: FP, pem: leaf().pem, approvedAt: 1, + subject: 'CN=imap.office.lan', issuer: 'CN=imap.office.lan', validFrom: 'a', validTo: 'b', ...over, +}); + +const request = (over: Partial = {}): CertificateTrustRequest => ({ + kind: 'imap', ids: ['acct-a'], host: 'imap.office.lan', port: 993, security: 'ssl', window: null, ...over, +}); +const REFUSED = { success: false, error: 'not trusted', code: 'CERTIFICATE_UNTRUSTED', retryable: false }; + +let now = START; +const inspect = vi.fn(async (_target: unknown) => inspection()); +const showMessageBox = vi.fn(async (_window: unknown, _options: MessageBoxOptions) => ({ response: 0 })); +const shown = (call = 0) => showMessageBox.mock.calls[call][1] as MessageBoxOptions & { detail: string; message: string; buttons: string[] }; +let restore: () => void; +let logs: CapturedLogs; + +beforeEach(() => { + now = START; + h.registry = []; + h.registryThrows = false; + resetFakeCoreDb(); + resetCertificateTrustForTest(); + inspect.mockReset().mockImplementation(async () => inspection()); + showMessageBox.mockReset().mockResolvedValue({ response: 0 }); + restore = setCertificateTrustDepsForTest({ inspect, showMessageBox, now: () => now }); + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(() => { + logs.stop(); + restore(); +}); + +/** The user pressed Reconnect for acct-a (IMAP), and that connect was refused over the certificate. */ +async function armedRefusedConnect(over: Partial = {}, then: object = { success: true }) { + const req = request(over); + expect(armCertificateReview(req.ids[0], req.kind)).toBe('armed'); + now += REVIEW_ARM_INTERVAL_MS; // so a test can arm the same pair again + const attempt = vi.fn().mockResolvedValueOnce(REFUSED).mockResolvedValue(then); + return { result: await withCertificateApproval(attempt, () => req), attempt }; +} + +describe('when the question may be asked (armed connects only)', () => { + // THE finding of the review. Breaks: a focus/online reconnect, a background + // sync or the pool meeting an attacker's certificate pops up "Trust …?" + // unprompted; one click pins it and the retry sends the password. + it('never asks for a connect nobody armed: the refusal comes back at once, unfetched', async () => { + const attempt = vi.fn().mockResolvedValue(REFUSED); + await expect(withCertificateApproval(attempt, () => request())).resolves.toEqual(REFUSED); + expect(attempt).toHaveBeenCalledOnce(); + expect(inspect).not.toHaveBeenCalled(); + expect(showMessageBox).not.toHaveBeenCalled(); + }); + + // Breaks: a self-signed server can never be approved, or approving does not reconnect. + it('asks for an armed connect, stores the pin on Trust and dials once more', async () => { + const { result, attempt } = await armedRefusedConnect(); + expect(result).toEqual({ success: true }); + expect(attempt).toHaveBeenCalledTimes(2); + expect(showMessageBox).toHaveBeenCalledOnce(); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toMatchObject({ host: 'imap.office.lan', port: 993, sha256: FP }); + }); + + // Breaks: an arm survives its connect, so the NEXT automatic reconnect + // (minutes later, on another network) still asks. + it('uses the arm up on the next connect, whatever its outcome', async () => { + armCertificateReview('acct-a', 'imap'); + await withCertificateApproval(async () => ({ success: true }), () => request()); + await expect(withCertificateApproval(async () => REFUSED, () => request())).resolves.toEqual(REFUSED); + expect(showMessageBox).not.toHaveBeenCalled(); + }); + + // Breaks: arming one account (or transport) lets another one's automatic + // connect ask. + it('is bound to the account and transport it was armed for', async () => { + armCertificateReview('acct-a', 'smtp'); + armCertificateReview('acct-b', 'imap'); + await expect(withCertificateApproval(async () => REFUSED, () => request())).resolves.toEqual(REFUSED); + expect(showMessageBox).not.toHaveBeenCalled(); + expect(takeCertificateReview('acct-a', 'smtp')).toBe(true); + expect(takeCertificateReview('acct-b', 'imap')).toBe(true); + expect(takeCertificateReview(undefined, 'imap')).toBe(false); + }); + + // Breaks: an arm left behind (the connect never came) makes an automatic + // connect much later ask. + it('lapses after a minute', () => { + armCertificateReview('acct-a', 'imap'); + now += REVIEW_ARM_TTL_MS + 1; + expect(takeCertificateReview('acct-a', 'imap')).toBe(false); + }); + + // Breaks: a compromised window raises the modal dialog over and over (arm, + // connect, repeat), or fans out over fabricated account ids. + it('is rate-limited per account+transport and overall', () => { + expect(armCertificateReview('acct-a', 'imap')).toBe('armed'); + expect(armCertificateReview('acct-a', 'imap')).toBe('too-soon'); + now += REVIEW_ARM_INTERVAL_MS - 1; + expect(armCertificateReview('acct-a', 'imap')).toBe('too-soon'); + expect(armCertificateReview('acct-a', 'smtp')).toBe('armed'); + now += 1; + expect(armCertificateReview('acct-a', 'imap')).toBe('armed'); + resetCertificateTrustForTest(); + for (let i = 0; i < REVIEW_ARMS_PER_MINUTE; i++) expect(armCertificateReview(`acct-${i}`, 'imap')).toBe('armed'); + expect(armCertificateReview('acct-fresh', 'imap')).toBe('too-soon'); + now += 60_001; + expect(armCertificateReview('acct-fresh', 'imap')).toBe('armed'); + }); + + // Breaks: Cancel connects anyway, or reads as a retryable blip. + it('returns the settled refusal on Cancel, without dialling again', async () => { + showMessageBox.mockResolvedValueOnce({ response: 1 }); + const { result, attempt } = await armedRefusedConnect(); + expect(result).toEqual({ success: false, error: certificateDeclinedMessage('imap.office.lan', 993), retryable: false, code: 'CERTIFICATE_UNTRUSTED' }); + expect(certificateDeclinedMessage('imap.office.lan', 993)).toContain('Settings → Accounts'); + expect(attempt).toHaveBeenCalledOnce(); + expect((await getAccountSecrets('acct-a'))?.certificates).toBeUndefined(); + }); + + // Breaks: the user switches accounts while the dialog is open, and the retry + // connects account A's credentials on account B's engine or SMTP client. + it('does not retry when the account on screen changed during the question', async () => { + let onScreen = 'acct-a'; + showMessageBox.mockImplementationOnce(async () => { onScreen = 'acct-b'; return { response: 0 }; }); + armCertificateReview('acct-a', 'imap'); + const attempt = vi.fn().mockResolvedValueOnce(REFUSED).mockResolvedValue({ success: true }); + const result = await withCertificateApproval(attempt, () => request(), { sameTarget: () => onScreen }); + expect(result).toEqual({ success: false, error: ACCOUNT_CHANGED_DURING_REVIEW, retryable: true, code: 'CERTIFICATE_UNTRUSTED' }); + expect(attempt).toHaveBeenCalledOnce(); + // The approval itself was the user's and stands; the next reconnect uses it. + expect((await getAccountSecrets('acct-a'))?.certificates?.imap?.sha256).toBe(FP); + }); + + // Breaks: a second refusal (the certificate changed between question and + // retry) opens a second dialog; OAuth or other failures open one at all. + it('asks at most once per connect, and never for OAuth or other failures', async () => { + armCertificateReview('acct-a', 'imap'); + const again = vi.fn().mockResolvedValue(REFUSED); + await expect(withCertificateApproval(again, () => request())).resolves.toEqual(REFUSED); + expect(again).toHaveBeenCalledTimes(2); + expect(showMessageBox).toHaveBeenCalledOnce(); + now += REVIEW_ARM_INTERVAL_MS; + armCertificateReview('acct-a', 'imap'); + await expect(withCertificateApproval(async () => REFUSED, () => null)).resolves.toEqual(REFUSED); + await expect(withCertificateApproval(async () => ({ success: false, error: 'x', code: 'STARTTLS_UNAVAILABLE' }), () => request())).resolves.toMatchObject({ code: 'STARTTLS_UNAVAILABLE' }); + expect(showMessageBox).toHaveBeenCalledOnce(); + }); +}); + +describe('requestCertificateTrust — the question, asked in main', () => { + // Breaks: approving stores something other than what the user saw, or binds + // it to the wrong server — the core of "trust this specific certificate". + it('shows the presented certificate and, on Trust, stores exactly it for this account, transport, host and port', async () => { + await expect(requestCertificateTrust(request())).resolves.toEqual({ outcome: 'retry' }); + expect(inspect).toHaveBeenCalledWith({ host: 'imap.office.lan', port: 993, security: 'ssl', protocol: 'imap' }); + expect(shown().buttons).toEqual(['Trust this certificate', 'Cancel']); + expect(shown().defaultId).toBe(1); + expect(shown().cancelId).toBe(1); + for (const text of ['imap.office.lan:993', 'Issued to: CN=imap.office.lan, O=Office', 'Issued by: CN=imap.office.lan, O=Office', 'Valid from: Nov 1 00:00:00 2026 GMT', 'Valid until: Nov 1 00:00:00 2027 GMT', FP]) { + expect(shown().detail).toContain(text); + } + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toEqual({ + host: 'imap.office.lan', port: 993, sha256: FP, pem: leaf().pem, approvedAt: START, + subject: leaf().subject, issuer: leaf().issuer, validFrom: leaf().validFrom, validTo: leaf().validTo, + }); + }); + + // Breaks: the dialog names an account the window chose (a compromised + // window labelling an attacker's server as the user's bank mail). + it('names the account from main\'s registry only, and no account when it has none', async () => { + h.registry = [{ id: 'acct-a', email: 'me@office.lan' }]; + await requestCertificateTrust(request()); + expect(shown(0).detail).toContain('Account: me@office.lan'); + h.registry = []; + await requestCertificateTrust(request({ ids: ['acct-new'] })); + expect(shown(1).detail).not.toContain('Account:'); + h.registryThrows = true; + await requestCertificateTrust(request({ ids: ['acct-x'] })); + expect(shown(2).detail).not.toContain('Account:'); + }); + + // Breaks: the dialog is not modal to the window that asked (it can hide + // behind it), or an IPC event without a window breaks the flow. + it('parents the dialog on the requesting window when there is one', async () => { + const window = requestingWindow({ sender: 'web-contents' }); + await requestCertificateTrust(request({ window })); + expect(showMessageBox.mock.calls[0][0]).toBe(window); + expect(requestingWindow({})).toBeNull(); + expect(requestingWindow(undefined)).toBeNull(); + }); + + // Breaks: two armed connects of one server (probe + connect) open two dialogs. + it('asks once for concurrent questions about the same server', async () => { + let answer!: (value: { response: number }) => void; + showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve; })); + const all = Promise.all([requestCertificateTrust(request()), requestCertificateTrust(request())]); + await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledTimes(1)); + answer({ response: 0 }); + expect(await all).toEqual([{ outcome: 'retry' }, { outcome: 'retry' }]); + expect(inspect).toHaveBeenCalledTimes(1); + }); + + // Breaks: an expired (or not yet valid) certificate is offered for approval. + it.each([ + ['expired', leaf({ notAfter: START - 1 }), 'has expired'], + ['not-yet-valid', leaf({ notBefore: START + 1 }), 'is not valid yet'], + ])('cannot approve a certificate that is %s: says so, with no Trust button', async (_label, presented, wording) => { + inspect.mockResolvedValueOnce(inspection({ leaf: presented })); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused', retryable: false, message: expect.stringContaining(wording) }); + expect(shown().buttons).toEqual(['OK']); + expect(shown().type).toBe('error'); + expect((await getAccountSecrets('acct-a'))?.certificates).toBeUndefined(); + }); + + // Breaks: a server that cannot be reached for inspection is either trusted + // or permanently refused, instead of "try again". + it('settles retryably, without a dialog, when the certificate cannot be fetched', async () => { + const { CertificateInspectionError } = await import('@sarvinbox/core'); + inspect.mockRejectedValueOnce(new CertificateInspectionError('slow', 'too-slow')); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused', retryable: true }); + inspect.mockRejectedValueOnce(new Error('boom')); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused', retryable: true }); + expect(showMessageBox).not.toHaveBeenCalled(); + }); + + // THE unreadable-store rule. Breaks: a locked or broken vault reads as "no + // pin yet", the user approves, and the write replaces every other account's + // secrets. + it('approves nothing into a vault that cannot be read', async () => { + await setAccountSecrets('acct-other', { imap: { password: PASSWORD, host: 'imap.other.lan' } }); + dbState.fail.add('blob-read'); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused', retryable: true }); + expect(showMessageBox).not.toHaveBeenCalled(); + dbState.fail.delete('blob-read'); + await expect(getAccountSecrets('acct-other')).resolves.toMatchObject({ imap: { password: PASSWORD } }); + }); + + // Review item 5. Breaks: the vault's ordinary write (setBlob) swallows a + // failed write, so an approval that was never stored is reported as trusted + // and the retry dials without a pin. The pin is written with the throwing + // writeBlob; the control shows an ordinary write would have "succeeded". + it('reports an approval it could not write, retryably, though an ordinary vault write would not notice', async () => { + dbState.failBlobWrite = true; + await expect(setAccountSecrets('acct-a', { imap: { password: PASSWORD, host: 'imap.office.lan' } })).resolves.toBeUndefined(); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused', retryable: true, message: expect.stringContaining('could not save') }); + dbState.failBlobWrite = false; + expect((await getAccountSecrets('acct-a'))?.certificates).toBeUndefined(); + }); + + // Review item 2 (CASA 4.1.2 migration). Breaks: the "was set to accept any + // certificate" wording follows the window's config (absent for a compromised + // window's own server, or forged onto anything) instead of main's vault. + it('tells a migrated "allow self-signed" account why it is asked, from the saved password only', async () => { + const forged = { ...request(), legacyInsecureTLS: true, accountLabel: 'bank@example.com' } as CertificateTrustRequest; + await requestCertificateTrust(forged); + expect(shown(0).detail).not.toContain('accept any certificate'); + expect(shown(0).detail).not.toContain('bank@example.com'); + resetFakeCoreDb(); + dbState.blobs.set('secure-credentials', Buffer.from(`PLAIN1:${JSON.stringify({ 'acct-a': { imap: { password: PASSWORD, host: 'imap.office.lan', allowInsecureTLS: true, allowPlaintext: false } } })}`)); + await requestCertificateTrust(request()); + expect(shown(1).detail).toContain('was set to accept any certificate'); + // Approving retires the switch from the saved password. + expect((await getAccountSecrets('acct-a'))?.imap).not.toHaveProperty('allowInsecureTLS'); + }); + + // Breaks: a changed certificate (renewal, or interception) is presented as a + // first approval, and replaces the pin without warning. + it('warns that the certificate CHANGED for the same server, and replaces the pin only on Trust', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN()); + inspect.mockResolvedValue(inspection({ leaf: leaf({ sha256: OTHER_FP, pem: 'NEW-PEM' }) })); + showMessageBox.mockResolvedValueOnce({ response: 1 }); + await requestCertificateTrust(request()); + expect(shown(0).message).toContain('new certificate'); + expect(shown(0).detail).toContain('CHANGED'); + expect(shown(0).detail).toContain(`Currently trusted (imap.office.lan:993):\n${FP}`); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap?.sha256).toBe(FP); + await requestCertificateTrust(request()); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toMatchObject({ sha256: OTHER_FP, pem: 'NEW-PEM' }); + }); + + // Review item 4. Breaks: a certificate trusted for the account's OLD server + // (or port) is silently replaced by approving one for another server. + it('says which certificate it replaces when the account trusts one for another host or port', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN({ host: 'old.office.lan', port: 143 })); + await requestCertificateTrust(request()); + expect(shown().detail).toContain('already trusts a certificate for old.office.lan:143'); + expect(shown().detail).toContain('REPLACES'); + expect(shown().message).toContain('new certificate'); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toMatchObject({ host: 'imap.office.lan', port: 993 }); + }); + + // Breaks: a pin for the OTHER transport is called a replacement (it is not: + // one pin per transport). + it('does not call a first certificate for a transport a replacement', async () => { + await setAccountCertificatePin('acct-a', 'smtp', PIN({ host: 'smtp.office.lan', port: 465 })); + await requestCertificateTrust(request()); + expect(shown().detail).not.toContain('REPLACES'); + expect(shown().detail).not.toContain('CHANGED'); + }); + + // Breaks: once a server moves to a publicly trusted certificate, the old pin + // blocks it forever (no way back to normal checks), or is dropped silently. + it('offers to stop using the pin when the server now presents a system-trusted certificate', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN()); + inspect.mockResolvedValue(inspection({ leaf: leaf({ sha256: OTHER_FP }), systemTrusted: true, systemError: null })); + showMessageBox.mockResolvedValueOnce({ response: 1 }); + await expect(requestCertificateTrust(request())).resolves.toMatchObject({ outcome: 'refused' }); + expect(shown(0).buttons).toEqual(['Stop using the approved certificate', 'Cancel']); + expect((await getAccountSecrets('acct-a'))?.certificates?.imap).toBeDefined(); + await expect(requestCertificateTrust(request())).resolves.toEqual({ outcome: 'retry' }); + expect((await getAccountSecrets('acct-a'))?.certificates).toBeUndefined(); + }); + + // Breaks: a refusal for a certificate the server no longer presents asks a + // pointless question. + it('retries without asking when the server now presents a system-trusted certificate and there is no pin', async () => { + inspect.mockResolvedValueOnce(inspection({ systemTrusted: true, systemError: null })); + await expect(requestCertificateTrust(request())).resolves.toEqual({ outcome: 'retry' }); + expect(showMessageBox).not.toHaveBeenCalled(); + }); +}); + +describe('applyCertificatePin — what a connection dials with', () => { + const config = { host: 'IMAP.office.lan.', port: 993, username: 'me@office.lan', authMethod: 'password' }; + const approve = () => setAccountCertificatePin('acct-a', 'imap', PIN()); + + // Breaks: an approved server cannot be reached (no pin on the config), or + // matching is case/root-dot sensitive and a pin is silently missed. + it('puts the stored pin on a password config for the same host and port', async () => { + await approve(); + await expect(applyCertificatePin(config, 'imap', ['acct-a'])).resolves.toEqual({ ...config, certificatePin: { sha256: FP, pem: leaf().pem } }); + }); + + // THE boundary. Breaks: a compromised window supplies its own pin with the + // config and main dials the saved password to the attacker's certificate. + it('replaces a pin the config arrived with, by the stored one or by none', async () => { + const forged = { ...config, certificatePin: { sha256: OTHER_FP, pem: 'ATTACKER' } }; + await expect(applyCertificatePin(forged, 'imap', ['acct-a'])).resolves.toEqual(config); + await approve(); + await expect(applyCertificatePin(forged, 'imap', ['acct-a'])).resolves.toEqual({ ...config, certificatePin: { sha256: FP, pem: leaf().pem } }); + }); + + // Breaks: an OAuth connection is narrowed (or redirected) by a pin. + it('never pins OAuth', async () => { + await approve(); + await expect(applyCertificatePin({ ...config, authMethod: 'oauth2', certificatePin: { sha256: FP, pem: 'x' } }, 'imap', ['acct-a'])).resolves.toEqual({ ...config, authMethod: 'oauth2' }); + }); + + // Multi-account (decided: pins are per account + transport + host + port). + it('applies only to the account, transport, host and port it was approved for', async () => { + await approve(); + await expect(applyCertificatePin(config, 'imap', ['acct-b'])).resolves.toEqual(config); + await expect(applyCertificatePin(config, 'smtp', ['acct-a'])).resolves.toEqual(config); + await expect(applyCertificatePin({ ...config, port: 143 }, 'imap', ['acct-a'])).resolves.toEqual({ ...config, port: 143 }); + await expect(applyCertificatePin({ ...config, host: 'mail.office.lan' }, 'imap', ['acct-a'])).resolves.toEqual({ ...config, host: 'mail.office.lan' }); + }); + + // Breaks: a pin stored under a legacy id of the same account is missed. + it('finds a pin under any of the account\'s ids', async () => { + await setAccountCertificatePin('acct-legacy', 'imap', PIN()); + await expect(findCertificatePin(['acct-a', 'acct-legacy'], 'imap', 'imap.office.lan', 993)).resolves.toMatchObject({ sha256: FP }); + }); + + // Breaks: a damaged stored pin is treated as a valid pin. + it('ignores a stored pin that is not a well-formed fingerprint and certificate', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN({ sha256: 'nope' })); + await expect(applyCertificatePin(config, 'imap', ['acct-a'])).resolves.toEqual(config); + }); + + // THE unreadable-store rule. Breaks: an unreadable vault yields "trusted" — + // or a throw that breaks the connect instead of normal verification. + it('dials with no pin (normal verification) when the vault cannot be read', async () => { + await approve(); + dbState.fail.add('blob-read'); + await expect(applyCertificatePin(config, 'imap', ['acct-a'])).resolves.toEqual(config); + await expect(findCertificatePin(['acct-a'], 'imap', 'imap.office.lan', 993)).rejects.toThrow(); + }); + + it('finds nothing for an empty host', async () => { + await expect(findCertificatePin(['acct-a'], 'imap', '', 993)).resolves.toBeNull(); + }); +}); + +describe('the account settings view of approved certificates', () => { + // Breaks: the settings show the wrong certificate, or hand the PEM to the window. + it('lists each transport\'s pin without the certificate itself', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN({ approvedAt: START })); + await expect(listAccountCertificates('acct-a')).resolves.toEqual({ + imap: { host: 'imap.office.lan', port: 993, sha256: FP, approvedAt: START, subject: 'CN=imap.office.lan', issuer: 'CN=imap.office.lan', validTo: 'b' }, + }); + await expect(listAccountCertificates('acct-none')).resolves.toEqual({}); + }); + + // Breaks: Remove leaves the certificate trusted, or the next automatic + // reconnect asks to trust it again. + it('removes a pin; automatic connects then refuse without a question', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN()); + await expect(removeAccountCertificate('acct-a', 'imap')).resolves.toBe(true); + expect((await getAccountSecrets('acct-a'))?.certificates).toBeUndefined(); + await expect(withCertificateApproval(async () => REFUSED, () => request())).resolves.toEqual(REFUSED); + expect(showMessageBox).not.toHaveBeenCalled(); + await expect(removeAccountCertificate('acct-x', 'smtp')).resolves.toBe(false); + }); + + // Breaks: a removal the vault could not write is reported as done. + it('reports a removal it could not write', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN()); + dbState.failBlobWrite = true; + await expect(removeAccountCertificate('acct-a', 'imap')).rejects.toThrow(); + }); +}); + +describe('logging', () => { + // Breaks: the saved password, a fingerprint, the certificate or the server's + // host reaches app.log (which users attach to bug reports) on any path. + it('never logs the password, fingerprint, certificate text or host — on any path', async () => { + h.registry = [{ id: 'acct-a', email: 'me@office.lan' }]; + await setAccountSecrets('acct-a', { imap: { password: PASSWORD, host: 'imap.office.lan' } }); + await armedRefusedConnect(); // approved + await applyCertificatePin({ host: 'imap.office.lan', port: 993, authMethod: 'password', password: PASSWORD } as never, 'imap', ['acct-a']); + inspect.mockResolvedValueOnce(inspection({ leaf: leaf({ sha256: OTHER_FP }) })); + showMessageBox.mockResolvedValueOnce({ response: 1 }); + await armedRefusedConnect(); // declined (changed) + inspect.mockResolvedValueOnce(inspection({ leaf: leaf({ notAfter: START - 1 }) })); + await requestCertificateTrust(request({ port: 995 })); // expired + inspect.mockRejectedValueOnce(new Error(`connect ECONNREFUSED imap.office.lan ${PASSWORD}`)); + await requestCertificateTrust(request({ port: 996 })); // unavailable + armCertificateReview('acct-a', 'imap'); // too soon + dbState.fail.add('blob-read'); + await applyCertificatePin({ host: 'imap.office.lan', port: 993, authMethod: 'password', password: PASSWORD } as never, 'imap', ['acct-a']); + await requestCertificateTrust(request({ port: 997 })); // unreadable + dbState.fail.delete('blob-read'); + await removeAccountCertificate('acct-a', 'imap'); // removed + + expect(logs.lines.length).toBeGreaterThan(4); + for (const secret of [PASSWORD, FP, OTHER_FP, 'LEAF', 'imap.office.lan', 'me@office.lan', 'CN=']) { + expect(logs.containing(secret)).toEqual([]); + } + }); +}); + +describe('trustDialogOptions', () => { + // Breaks: Trust becomes the default button (Enter approves blindly). + it('makes Cancel the default and the escape answer', () => { + const options = trustDialogOptions(request(), leaf(), null); + expect(options.buttons?.[options.defaultId!]).toBe('Cancel'); + expect(options.buttons?.[options.cancelId!]).toBe('Cancel'); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/core-db-write-blob.test.ts b/apps/desktop/test/unit/electron/services/core-db-write-blob.test.ts new file mode 100644 index 00000000..6215702b --- /dev/null +++ b/apps/desktop/test/unit/electron/services/core-db-write-blob.test.ts @@ -0,0 +1,47 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * The core DB's two blob writers, against the REAL addon. What breaks if this + * file fails: a caller that tells the user something was saved — an approved + * mail-server certificate (CASA 4.1.2) — uses a write that swallows failure, + * so "trusted" is reported for a certificate that was never stored; or the + * ordinary write starts throwing where every other store expects it not to. + */ + +const h = vi.hoisted(() => ({ dir: '' })); +vi.mock('electron', () => ({ app: { getPath: () => h.dir } })); +vi.mock('../../../../electron/services/db-key-store', () => ({ getDbEncryptionKey: () => null })); + +async function launch(): Promise { + vi.resetModules(); + return import('../../../../electron/services/core-db'); +} + +beforeEach(() => { h.dir = mkdtempSync(join(tmpdir(), 'core-db-write-blob-')); }); +afterEach(() => { rmSync(h.dir, { recursive: true, force: true }); }); + +describe('writeBlob / setBlob', () => { + // Breaks: the throwing writer does not actually store, or reads back differently. + it('writeBlob stores what readBlob reads back', async () => { + const db = await launch(); + db.writeBlob('k', Buffer.from('v1')); + db.writeBlob('k', Buffer.from('v2')); + expect(db.readBlob('k')?.toString()).toBe('v2'); + db.getCoreDb().close(); + }); + + // THE difference. Breaks: a failed write is reported as stored (writeBlob), + // or the long-standing best-effort setBlob starts throwing at its callers. + it('writeBlob throws on a failed write, where setBlob only logs it', async () => { + const db = await launch(); + db.getCoreDb().exec('DROP TABLE core_blobs'); + expect(() => db.writeBlob('k', Buffer.from('v'))).toThrow(); + expect(() => db.setBlob('k', Buffer.from('v'))).not.toThrow(); + expect(() => db.writeBlob('', Buffer.from('v'))).toThrow(); + db.getCoreDb().close(); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/secure-credential-store.test.ts b/apps/desktop/test/unit/electron/services/secure-credential-store.test.ts index 8df78815..c0cff4ee 100644 --- a/apps/desktop/test/unit/electron/services/secure-credential-store.test.ts +++ b/apps/desktop/test/unit/electron/services/secure-credential-store.test.ts @@ -52,6 +52,8 @@ import { migrateSecureCredsFromFile, narrowAccountSecretTransport, rekeyAccountSecrets, + removeAccountCertificatePin, + setAccountCertificatePin, setAccountSecrets, } from '../../../../electron/services/secure-credential-store'; import { asPlatform } from '../../../helpers/as-platform'; @@ -62,10 +64,13 @@ const LEGACY = 'secure-credentials.json'; const plainEnvelope = (value: unknown): Buffer => Buffer.from(`PLAIN1:${JSON.stringify(value)}`, 'utf8'); // Every secret written through setAccountSecrets now records the transport -// relaxations chosen with it, as booleans (see 'transport binding' below). +// relaxation chosen with it, as a boolean (see 'transport binding' below). // Changed deliberately (transport binding): the expected entries in the tests -// that spread this used to be the bare secret (and host). -const STRICT = { allowInsecureTLS: false, allowPlaintext: false }; +// that spread this used to be the bare secret (and host). Changed deliberately +// again (certificate pinning, CASA 4.1.2): it no longer carries +// `allowInsecureTLS: false` — the "allow self-signed" switch is retired and +// never written. +const STRICT = { allowPlaintext: false }; beforeAll(() => { h.userData = mkdtempSync(join(tmpdir(), 'sarvinbox-vault-')); }); @@ -163,6 +168,19 @@ describe('an undecodable vault', () => { ); }); + // Breaks: a core DB that cannot be read (a broken addon, a locked file) reads + // as an empty vault, and the next write — a password, or an approved + // certificate — replaces every other account's secrets with just itself. + it('THROWS when the core DB itself cannot be read, and refuses the write', async () => { + await setAccountSecrets('acct-other', { imap: { password: 'precious' } }); + dbState.fail.add('blob-read'); + await expect(getAccountSecrets('acct-other')).rejects.toThrow(); + await expect(setAccountSecrets('acct-a', { imap: { password: 'new' } })).rejects.toThrow(); + dbState.fail.delete('blob-read'); + await expect(getAccountSecrets('acct-other')).resolves.toEqual({ imap: { password: 'precious', ...STRICT } }); + await expect(getAccountSecrets('acct-a')).resolves.toBeNull(); + }); + it('fails the WRITE too, so a locked keychain cannot clobber other accounts', async () => { const original = plainEnvelope({ 'acct-other': { imap: { password: 'precious' } } }); dbState.blobs.set(BLOB_KEY, Buffer.concat([Buffer.from('ENC1:'), original])); @@ -321,85 +339,174 @@ describe('transport binding on the vault entry', () => { // (vault-credentials.ts). Breaks if dropped: a new secret is written unbound // and its first connect — possibly from a compromised window — picks how it // is sent. - it('stores the relaxations chosen with a secret, always as booleans', async () => { + // + // Changed deliberately (certificate pinning, CASA 4.1.2): this used to store + // `allowInsecureTLS: true` too. That switch is retired, so it is no longer + // written — a window sending it changes nothing. + it('stores the relaxation chosen with a secret, always as a boolean, and never the retired switch', async () => { await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true }, smtp: { password: 's', host: 'smtp.x.com' }, }); expect(await getAccountSecrets('acct-a')).toEqual({ - imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true }, + imap: { password: 'pw', host: 'imap.x.com', allowPlaintext: true }, smtp: { password: 's', host: 'smtp.x.com', ...STRICT }, }); }); // Only a real `true` relaxes; settings round-trip through IPC as JSON. it('reads a truthy non-boolean as not chosen', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'pw', allowInsecureTLS: 'true', allowPlaintext: 1 } as never }); + await setAccountSecrets('acct-a', { imap: { password: 'pw', allowPlaintext: 1 } as never }); expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', ...STRICT }); }); - // THE loosening. Breaks: a window that does not know the password ticks - // "allow self-signed" for it, and main sends it to a man-in-the-middle. + // THE loosening. Breaks: a window that does not know the password picks + // "None" for it, and main sends it in cleartext. it('ignores relaxations that arrive without a secret', async () => { await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com' } }); - await setAccountSecrets('acct-a', { imap: { host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true } }); + await setAccountSecrets('acct-a', { imap: { host: 'imap.x.com', allowPlaintext: true } }); expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...STRICT }); }); }); +// Changed deliberately (certificate pinning, CASA 4.1.2): these used to bind +// and narrow `allowInsecureTLS` alongside `allowPlaintext`. The switch is +// retired, so the plaintext relaxation is the only one left; a legacy entry's +// stored `allowInsecureTLS` is left as it is (read only to word the approval +// dialog) and never bound or narrowed. describe('bindAccountSecretTransport', () => { const legacy = (vault: unknown) => dbState.blobs.set(BLOB_KEY, plainEnvelope(vault)); // Upgrade path: entries saved before transport binding are bound on first use. - it('fills in the relaxations a legacy entry lacks, leaving the other kind alone', async () => { + it('fills in the relaxation a legacy entry lacks, leaving the other kind alone', async () => { legacy({ 'acct-a': { imap: { password: 'pw', host: 'imap.x.com' }, smtp: { password: 's' } } }); - await bindAccountSecretTransport('acct-a', 'imap', { allowInsecureTLS: true, allowPlaintext: false }); + await bindAccountSecretTransport('acct-a', 'imap', { allowPlaintext: true }); expect(await getAccountSecrets('acct-a')).toEqual({ - imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: false }, + imap: { password: 'pw', host: 'imap.x.com', allowPlaintext: true }, smtp: { password: 's' }, }); }); // Breaks: a later "first use" asking for more rewrites an existing choice. it('never changes a recorded relaxation, and is a no-op for missing entries', async () => { - legacy({ 'acct-a': { imap: { password: 'pw', allowInsecureTLS: false } } }); - await bindAccountSecretTransport('acct-a', 'imap', { allowInsecureTLS: true, allowPlaintext: true }); - await bindAccountSecretTransport('acct-a', 'smtp', { allowInsecureTLS: true, allowPlaintext: true }); - await bindAccountSecretTransport('acct-missing', 'imap', { allowInsecureTLS: true, allowPlaintext: true }); - await bindAccountSecretTransport('', 'imap', { allowInsecureTLS: true, allowPlaintext: true }); - expect(await getAccountSecrets('acct-a')).toEqual({ imap: { password: 'pw', allowInsecureTLS: false, allowPlaintext: true } }); + legacy({ 'acct-a': { imap: { password: 'pw', allowInsecureTLS: true, allowPlaintext: false } } }); + await bindAccountSecretTransport('acct-a', 'imap', { allowPlaintext: true }); + await bindAccountSecretTransport('acct-a', 'smtp', { allowPlaintext: true }); + await bindAccountSecretTransport('acct-missing', 'imap', { allowPlaintext: true }); + await bindAccountSecretTransport('', 'imap', { allowPlaintext: true }); + expect(await getAccountSecrets('acct-a')).toEqual({ imap: { password: 'pw', allowInsecureTLS: true, allowPlaintext: false } }); expect(await getAccountSecrets('acct-missing')).toBeNull(); }); }); describe('narrowAccountSecretTransport', () => { - const both = { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true }; + const none = { password: 'pw', host: 'imap.x.com', allowPlaintext: true }; // A stricter connection worked, so the user's stricter choice becomes the - // saved one. Breaks: switching "allow self-signed" off never sticks, and a - // later config can switch it back on for the saved password. - it('switches off only the named relaxations', async () => { - await setAccountSecrets('acct-a', { imap: both }); - await narrowAccountSecretTransport('acct-a', 'imap', 'pw', ['allowInsecureTLS']); - expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ ...both, allowInsecureTLS: false }); + // saved one. Breaks: switching "None" off never sticks, and a later config + // can switch it back on for the saved password. + it('switches off the named relaxation', async () => { + await setAccountSecrets('acct-a', { imap: none }); + await narrowAccountSecretTransport('acct-a', 'imap', 'pw', ['allowPlaintext']); + expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ ...none, allowPlaintext: false }); }); // Breaks: narrowing becomes a way to loosen. it('never switches a relaxation on', async () => { await setAccountSecrets('acct-a', { imap: { password: 'pw' } }); - await narrowAccountSecretTransport('acct-a', 'imap', 'pw', ['allowInsecureTLS', 'allowPlaintext']); + await narrowAccountSecretTransport('acct-a', 'imap', 'pw', ['allowPlaintext']); expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', ...STRICT }); }); // A password saved since the connect started carries its own choice. // Breaks: a slow connect with the old password undoes the user's new choice. it('leaves the entry alone once it holds a different password, and no-ops without one', async () => { - await setAccountSecrets('acct-a', { imap: both }); - await narrowAccountSecretTransport('acct-a', 'imap', 'old-pw', ['allowInsecureTLS', 'allowPlaintext']); - await narrowAccountSecretTransport('acct-a', 'smtp', 'pw', ['allowInsecureTLS']); - await narrowAccountSecretTransport('acct-a', 'imap', '', ['allowInsecureTLS']); - await narrowAccountSecretTransport('', 'imap', 'pw', ['allowInsecureTLS']); - expect(await getAccountSecrets('acct-a')).toEqual({ imap: both }); + await setAccountSecrets('acct-a', { imap: none }); + await narrowAccountSecretTransport('acct-a', 'imap', 'old-pw', ['allowPlaintext']); + await narrowAccountSecretTransport('acct-a', 'smtp', 'pw', ['allowPlaintext']); + await narrowAccountSecretTransport('acct-a', 'imap', '', ['allowPlaintext']); + await narrowAccountSecretTransport('', 'imap', 'pw', ['allowPlaintext']); + expect(await getAccountSecrets('acct-a')).toEqual({ imap: none }); + }); +}); + +describe('approved certificates (CASA 4.1.2)', () => { + const PIN = { + host: 'imap.office.lan', port: 993, sha256: 'AB:CD', pem: 'PEM', approvedAt: 1, + subject: 'CN=imap.office.lan', issuer: 'CN=imap.office.lan', validFrom: 'a', validTo: 'b', + }; + + // Breaks: an approved certificate is lost when the window re-saves the + // password (it does after every successful typed connect), so the user is + // asked again on every launch — or the two transports overwrite each other. + it('stores a pin per transport, kept across password saves and next to the secrets', async () => { + await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.office.lan' } }); + await setAccountCertificatePin('acct-a', 'imap', PIN); + await setAccountCertificatePin('acct-a', 'smtp', { ...PIN, host: 'smtp.office.lan', port: 465 }); + await setAccountSecrets('acct-a', { imap: { password: 'pw2', host: 'imap.office.lan' } }); + expect((await getAccountSecrets('acct-a'))?.certificates).toEqual({ imap: PIN, smtp: { ...PIN, host: 'smtp.office.lan', port: 465 } }); + }); + + // THE boundary. Breaks: the window (which renders untrusted mail) writes a + // pin through secureCreds:set and points the saved password at an attacker's + // certificate. Only main's approval flow calls setAccountCertificatePin. + it('never takes a pin from setAccountSecrets', async () => { + await setAccountSecrets('acct-a', { imap: { password: 'pw', certificatePin: PIN }, certificates: { imap: PIN } } as never); + expect(await getAccountSecrets('acct-a')).toEqual({ imap: { password: 'pw', ...STRICT } }); + }); + + // Breaks: approving a certificate for a migrated account leaves the retired + // switch in place for something to read again. + it('drops the retired switch from the entry once a pin is approved', async () => { + dbState.blobs.set(BLOB_KEY, plainEnvelope({ 'acct-a': { imap: { password: 'pw', host: 'imap.office.lan', allowInsecureTLS: true, allowPlaintext: false } } })); + await setAccountCertificatePin('acct-a', 'imap', PIN); + expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.office.lan', allowPlaintext: false }); + }); + + // Breaks: a pin approved during a new account's first probe (no password + // saved yet) has nowhere to live, or counts as "secrets on file". + it('can hold a pin for an account with no saved password, which is not "secrets"', async () => { + await setAccountCertificatePin('acct-new', 'imap', PIN); + expect(await getAccountSecrets('acct-new')).toEqual({ certificates: { imap: PIN } }); + await expect(hasAccountSecrets('acct-new')).resolves.toBe(false); + }); + + // Breaks: Remove leaves the certificate trusted under one of the account's + // ids, or removing one transport's pin drops the other. + it('removes a pin under every id given, leaving the other transport and no empty shell', async () => { + await setAccountCertificatePin('acct-a', 'imap', PIN); + await setAccountCertificatePin('acct-a', 'smtp', PIN); + await setAccountCertificatePin('acct-legacy', 'imap', PIN); + await expect(removeAccountCertificatePin(['acct-a', 'acct-legacy'], 'imap')).resolves.toBe(true); + expect((await getAccountSecrets('acct-a'))?.certificates).toEqual({ smtp: PIN }); + await expect(getAccountSecrets('acct-legacy')).resolves.toBeNull(); + await expect(removeAccountCertificatePin(['acct-a'], 'imap')).resolves.toBe(false); + }); + + // Breaks: a pin outlives its account, or the account-id canonicalisation + // leaves it behind under the old id. + it('goes with the account on delete and on re-key', async () => { + await setAccountCertificatePin('acct-old', 'imap', PIN); + await rekeyAccountSecrets('acct-old', 'acct-new'); + expect((await getAccountSecrets('acct-new'))?.certificates).toEqual({ imap: PIN }); + await deleteAccountSecrets('acct-new'); + await expect(getAccountSecrets('acct-new')).resolves.toBeNull(); + }); + + // Breaks: an approval or removal against an unreadable vault "succeeds" + // into an empty one and wipes every other account. + it('refuses to write or remove a pin when the vault cannot be read', async () => { + await setAccountSecrets('acct-other', { imap: { password: 'precious' } }); + dbState.fail.add('blob-read'); + await expect(setAccountCertificatePin('acct-a', 'imap', PIN)).rejects.toThrow(); + await expect(removeAccountCertificatePin(['acct-other'], 'imap')).rejects.toThrow(); + dbState.fail.delete('blob-read'); + await expect(getAccountSecrets('acct-other')).resolves.toEqual({ imap: { password: 'precious', ...STRICT } }); + }); + + // Breaks: a pin is written under no account at all. + it('refuses a pin with no account id', async () => { + await expect(setAccountCertificatePin('', 'imap', PIN)).rejects.toThrow(); }); }); diff --git a/apps/desktop/test/unit/electron/services/vault-credentials.test.ts b/apps/desktop/test/unit/electron/services/vault-credentials.test.ts index 9a7a223f..31091398 100644 --- a/apps/desktop/test/unit/electron/services/vault-credentials.test.ts +++ b/apps/desktop/test/unit/electron/services/vault-credentials.test.ts @@ -55,8 +55,16 @@ import { type VaultPasswordFound, } from '../../../../electron/services/vault-credentials'; -const STRICT = { allowInsecureTLS: false, allowPlaintext: false }; -const SELF_SIGNED = { allowInsecureTLS: true, allowPlaintext: false }; +// Changed deliberately (certificate pinning, CASA 4.1.2): the transport saved +// with a password used to carry two relaxations, `allowInsecureTLS` ("allow +// self-signed") and `allowPlaintext`. The first is retired — certificates are +// approved per server in main and applied by certificate-trust.ts — so the +// tests below that exercised the transport binding through "self-signed" now +// exercise it through the remaining relaxation, security 'none' (UNENCRYPTED), +// with the same intent. Registry configs that said `allowInsecureTLS: true` +// say `security: 'none'`. +const STRICT = { allowPlaintext: false }; +const UNENCRYPTED = { allowPlaintext: true }; // Changed deliberately (transport binding): a found password now comes with the // relaxations saved alongside it and the id it was found under; the 'found' // expectations below that use this used to be { status, password } only. @@ -273,13 +281,13 @@ describe('resolveVaultPassword — legacy (unbound) entries', () => { it('reads the transport from the account the host rule found', async () => { const id = accountIdFor('a@x.com'); legacyVault({ [id]: { imap: { password: 'pw' } } }); - atStartup([{ id: accountIdFor('a@x.com', 'imap.x.com'), email: 'a@x.com', imapConfig: { host: 'imap.x.com', allowInsecureTLS: true }, smtpConfig: null }]); + atStartup([{ id: accountIdFor('a@x.com', 'imap.x.com'), email: 'a@x.com', imapConfig: { host: 'imap.x.com', security: 'none' }, smtpConfig: null }]); const result = await resolveVaultPassword([id], 'imap', 'imap.x.com'); - expect(result).toEqual(found('pw', id, SELF_SIGNED)); - expect(withSavedPassword({ host: 'imap.x.com', allowInsecureTLS: true }, 'imap', result as VaultPasswordFound)).toHaveProperty('config'); - expect((await getAccountSecrets(id))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...SELF_SIGNED }); + expect(result).toEqual(found('pw', id, UNENCRYPTED)); + expect(withSavedPassword({ host: 'imap.x.com', security: 'none' }, 'imap', result as VaultPasswordFound)).toHaveProperty('config'); + expect((await getAccountSecrets(id))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...UNENCRYPTED }); }); // The same when the host was bound by an earlier version and only the transport @@ -287,21 +295,21 @@ describe('resolveVaultPassword — legacy (unbound) entries', () => { it('reads it through the account for an entry already bound to its host', async () => { const id = accountIdFor('a@x.com'); legacyVault({ [id]: { imap: { password: 'pw', host: 'imap.x.com' } } }); - atStartup([{ id: accountIdFor('a@x.com', 'imap.x.com'), email: 'a@x.com', imapConfig: { host: 'imap.x.com', allowInsecureTLS: true }, smtpConfig: null }]); - await expect(resolveVaultPassword([id], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', id, SELF_SIGNED)); + atStartup([{ id: accountIdFor('a@x.com', 'imap.x.com'), email: 'a@x.com', imapConfig: { host: 'imap.x.com', security: 'none' }, smtpConfig: null }]); + await expect(resolveVaultPassword([id], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', id, UNENCRYPTED)); }); // Multi-account: the relaxations of one server must not travel to the other, and // which is which depends on the server asked for, not on registry order. it.each([ ['imap.strict.com', STRICT], - ['imap.selfsigned.com', SELF_SIGNED], + ['imap.unencrypted.com', UNENCRYPTED], ])('takes the transport from the owner whose server is %s', async (host, transport) => { const id = accountIdFor('a@x.com'); legacyVault({ [id]: { imap: { password: 'pw' } } }); atStartup([ { id: accountIdFor('a@x.com', 'imap.strict.com'), email: 'a@x.com', imapConfig: { host: 'imap.strict.com' }, smtpConfig: null }, - { id: accountIdFor('a@x.com', 'imap.selfsigned.com'), email: 'a@x.com', imapConfig: { host: 'imap.selfsigned.com', allowInsecureTLS: true }, smtpConfig: null }, + { id: accountIdFor('a@x.com', 'imap.unencrypted.com'), email: 'a@x.com', imapConfig: { host: 'imap.unencrypted.com', security: 'none' }, smtpConfig: null }, ]); await expect(resolveVaultPassword([id], 'imap', host)).resolves.toEqual(found('pw', id, transport)); }); @@ -310,7 +318,7 @@ describe('resolveVaultPassword — legacy (unbound) entries', () => { // by the same-site rule has no record of its own, so it stays strict. it('stays strict for a server the same account does not record', async () => { legacyVault({ 'acct-a': { smtp: { password: 's' } } }); - atStartup([{ id: 'acct-a', email: 'a@x.com', imapConfig: { host: 'imap.x.com', allowInsecureTLS: true }, smtpConfig: null }]); + atStartup([{ id: 'acct-a', email: 'a@x.com', imapConfig: { host: 'imap.x.com', security: 'none' }, smtpConfig: null }]); await expect(resolveVaultPassword(['acct-a'], 'smtp', 'smtp.x.com')).resolves.toEqual(found('s', 'acct-a')); }); }); @@ -440,16 +448,25 @@ describe('resolveVaultPassword — legacy (unbound) entries', () => { }); describe('resolveVaultPassword — how the password may be sent', () => { - // Breaks: a self-signed account's saved password stops connecting, or the - // relaxation chosen for IMAP leaks onto SMTP. - it('returns the relaxations saved with the password, per kind', async () => { + // Breaks: an unencrypted account's saved password stops connecting, or the + // relaxation chosen for SMTP leaks onto IMAP. + it('returns the relaxation saved with the password, per kind', async () => { await setAccountSecrets('acct-a', { - imap: { password: 'i', host: 'imap.x.com', allowInsecureTLS: true }, + imap: { password: 'i', host: 'imap.x.com' }, smtp: { password: 's', host: 'smtp.x.com', allowPlaintext: true }, }); - await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('i', 'acct-a', SELF_SIGNED)); - await expect(resolveVaultPassword(['acct-a'], 'smtp', 'smtp.x.com')) - .resolves.toEqual(found('s', 'acct-a', { allowInsecureTLS: false, allowPlaintext: true })); + await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('i', 'acct-a')); + await expect(resolveVaultPassword(['acct-a'], 'smtp', 'smtp.x.com')).resolves.toEqual(found('s', 'acct-a', UNENCRYPTED)); + }); + + // CASA 4.1.2 migration. Breaks: an account saved with the retired "allow + // self-signed" switch is either refused outright (asked to re-type its + // password) or — worse — still relaxed. It is found strict, flagged only so + // the approval dialog can say why it asks once. + it('finds a password saved with the retired switch as strict, flagged for the approval dialog', async () => { + legacyVault({ 'acct-a': { imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: false } } }); + await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')) + .resolves.toEqual({ ...found('pw', 'acct-a'), legacyInsecureTLS: true }); }); }); @@ -464,23 +481,24 @@ describe('resolveVaultPassword — legacy entries without a recorded transport', imapConfig: { host: 'imap.x.com', allowInsecureTLS: true, security: 'none' }, smtpConfig: { host: 'smtp.x.com', security: 'ssl' }, }]); + // The registry's retired allowInsecureTLS binds nothing (CASA 4.1.2). await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')) - .resolves.toEqual(found('pw', 'acct-a', { allowInsecureTLS: true, allowPlaintext: true })); + .resolves.toEqual(found('pw', 'acct-a', UNENCRYPTED)); await expect(resolveVaultPassword(['acct-a'], 'smtp', 'smtp.x.com')).resolves.toEqual(found('s', 'acct-a')); expect(await getAccountSecrets('acct-a')).toEqual({ - imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true }, + imap: { password: 'pw', host: 'imap.x.com', ...UNENCRYPTED }, smtp: { password: 's', host: 'smtp.x.com', ...STRICT }, }); // Bound: the next startup's registry does not move it. atStartup([]); await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')) - .resolves.toEqual(found('pw', 'acct-a', { allowInsecureTLS: true, allowPlaintext: true })); + .resolves.toEqual(found('pw', 'acct-a', UNENCRYPTED)); }); // THE bypass the review found. Breaks: before the app happens to use a // legacy password (another account's sending password, an account without - // background sync), a compromised window writes "None" / "allow self-signed" - // into the registry and the password is bound — and sent — that way. + // background sync), a compromised window writes "None" into the registry and + // the password is bound — and sent — that way. it('ignores registry writes made after startup', async () => { legacyVault({ 'acct-b': { smtp: { password: 's', host: 'smtp.b.com' } } }); atStartup([{ id: 'acct-b', email: 'b@b.com', imapConfig: { host: 'imap.b.com' }, smtpConfig: { host: 'smtp.b.com', security: 'ssl' } }]); @@ -488,7 +506,7 @@ describe('resolveVaultPassword — legacy entries without a recorded transport', await expect(resolveVaultPassword(['acct-b'], 'smtp', 'smtp.b.com')).resolves.toEqual(found('s', 'acct-b')); }); - // An OAuth registry config never grants either relaxation to the password. + // An OAuth registry config never grants a relaxation to the password. it('reads an OAuth registry config as strict', async () => { legacyVault({ 'acct-a': { imap: { password: 'pw', host: 'imap.x.com' } } }); atStartup([{ id: 'acct-a', email: 'a@x.com', imapConfig: { host: 'imap.x.com', authMethod: 'oauth2', allowInsecureTLS: true, security: 'none' } }]); @@ -508,18 +526,18 @@ describe('resolveVaultPassword — legacy entries without a recorded transport', // Fills only what is missing. Breaks: a partly-recorded entry is re-decided. it('keeps a relaxation the entry already records', async () => { - legacyVault({ 'acct-a': { imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true } } }); + legacyVault({ 'acct-a': { imap: { password: 'pw', host: 'imap.x.com', allowPlaintext: true } } }); atStartup([]); - await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', 'acct-a', SELF_SIGNED)); + await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', 'acct-a', UNENCRYPTED)); }); // The registry only matters for entries that record nothing. Breaks: every // saved password stops connecting whenever the registry can't be read. it('uses an entry that records its transport even with no startup snapshot', async () => { - await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com', allowInsecureTLS: true } }); + await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com', allowPlaintext: true } }); h.registryThrows = true; captureRegistryForLegacyBinding(); - await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', 'acct-a', SELF_SIGNED)); + await expect(resolveVaultPassword(['acct-a'], 'imap', 'imap.x.com')).resolves.toEqual(found('pw', 'acct-a', UNENCRYPTED)); }); // No snapshot is not "no record". Breaks: a registry that could not be read @@ -538,56 +556,61 @@ describe('withSavedPassword', () => { const saved = (transport = STRICT): VaultPasswordFound => ({ status: 'found', password: 'pw', transport, id: 'acct-a' }); const config = { host: 'imap.x.com', port: 993, username: 'a@x.com', authMethod: 'password' as const, security: 'ssl' as const }; + // Changed deliberately (certificate pinning): the first case used to keep a + // granted `allowInsecureTLS`; the retired switch is now dropped from the + // config rather than passed through. it('injects the password for a connect asking for no more than was saved', () => { - expect(withSavedPassword(config, 'imap', saved())).toEqual({ config: { ...config, password: 'pw', allowInsecureTLS: false } }); - expect(withSavedPassword({ ...config, allowInsecureTLS: true }, 'imap', saved(SELF_SIGNED))) - .toEqual({ config: { ...config, password: 'pw', allowInsecureTLS: true } }); + expect(withSavedPassword(config, 'imap', saved())).toEqual({ config: { ...config, password: 'pw' } }); + expect(withSavedPassword({ ...config, security: 'none' as const }, 'imap', saved(UNENCRYPTED))) + .toEqual({ config: { ...config, security: 'none', password: 'pw' } }); }); - // THE finding. Breaks: a compromised window adds "allow self-signed" (or - // 'none') to a saved account's connect, and main hands the real password to - // a man-in-the-middle. + // THE finding. Breaks: a compromised window adds 'none' to a saved account's + // connect, and main hands the real password over in cleartext. Changed + // deliberately (certificate pinning): the "allow self-signed" refusal is gone + // with the switch — a config carrying it is not relaxed, so it is not refused. it('refuses a connect asking for a relaxation the password was not saved with', () => { - expect(withSavedPassword({ ...config, allowInsecureTLS: true }, 'imap', saved())).toEqual({ - refusal: "Your saved mailbox password was saved for a connection that checks imap.x.com's certificate. Re-enter your password to connect without checking it.", - }); - expect(withSavedPassword({ ...config, security: 'none' as const }, 'imap', saved(SELF_SIGNED))).toEqual({ + expect(withSavedPassword({ ...config, security: 'none' as const }, 'imap', saved())).toEqual({ refusal: 'Your saved mailbox password was saved for an encrypted connection to imap.x.com. Re-enter your password to connect without encryption.', }); }); - // Tightening is the user's call. Breaks: unticking "allow self-signed" is ignored. + // CASA 4.1.2. Breaks: an old config's "allow self-signed" survives into the + // connect with the saved password, or a pin the window put on the config is + // dialled with the saved password (only main's store may supply one). + it('drops the retired switch and any pin from the window', () => { + const fromWindow = { ...config, allowInsecureTLS: true, certificatePin: { sha256: 'AB', pem: 'ATTACKER' } }; + expect(withSavedPassword(fromWindow, 'imap', saved())).toEqual({ config: { ...config, password: 'pw' } }); + }); + + // Tightening is the user's call. Breaks: choosing encryption again is ignored. it('lets a connect be stricter than the password was saved for', () => { - const both = { allowInsecureTLS: true, allowPlaintext: true }; - expect(withSavedPassword(config, 'imap', saved(both))).toEqual({ config: { ...config, password: 'pw', allowInsecureTLS: false } }); + expect(withSavedPassword(config, 'imap', saved(UNENCRYPTED))).toEqual({ config: { ...config, password: 'pw' } }); }); }); describe('narrowSavedTransport', () => { - const both = { allowInsecureTLS: true, allowPlaintext: true }; - const savedBoth = async (): Promise => { - await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com', ...both } }); - return { status: 'found', password: 'pw', transport: both, id: 'acct-a' }; + const savedUnencrypted = async (): Promise => { + await setAccountSecrets('acct-a', { imap: { password: 'pw', host: 'imap.x.com', ...UNENCRYPTED } }); + return { status: 'found', password: 'pw', transport: UNENCRYPTED, id: 'acct-a' }; }; - // A verified, encrypted connection to that server just worked. Breaks: the - // user's switch back to "verify" never sticks, so a later config can switch - // the saved password back to an unverified connection. - it('switches off the relaxations a working connection did without', async () => { - await narrowSavedTransport('imap', await savedBoth(), { security: 'starttls' }); + // An encrypted connection to that server just worked. Breaks: the user's + // switch back to encryption never sticks, so a later config can switch the + // saved password back to an unencrypted connection. + it('switches off the relaxation a working connection did without', async () => { + await narrowSavedTransport('imap', await savedUnencrypted(), { security: 'starttls' }); expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...STRICT }); }); - it('keeps the relaxations the connection used', async () => { - await narrowSavedTransport('imap', await savedBoth(), { allowInsecureTLS: true, security: 'none' }); - expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...both }); - await narrowSavedTransport('imap', await savedBoth(), { allowInsecureTLS: true, security: 'ssl' }); - expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: false }); + it('keeps the relaxation the connection used', async () => { + await narrowSavedTransport('imap', await savedUnencrypted(), { security: 'none' }); + expect((await getAccountSecrets('acct-a'))?.imap).toEqual({ password: 'pw', host: 'imap.x.com', ...UNENCRYPTED }); }); // Best-effort: a vault that can't be written must not fail a working connect. it('swallows a write failure', async () => { - const saved = await savedBoth(); + const saved = await savedUnencrypted(); dbState.blobs.set('secure-credentials', Buffer.from('garbage')); await expect(narrowSavedTransport('imap', saved, {})).resolves.toBeUndefined(); }); @@ -596,7 +619,7 @@ describe('narrowSavedTransport', () => { describe('transportMismatchMessage', () => { // Breaks: the user sees a vague error and can't tell what to do. it('says what the saved password allows and to re-enter it', () => { - expect(transportMismatchMessage('smtp', 'smtp.x.com', 'insecure-tls')).toContain('Your saved sending password'); + expect(transportMismatchMessage('smtp', 'smtp.x.com', 'plaintext')).toContain('Your saved sending password'); expect(transportMismatchMessage('smtp', 'smtp.x.com', 'plaintext')).toContain('Re-enter your password to connect without encryption.'); }); }); diff --git a/apps/desktop/test/unit/src/components/TrustedCertificate.test.tsx b/apps/desktop/test/unit/src/components/TrustedCertificate.test.tsx new file mode 100644 index 00000000..470f57ce --- /dev/null +++ b/apps/desktop/test/unit/src/components/TrustedCertificate.test.tsx @@ -0,0 +1,96 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { TrustedCertificate } from '../../../../src/components/TrustedCertificate'; +import { cleanup, fire, render, settle, type Mounted } from '../../../helpers/render'; + +// CASA 4.1.2 — the account settings' view of an approved certificate. What +// breaks if this file fails: the user cannot see WHICH certificate an account +// trusts (the assessor's "identify the specific permitted certificates"), or +// cannot stop trusting it; or a certificate approved for another server or +// port is shown as this one's. + +const FP = Array.from({ length: 32 }, (_, i) => (i + 16).toString(16).toUpperCase()).join(':'); +const APPROVED = { host: 'imap.office.lan', port: 993, sha256: FP, approvedAt: Date.parse('2026-11-28T10:00:00Z'), subject: 'CN=imap.office.lan', issuer: 'CN=imap.office.lan', validTo: 'Nov 1 00:00:00 2027 GMT' }; + +const list = vi.fn(); +const remove = vi.fn(); +let view: Mounted; +const text = () => view.container.textContent ?? ''; +const button = (label: string) => view.all('button').find((b) => b.textContent?.includes(label)) ?? null; + +beforeEach(() => { + list.mockReset().mockResolvedValue({ success: true, data: { imap: APPROVED } }); + remove.mockReset().mockResolvedValue({ success: true, data: { removed: true } }); + (window as unknown as { electronAPI: unknown }).electronAPI = { certificates: { list, remove } }; +}); +afterEach(() => cleanup()); + +describe('TrustedCertificate', () => { + // Breaks: the fingerprint, server or approval date is not shown, so the user + // cannot compare it with what their administrator gave them. + it('shows the approved certificate: server, approval date, validity and full SHA-256', async () => { + view = render(); + await settle(); + expect(list).toHaveBeenCalledWith('acct-a'); + expect(text()).toContain('Trusted certificate'); + expect(text()).toContain('imap.office.lan:993'); + expect(text()).toContain('valid until Nov 1 00:00:00 2027 GMT'); + expect(text()).toContain(new Date(APPROVED.approvedAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })); + expect(text().replace(/\s/g, '')).toContain(FP); + expect(view.find('[aria-label^="SHA-256 fingerprint"]')?.getAttribute('aria-label')).toBe(`SHA-256 fingerprint ${FP}`); + }); + + // Breaks: Remove does nothing, or the row keeps claiming the certificate is trusted. + it('removes it and says the next reconnect will ask', async () => { + view = render(); + await settle(); + fire(button('Remove')!, 'click'); + await settle(); + expect(remove).toHaveBeenCalledWith('acct-a', 'imap'); + expect(text()).not.toContain('Trusted certificate'); + expect(text()).toContain('will ask about this server'); + }); + + // Breaks: a failed removal is silent and the user believes it is gone. + it('says so when the removal fails, and keeps showing the certificate', async () => { + remove.mockResolvedValueOnce({ success: false, error: 'The approved certificate could not be removed. Try again in a moment.' }); + view = render(); + await settle(); + fire(button('Remove')!, 'click'); + await settle(); + expect(text()).toContain('could not be removed'); + expect(text()).toContain('Trusted certificate'); + }); + + // Breaks: a pin for the account's OLD server (or another port), or for the + // other transport, is presented as this server's. + it('shows nothing for another host, port or transport, or with no certificate', async () => { + for (const props of [{ host: 'mail.other.lan', port: 993 }, { host: 'IMAP.office.lan.', port: 143 }]) { + view = render(); + await settle(); + expect(text()).toBe(''); + cleanup(); + } + view = render(); + await settle(); + expect(text()).toBe(''); + cleanup(); + view = render(); + await settle(); + expect(text()).toContain('Trusted certificate'); + }); + + // Breaks: an unreadable vault or a missing account crashes the settings popup. + it('shows nothing when the list fails or there is no account', async () => { + list.mockRejectedValueOnce(new Error('ipc down')); + view = render(); + await settle(); + expect(text()).toBe(''); + cleanup(); + view = render(); + await settle(); + expect(text()).toBe(''); + expect(list).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/desktop/test/unit/src/components/connection-security-ui.test.tsx b/apps/desktop/test/unit/src/components/connection-security-ui.test.tsx index 4236c582..fd528766 100644 --- a/apps/desktop/test/unit/src/components/connection-security-ui.test.tsx +++ b/apps/desktop/test/unit/src/components/connection-security-ui.test.tsx @@ -97,20 +97,47 @@ describe('SmtpConfigForm', () => { expect(connectSmtp).toHaveBeenCalledWith(expect.objectContaining({ security: 'none', secure: false, port: 25 })); }); - // An OAuth connection always checks the certificate (core resolveTlsOptions), - // so the box would do nothing. Breaks: an OAuth user ticks a box that is - // silently ignored, or a saved stale opt-in rides along on every send. - it('offers "allow self-signed" for a password account only, and never sends it for OAuth', async () => { + // Changed deliberately (certificate pinning, CASA 4.1.2): this used to pin + // that the form offered "Allow self-signed / invalid certificates" to a + // password account. The switch is retired — a server's own certificate is + // shown by main to approve during the connect — so the form offers no + // certificate setting, says how a self-signed server works, and sends nothing + // certificate-related, even when a saved config still carries the old switch. + it('offers no "allow self-signed" switch and never sends one, for password or OAuth', async () => { state.smtpConfig = { host: 'smtp.x.com', port: 465, secure: true, username: 'me@x.com', allowInsecureTLS: true }; mounted = render(); - expect(text()).toContain('Allow self-signed'); + expect(text()).not.toContain('Allow self-signed'); + expect(mounted.container.querySelector('input[type="checkbox"]')).toBeNull(); + expect(text()).toContain('shows it to you to approve'); + typeInto(mounted.find('input[type="password"]'), 'pw'); + await submitForm(); + expect((connectSmtp.mock.calls.at(-1) as unknown[])[0]).not.toHaveProperty('allowInsecureTLS'); mounted.unmount(); state.imapConfig = { host: 'imap.gmail.com', username: 'me@gmail.com', authMethod: 'oauth2', oauthProvider: 'gmail' }; state.smtpConfig = { host: 'smtp.gmail.com', port: 465, secure: true, username: 'me@gmail.com', authMethod: 'oauth2', allowInsecureTLS: true }; mounted = render(); - expect(text()).not.toContain('Allow self-signed'); + expect(text()).not.toContain('shows it to you to approve'); + await submitForm(); + expect((connectSmtp.mock.calls.at(-1) as unknown[])[0]).not.toHaveProperty('allowInsecureTLS'); + }); + + // CASA 4.1.2. Breaks: "Verify" on a self-signed sending server can never + // ask (the form does not arm main's question), or an OAuth form arms it. + it('arms main\'s certificate question for SMTP when the user verifies, and never for OAuth', async () => { + const review = vi.fn(async () => ({ success: true, data: { armed: true } })); + (window.electronAPI as unknown as { certificates: unknown }).certificates = { review }; + Object.assign(state, { activeAccountId: 'acct-a', smtpConfig: { host: 'smtp.x.com', port: 465, secure: true, username: 'me@x.com' } }); + mounted = render(); + typeInto(mounted.find('input[type="password"]'), 'pw'); + await submitForm(); + expect(review).toHaveBeenCalledWith('acct-a', 'smtp'); + expect(review.mock.invocationCallOrder[0]).toBeLessThan(connectSmtp.mock.invocationCallOrder.at(-1)!); + mounted.unmount(); + review.mockClear(); + state.imapConfig = { host: 'imap.gmail.com', username: 'me@gmail.com', authMethod: 'oauth2', oauthProvider: 'gmail' }; + mounted = render(); await submitForm(); - expect(connectSmtp).toHaveBeenCalledWith(expect.objectContaining({ authMethod: 'oauth2', allowInsecureTLS: undefined })); + expect(review).not.toHaveBeenCalled(); }); }); @@ -120,13 +147,30 @@ describe('ConnectionDialog (re-auth)', () => { // Breaks: re-entering a password turns a STARTTLS or None account into // implicit TLS on its old port (it sent `secure: true`), so it cannot - // reconnect, and drops the self-signed choice. - it('keeps the account\'s connection security and self-signed choice', async () => { + // reconnect. Changed deliberately (certificate pinning, CASA 4.1.2): this + // used to also keep the "allow self-signed" choice; the switch is retired, so + // the re-auth no longer sends it (main applies an approved certificate itself). + it('keeps the account\'s connection security, and drops the retired self-signed switch', async () => { state.imapConfig = { host: 'mail.x.com', port: 143, username: 'me@x.com', secure: false, security: 'none', allowInsecureTLS: true }; mounted = render(); typeInto(mounted.find('input[type="password"]'), 'new-pw'); await submitForm(); - expect(connect).toHaveBeenCalledWith(expect.objectContaining({ host: 'mail.x.com', port: 143, security: 'none', secure: false, allowInsecureTLS: true })); + expect(connect).toHaveBeenCalledWith(expect.objectContaining({ host: 'mail.x.com', port: 143, security: 'none', secure: false })); + expect((connect.mock.calls.at(-1) as unknown[])[0]).not.toHaveProperty('allowInsecureTLS'); + }); + + // CASA 4.1.2. Breaks: re-entering the password for a self-signed account can + // never ask about its certificate, or arms an id the connect does not run as. + it('arms main\'s certificate question for the account the connect runs as', async () => { + const review = vi.fn(async () => ({ success: true, data: { armed: true } })); + (window.electronAPI as unknown as { certificates: unknown }).certificates = { review }; + state.accounts = [{ id: 'acct-existing', email: 'me@x.com', imapConfig: { host: 'mail.x.com' } }]; + state.imapConfig = { host: 'mail.x.com', port: 993, username: 'me@x.com', secure: true }; + mounted = render(); + typeInto(mounted.find('input[type="password"]'), 'new-pw'); + await submitForm(); + expect(review).toHaveBeenCalledWith('acct-existing', 'imap'); + expect(review.mock.invocationCallOrder[0]).toBeLessThan(connect.mock.invocationCallOrder.at(-1)!); }); it('resolves a legacy account from `secure`', async () => { @@ -183,6 +227,35 @@ describe('ConnectionSecurityBanner', () => { expect(text()).toContain('Sending is refused the same way.'); }); + // CASA 4.1.2. Breaks: an untrusted certificate is headlined as "would not use + // encryption" — sending the user to the wrong setting (None). + it('headlines an untrusted certificate as such, for either server', () => { + Object.assign(state, { + connectionSecurityIssue: 'The incoming mail server x:993 presented a certificate Sarv Inbox does not trust …', + connectionSecurityCode: 'CERTIFICATE_UNTRUSTED', + smtpSecurityIssue: null, + connected: false, + }); + mounted = render(); + expect(text()).toContain("Not connected: the mail server's certificate is not trusted."); + expect(text()).not.toContain('would not use encryption'); + mounted.unmount(); + Object.assign(state, { connectionSecurityIssue: null, smtpSecurityIssue: 'The outgoing mail server y:465 presented a certificate …', smtpSecurityCode: 'CERTIFICATE_UNTRUSTED', connected: true }); + mounted = render(); + expect(text()).toContain("Can't send: the outgoing mail server's certificate is not trusted."); + }); + + // Breaks: two different refusals on the two servers read as "the same way". + it('spells out a sending refusal of a different kind', () => { + Object.assign(state, { + connectionSecurityIssue: 'incoming would not encrypt', connectionSecurityCode: 'STARTTLS_UNAVAILABLE', + smtpSecurityIssue: 'outgoing certificate not approved', smtpSecurityCode: 'CERTIFICATE_UNTRUSTED', connected: false, + }); + mounted = render(); + expect(text()).toContain('outgoing certificate not approved'); + expect(text()).not.toContain('Sending is refused the same way.'); + }); + // Breaks: dismissing one refusal hides a later, different one. it('comes back for a new refusal after being dismissed', () => { Object.assign(state, { connectionSecurityIssue: 'The incoming mail server x did not agree.', smtpSecurityIssue: null, connected: false }); diff --git a/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx b/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx index 6c212bdb..eefe8b1f 100644 --- a/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx +++ b/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx @@ -6,6 +6,7 @@ import { AddAccountModal } from '../../../../../src/components/AddAccountModal'; import { EmailSetupStep, type EmailSetupResult } from '../../../../../src/components/onboarding/EmailSetupStep'; import { EMAIL_PROVIDERS } from '../../../../../src/config/email-providers'; import { saveOnboardingEmailProgress } from '../../../../../src/services/onboarding-progress'; +import { accountIdFor } from '../../../../../src/store/helpers'; import type { EmailStore, StoredAccount } from '../../../../../src/store/types'; import { act, cleanup, fire, render, settle, toggle, typeInto, type Mounted } from '../../../../helpers/render'; @@ -234,7 +235,12 @@ describe('provider-first onboarding email', () => { }); // Regression: changing security must update ports and preserve first-class IMAP security. - it('uses chosen STARTTLS and explicit certificate settings', async () => { + // Changed deliberately (certificate pinning, CASA 4.1.2): this used to tick + // an "allow self-signed or invalid certificates" box and expect + // `allowInsecureTLS: true` on both configs. The box is gone: a server's own + // certificate is shown by main to approve during the connect, and the form + // sends no certificate setting at all. + it('uses chosen STARTTLS and sends no certificate setting', async () => { const view = render(); await choose(view, 'Other email'); enterManual(view); @@ -242,11 +248,35 @@ describe('provider-first onboarding email', () => { typeInto(view.byLabel('SMTP server'), 'smtp.private.example'); setSelect(view.byLabel('IMAP security'), 'starttls'); setSelect(view.byLabel('SMTP security'), 'starttls'); - toggle(view.find('details input[type="checkbox"]')); + expect(view.find('details input[type="checkbox"]')).toBeNull(); + expect(view.container.textContent).toContain('shows it to you to approve'); submit(view); await settle(); - expect(addAccount.mock.calls[0][0]).toMatchObject({ port: 143, secure: false, security: 'starttls', allowInsecureTLS: true }); - expect(connectSmtp.mock.calls[0][0]).toMatchObject({ port: 587, secure: false, security: 'starttls', allowInsecureTLS: true }); + expect(addAccount.mock.calls[0][0]).toMatchObject({ port: 143, secure: false, security: 'starttls' }); + expect(connectSmtp.mock.calls[0][0]).toMatchObject({ port: 587, secure: false, security: 'starttls' }); + expect(addAccount.mock.calls[0][0]).not.toHaveProperty('allowInsecureTLS'); + expect(connectSmtp.mock.calls[0][0]).not.toHaveProperty('allowInsecureTLS'); + }); + + // CASA 4.1.2. Breaks: main never asks about a self-signed server for the + // user's own "Test & connect" (the form does not arm the question), arms it + // for the wrong account or transport, or arms it after the connect; or the + // probe dials without the certificate approved for the account it is about + // to become. + it('arms main\'s certificate question for its own receiving and sending checks, before each', async () => { + const review = vi.fn(async () => ({ success: true, data: { armed: true } })); + (window.electronAPI as unknown as { certificates: unknown }).certificates = { review }; + const view = render(); + await choose(view, 'Other email'); + enterManual(view); + typeInto(view.byLabel('IMAP server'), 'imap.private.example'); + typeInto(view.byLabel('SMTP server'), 'smtp.private.example'); + submit(view); + await settle(); + expect(review).toHaveBeenNthCalledWith(1, accountIdFor('person@example.com', 'imap.private.example'), 'imap'); + expect(review.mock.invocationCallOrder[0]).toBeLessThan(addAccount.mock.invocationCallOrder[0]); + expect(review).toHaveBeenNthCalledWith(2, expect.any(String), 'smtp'); + expect(review.mock.invocationCallOrder[1]).toBeLessThan(connectSmtp.mock.invocationCallOrder[0]); }); // CASA M-5: sending can be set to None too, and the choice is sent as such. @@ -720,7 +750,9 @@ describe('adding another mailbox with the onboarding flow', () => { expect(view.container.textContent).toContain('configure in AI → Providers'); fire(button(view, 'Connect as second@sarv.example'), 'click'); await settle(); expect(startFlow).not.toHaveBeenCalled(); expect(mocks.confirm).not.toHaveBeenCalled(); - expect(probeCredentials).toHaveBeenCalledWith(expect.objectContaining({ username: 'second@sarv.example', authMethod: 'oauth2' })); + // Changed deliberately (certificate pinning): the probe now also names the + // account it is for, whose approved certificate main dials with. + expect(probeCredentials).toHaveBeenCalledWith(expect.objectContaining({ username: 'second@sarv.example', authMethod: 'oauth2' }), expect.any(String)); expect(addAccount).toHaveBeenCalledWith(expect.objectContaining({ username: 'second@sarv.example' }), { alreadyVerified: true }); expect(state.accounts).toHaveLength(2); expect(state.accounts.find((item) => item.id === 'existing-mail')?.email).toBe('person@sarv.example'); @@ -791,7 +823,7 @@ describe('adding another mailbox with the onboarding flow', () => { savedAccount(); const view = render(); await choose(view, 'Outlook'); enterManual(view, 'second@example.com'); toggle(view.byLabel('Set up sending later')); submit(view); await settle(); - expect(probeCredentials).toHaveBeenCalledWith(expect.objectContaining({ host: 'outlook.office365.com', password: ' a secret password ' })); + expect(probeCredentials).toHaveBeenCalledWith(expect.objectContaining({ host: 'outlook.office365.com', password: ' a secret password ' }), expect.any(String)); expect(addAccount).toHaveBeenCalledWith(expect.objectContaining({ username: 'second@example.com', password: ' a secret password ' }), { alreadyVerified: true }); expect(connectSmtp).not.toHaveBeenCalled(); expect(state.accounts).toHaveLength(2); expect(onClose).toHaveBeenCalledOnce(); }); diff --git a/apps/desktop/test/unit/src/components/onboarding/IMAPStep.test.tsx b/apps/desktop/test/unit/src/components/onboarding/IMAPStep.test.tsx index 5dc165fe..19086243 100644 --- a/apps/desktop/test/unit/src/components/onboarding/IMAPStep.test.tsx +++ b/apps/desktop/test/unit/src/components/onboarding/IMAPStep.test.tsx @@ -79,8 +79,12 @@ describe('first-run email connection', () => { // The choice itself (CASA M-5): `secure` alone stored STARTTLS and None alike. security: 'ssl', secure: true, - allowInsecureTLS: undefined, }); + // Changed deliberately (certificate pinning, CASA 4.1.2): the form used to + // send `allowInsecureTLS` from an "allow self-signed" box. The box is gone; + // main shows a server's own certificate to approve during the connect. + expect((addAccount.mock.calls[0] as unknown[])[0]).not.toHaveProperty('allowInsecureTLS'); + expect(view.find('input[type="checkbox"]')).toBeNull(); expect(connect).not.toHaveBeenCalled(); expect(onNext).toHaveBeenCalledOnce(); }); diff --git a/apps/desktop/test/unit/src/store/helpers.test.ts b/apps/desktop/test/unit/src/store/helpers.test.ts index 046b7223..f96266d1 100644 --- a/apps/desktop/test/unit/src/store/helpers.test.ts +++ b/apps/desktop/test/unit/src/store/helpers.test.ts @@ -643,10 +643,12 @@ describe('what the account write paths leave in localStorage', () => { }); }); -// Every vault entry now also records the transport relaxations chosen with the +// Every vault entry now also records the transport relaxation chosen with the // secret. Changed deliberately (transport binding): the expected entries that -// spread this used to be the bare secret and host. -const STRICT = { allowInsecureTLS: false, allowPlaintext: false }; +// spread this used to be the bare secret and host. Changed deliberately again +// (certificate pinning, CASA 4.1.2): `allowInsecureTLS: false` is gone — the +// "allow self-signed" switch is retired and never written. +const STRICT = { allowPlaintext: false }; describe('vaultEntryFor', () => { // Main only injects a saved secret for the host it was saved for. Breaks if @@ -657,11 +659,13 @@ describe('vaultEntryFor', () => { }); // Main sends a saved password no more loosely than it was saved for. Breaks - // if dropped: a self-signed or unencrypted account's password is saved - // strict and the account stops connecting the next time it reconnects. - it('carries the self-signed and no-encryption choices made with the secret', () => { + // if dropped: an unencrypted account's password is saved strict and the + // account stops connecting the next time it reconnects. Changed deliberately + // (certificate pinning): the retired self-signed switch is no longer carried + // — certificates are approved in main, never chosen by the window. + it('carries the no-encryption choice made with the secret, and never the retired self-signed switch', () => { expect(vaultEntryFor({ host: 'imap.x.com', password: 'p', allowInsecureTLS: true, security: 'none' })) - .toEqual({ password: 'p', host: 'imap.x.com', allowInsecureTLS: true, allowPlaintext: true }); + .toEqual({ password: 'p', host: 'imap.x.com', allowPlaintext: true }); // A legacy secure:false account is a required STARTTLS, not plaintext. expect(vaultEntryFor({ host: 'imap.x.com', password: 'p', secure: false })).toEqual({ password: 'p', host: 'imap.x.com', ...STRICT }); }); diff --git a/apps/desktop/test/unit/src/store/slices/connection-security-issue.test.ts b/apps/desktop/test/unit/src/store/slices/connection-security-issue.test.ts index 86d5c15e..5e37a8ff 100644 --- a/apps/desktop/test/unit/src/store/slices/connection-security-issue.test.ts +++ b/apps/desktop/test/unit/src/store/slices/connection-security-issue.test.ts @@ -226,3 +226,58 @@ describe('refusals follow the active account', () => { expect(state.smtpSecurityIssue ?? null).toBeNull(); }); }); + +// CASA 4.1.2: a connect refused over the server's certificate (main has +// already asked about it, and the user said no — or it could not be approved) +// is shown in the same banner, tagged so the banner says "certificate not +// trusted" rather than "would not use encryption". What breaks if these fail: +// the account sits on "Disconnected" with no reason, or the banner sends the +// user to the wrong setting. +describe('an untrusted certificate', () => { + const CERT = 'Sarv Inbox did not connect to mail.x.com:993 because the certificate it presents has not been approved. To review the certificate again, open Settings → Accounts and reconnect the account.'; + + it('keeps the message and its kind for the banner on connect, and clears both on success', async () => { + let refuse = true; + const { state } = await loadConnectionSlice(stubs(), api(async () => (refuse + ? { success: false, error: CERT, code: 'CERTIFICATE_UNTRUSTED' } + : { success: true }))); + const error = await state.connect(config).catch((e: unknown) => e as Error & { code?: string }); + expect(error).toMatchObject({ message: CERT, code: 'CERTIFICATE_UNTRUSTED' }); + expect(state.connectionSecurityIssue).toBe(CERT); + expect(state.connectionSecurityCode).toBe('CERTIFICATE_UNTRUSTED'); + expect(state.needsReauth).toBe(false); + refuse = false; + await state.connect(config); + expect(state.connectionSecurityIssue).toBeNull(); + }); + + it('keeps a sending refusal and its kind for the banner', async () => { + const { state } = await loadConnectionSlice({ activeAccountId: 'acct-a' }, { + smtp: { connect: vi.fn(async () => ({ success: false, error: CERT, code: 'CERTIFICATE_UNTRUSTED' })) }, + secureCreds: { set: vi.fn(async () => undefined) }, + }); + await expect(state.connectSmtp({ host: 'smtp.x.com', port: 465, username: 'me@x.com', password: 'pw', security: 'ssl', secure: true })).rejects.toThrow(CERT); + expect(state.smtpSecurityIssue).toBe(CERT); + expect(state.smtpSecurityCode).toBe('CERTIFICATE_UNTRUSTED'); + }); + + // Breaks: switching accounts leaves the old account's kind behind, so a + // later STARTTLS refusal on the new account is headlined as a certificate one. + it('drops the kind with the issue when the active account changes', async () => { + const { account } = await import('./connection-slice-harness'); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b')], + activeAccountId: 'acct-a', + connectionSecurityIssue: CERT, connectionSecurityCode: 'CERTIFICATE_UNTRUSTED', + smtpSecurityIssue: CERT, smtpSecurityCode: 'CERTIFICATE_UNTRUSTED', + loadFolders: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), loadQuota: vi.fn(), + startIdle: vi.fn(async () => {}), syncSingleFolder: vi.fn(async () => {}), + }, { + accounts: { setActive: vi.fn(async () => undefined) }, + imap: { isConnected: vi.fn(async () => ({ success: true, data: true })) }, + }); + await state.selectAccount('acct-b'); + expect(state.connectionSecurityCode ?? null).toBeNull(); + expect(state.smtpSecurityCode ?? null).toBeNull(); + }); +}); diff --git a/apps/desktop/test/unit/src/utils/certificate-review.test.ts b/apps/desktop/test/unit/src/utils/certificate-review.test.ts new file mode 100644 index 00000000..9516bc6b --- /dev/null +++ b/apps/desktop/test/unit/src/utils/certificate-review.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { allowCertificateReview, formatFingerprint } from '../../../../src/utils/certificate-review'; + +// What breaks if this file fails: a form the user submits to (re)connect no +// longer arms main's certificate question for that connect (so a self-signed +// server can never be approved), arms the wrong transport, or the arm throws +// and breaks the submit. + +const setApi = (api: unknown) => { (globalThis as unknown as { window: unknown }).window = { electronAPI: api }; }; +afterEach(() => { delete (globalThis as unknown as { window?: unknown }).window; }); + +describe('allowCertificateReview', () => { + // Breaks: the arm never reaches main, or names the wrong account or transport. + it('arms main\'s question for that account and transport', () => { + const review = vi.fn(async () => ({ success: true, data: { armed: true } })); + setApi({ certificates: { review } }); + allowCertificateReview('acct-a', 'imap'); + allowCertificateReview('acct-a', 'smtp'); + expect(review.mock.calls).toEqual([['acct-a', 'imap'], ['acct-a', 'smtp']]); + }); + + // Breaks: a missing account, an older main without the channel, or a failing + // IPC turns into an exception in the submit handler. + it('does nothing without an account, and never throws', async () => { + const review = vi.fn(async () => { throw new Error('no handler'); }); + setApi({ certificates: { review } }); + allowCertificateReview(null, 'imap'); + allowCertificateReview(undefined, 'smtp'); + expect(review).not.toHaveBeenCalled(); + expect(() => allowCertificateReview('acct-a', 'imap')).not.toThrow(); + setApi({}); + expect(() => allowCertificateReview('acct-a', 'imap')).not.toThrow(); + setApi({ certificates: { review: () => { throw new Error('sync'); } } }); + expect(() => allowCertificateReview('acct-a', 'imap')).not.toThrow(); + await Promise.resolve(); + }); +}); + +describe('formatFingerprint', () => { + // Breaks: the fingerprint is shown as one unbroken 95-character run nobody can compare. + it('groups a SHA-256 fingerprint in fours of eight pairs', () => { + const fp = Array.from({ length: 32 }, (_, i) => (i + 16).toString(16).toUpperCase()).join(':'); + const groups = formatFingerprint(fp); + expect(groups).toHaveLength(4); + expect(groups.join(':')).toBe(fp); + expect(groups[0].split(':')).toHaveLength(8); + }); +}); diff --git a/docs/TESTING.md b/docs/TESTING.md index 50a2156f..55de87d9 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -103,6 +103,17 @@ to test while the dev app holds the Electron ABI, from the package directory: The message used to tell everyone to run `pnpm test:node-abi`: the manual flip this section warns against, and backwards for a run inside Electron. +TLS behaviour is the other reason to run inside Electron. The shipped app's +Node is built on BoringSSL, CI's on OpenSSL, and they disagree about what +verifies (BoringSSL will not accept a self-signed `CA:FALSE` certificate as its +own trust anchor without `allowPartialTrustChain`). The certificate-pinning +suite runs real handshakes with throwaway certificates +(`packages/core/src/test-support/tls-test-servers.ts`); after touching +`resolveTlsOptions` or the inspection, run it both ways from `packages/core`: +`npx vitest run test/integration/utils/certificate-pin.integration.test.ts`, and +the same file with the Electron command above. It opens no database, so it does +not care which ABI the addon is on. + Two rebuilds must never run in the same directory at once: `node-gyp rebuild` starts by deleting `build/`, so a second run removes what the first is compiling into and both die on an ENOENT for a path that should exist diff --git a/packages/core/src/imap/connection-manager.ts b/packages/core/src/imap/connection-manager.ts index e3480ac1..f17b9b1d 100644 --- a/packages/core/src/imap/connection-manager.ts +++ b/packages/core/src/imap/connection-manager.ts @@ -450,7 +450,7 @@ export class ConnectionManager extends EventEmitter { this._authFailed = true; this._authFailedAt = Date.now(); this.emit('auth-error', error as Error); - } else if (this.isStartTlsUnavailableError(error)) { + } else if (this.isSecurityRefusalError(error)) { this.latchSecurityFailure(error as Error); } this.emit('error', error as Error); @@ -778,8 +778,10 @@ export class ConnectionManager extends EventEmitter { // auth (the next attempt is refused identically), but nothing was // sent and the credentials are fine — a one-line warning, not an // error with a stack per attempt. - if (this.isStartTlsUnavailableError(error)) { - logger.warn('Reconnect stopped: STARTTLS is required for this account but the server did not encrypt the session'); + if (this.isSecurityRefusalError(error)) { + logger.warn(this.isStartTlsUnavailableError(error) + ? 'Reconnect stopped: STARTTLS is required for this account but the server did not encrypt the session' + : 'Reconnect stopped: the server presented a certificate this account does not trust'); this._reconnectAttempts = 0; this.transition('error'); this.latchSecurityFailure(error as Error); @@ -1031,6 +1033,11 @@ export class ConnectionManager extends EventEmitter { return ImapErrors.isStartTlsUnavailableError(error); } + /** A STARTTLS refusal or an untrusted certificate: latched, never re-dialled (see isSecurityRefusalError). */ + isSecurityRefusalError(error: unknown): boolean { + return ImapErrors.isSecurityRefusalError(error); + } + isAuthError(error: unknown): boolean { return ImapErrors.isAuthError(error); } diff --git a/packages/core/src/imap/connection-pool.ts b/packages/core/src/imap/connection-pool.ts index 4756a05c..8908e039 100644 --- a/packages/core/src/imap/connection-pool.ts +++ b/packages/core/src/imap/connection-pool.ts @@ -5,7 +5,7 @@ import { errorDiagnostic } from '../utils/error-diagnostic'; import { logger } from '../utils/logger'; import { isTimeoutError, withTimeout } from '../utils/timeout'; -import { isConnectionError, isStartTlsUnavailableError } from './imap-errors'; +import { isConnectionError, isSecurityRefusalError, isStartTlsUnavailableError } from './imap-errors'; import { ImapFlowClient } from './imapflow-client'; // A pooled connection that has sat unused longer than this is REVALIDATED with a @@ -310,7 +310,7 @@ export class IMAPConnectionPool { // info so it doesn't read as a connect-error storm during a long drain. if (error instanceof PoolConnectionParkedError) { logger.info(`Pool: not opening a new connection — ${Math.round(error.remainingMs / 1000)}s of server-connection-cap back-off left`); - } else if (isStartTlsUnavailableError(error)) { + } else if (isSecurityRefusalError(error)) { // Already said once, when the pool latched it (createConnection). } else if (isConnectionError(error)) { // A TRANSIENT connect failure under load (Gmail rate/cap: "connect @@ -400,9 +400,11 @@ export class IMAPConnectionPool { // Let the owner park the account on a quota/timeout failure so the very // next pool acquire (and every other connect path) sees the gate closed. this.config.onConnectError?.(error); - if (isStartTlsUnavailableError(error) && !this.securityRefusal) { + if (isSecurityRefusalError(error) && !this.securityRefusal) { this.securityRefusal = error as Error; - logger.warn('Pool: the server did not encrypt a new connection (STARTTLS required) — no more pooled connections until the account reconnects'); + logger.warn(isStartTlsUnavailableError(error) + ? 'Pool: the server did not encrypt a new connection (STARTTLS required) — no more pooled connections until the account reconnects' + : 'Pool: the server presented a certificate this account does not trust — no more pooled connections until the account reconnects'); this.config.onSecurityError?.(error as Error); } throw error; diff --git a/packages/core/src/imap/imap-errors.ts b/packages/core/src/imap/imap-errors.ts index 657b1c3b..45473a7a 100644 --- a/packages/core/src/imap/imap-errors.ts +++ b/packages/core/src/imap/imap-errors.ts @@ -9,6 +9,7 @@ // must be backed off, not reconnected. import { isTerminalOAuthError, oauthTokenErrorOf } from '../oauth/oauth-errors'; +import { isCertificateUntrustedError } from '../utils/tls'; type AnyErr = Error & { code?: string; @@ -249,6 +250,19 @@ export function isStartTlsUnavailableError(error: unknown): boolean { return e.tlsFailed === true && /does not support STARTTLS/i.test(error.message); } +/** + * A connect the account's security settings refused before any credential was + * sent: a STARTTLS account whose server would not encrypt (CASA M-5), or a + * server whose certificate is not trusted (CASA 4.1.2 — no approved + * certificate, or not the approved one). Both are terminal until the user acts + * (changes the connection security, or approves a certificate in main), so the + * reconnect ladder and the pool latch them instead of dialling again; neither + * is an auth error (the password must not be forgotten). + */ +export function isSecurityRefusalError(error: unknown): boolean { + return isStartTlsUnavailableError(error) || isCertificateUntrustedError(error); +} + /** * Per-account connection-cap violation (e.g. Gmail's ~15 simultaneous * connections). Retrying immediately just adds another connect against a diff --git a/packages/core/src/imap/imapflow-client.ts b/packages/core/src/imap/imapflow-client.ts index 83111970..0db245a4 100644 --- a/packages/core/src/imap/imapflow-client.ts +++ b/packages/core/src/imap/imapflow-client.ts @@ -54,7 +54,7 @@ import { logger } from '../utils/logger'; import { messageIdKey } from '../utils/message-id'; import { createMutex, type Mutex } from '../utils/mutex'; import { withTimeout, withStallTimeout, isTimeoutError } from '../utils/timeout'; -import { resolveTlsOptions } from '../utils/tls'; +import { CERTIFICATE_UNTRUSTED, certificateUntrustedMessage, resolveTlsOptions, untrustedCertificateCode } from '../utils/tls'; import { acquireConnectionSlot, type ConnectionPriority } from './connection-budget'; import { GMAIL_NATIVE_CATEGORY_SLUGS, modifyGmailNativeCategories, type GmailNativeCategory } from './gmail-category-api'; @@ -301,8 +301,10 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { // maxIdleTime (10 min) so a healthy IDLE refresh always resets it first; // 13 min gives the refresh room without letting a wedged socket linger. socketTimeout: 13 * 60 * 1000, - // Certificate verification ON unless the account opted out (never for - // OAuth), plus the TLS 1.2 floor — the same resolver the SMTP client uses. + // Certificate verification is always on, with the TLS 1.2 floor; a pinned + // password account accepts exactly its approved certificate. The same + // resolver the SMTP client uses. Plain data on the config, so every + // pooled, background and reconnecting connection builds the same check. tls: resolveTlsOptions(config), }; @@ -312,6 +314,7 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { secure: options.secure, security: resolveConnectionSecurity(config), starttls: options.doSTARTTLS ? 'required' : options.secure ? 'n/a' : 'if offered', + certificate: options.tls?.ca ? 'approved certificate only' : 'system trust', }); const client = new ImapFlow(options); @@ -415,6 +418,14 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { if (isImapFlowStarttlsRefusal(err)) { throw new IMAPError(starttlsUnavailableMessage('incoming', config.host), STARTTLS_UNAVAILABLE, (err as Error).message); } + // The handshake refused the server's certificate (CASA 4.1.2): self-signed + // or from an unknown issuer with no approved certificate, or not the one + // the account approved. Settled until the user approves one, and the + // password was never sent — the same treatment as the STARTTLS refusal. + const certificateCode = untrustedCertificateCode(err); + if (certificateCode) { + throw new IMAPError(certificateUntrustedMessage('incoming', config.host, config.port), CERTIFICATE_UNTRUSTED, certificateCode); + } // The connect sequence runs several commands (CAPABILITY, LOGIN, ENABLE // QRESYNC/CONDSTORE, NAMESPACE, ID…). A bare "Command failed" hides WHICH // one — route through toImapError so the message carries the server's diff --git a/packages/core/src/imap/index.ts b/packages/core/src/imap/index.ts index a0ca89e5..b28956b8 100644 --- a/packages/core/src/imap/index.ts +++ b/packages/core/src/imap/index.ts @@ -83,6 +83,7 @@ export { isQuotaError, isRateLimited, isStartTlsUnavailableError, + isSecurityRefusalError, STARTTLS_UNAVAILABLE, getSuggestedBackoffMs, describeNetworkError, diff --git a/packages/core/src/imap/sync-engine.ts b/packages/core/src/imap/sync-engine.ts index 92ffce62..17ee277c 100644 --- a/packages/core/src/imap/sync-engine.ts +++ b/packages/core/src/imap/sync-engine.ts @@ -36,7 +36,7 @@ import { mapEnvelopeFields } from './envelope-mapper'; import { isFolderSyncEnabled, folderHeadersOnly } from './folder-sync-policy'; import { FolderSyncer, type FolderSyncResult } from './folder-syncer'; import type { AutocryptSink } from './header-stage'; -import { getSuggestedBackoffMs, isStartTlsUnavailableError } from './imap-errors'; +import { getSuggestedBackoffMs, isSecurityRefusalError } from './imap-errors'; import { fetchPaceFor, fetchSizeAfterFailure, nextFetchSize, type FetchPace } from './incremental-fetch'; import { isSarvHost } from './label-strategy'; import { MessageProcessor, isExpectedMessage, type IngestServerActions } from './message-processor'; @@ -2253,11 +2253,12 @@ export class SyncEngine { this.requeueBodyFetch(item); return 'connection_error'; } - // The server would not encrypt a new connection (CASA M-5). Not this - // message's fault: no strike, keep it queued, and stop draining — - // the account is now refused (no reconnects) until it connects - // again, which resumes the queue like any reconnect. - if (isStartTlsUnavailableError(error)) { + // The server would not encrypt a new connection (CASA M-5), or its + // certificate is not trusted (CASA 4.1.2). Not this message's fault: + // no strike, keep it queued, and stop draining — the account is now + // refused (no reconnects) until it connects again, which resumes the + // queue like any reconnect. + if (isSecurityRefusalError(error)) { this.requeueBodyFetch(item); return 'security_error'; } diff --git a/packages/core/src/smtp/smtp-client.ts b/packages/core/src/smtp/smtp-client.ts index 7ba1fa54..d52f24e9 100644 --- a/packages/core/src/smtp/smtp-client.ts +++ b/packages/core/src/smtp/smtp-client.ts @@ -8,7 +8,7 @@ import type { OutgoingMimeTransform, SMTPConfig, SendEmailOptions, SendResult } import { resolveConnectionSecurity, starttlsUnavailableMessage } from '../utils/connection-security'; import { failureCause } from '../utils/error-diagnostic'; import { createLogger } from '../utils/logger'; -import { resolveTlsOptions } from '../utils/tls'; +import { CERTIFICATE_UNTRUSTED, certificateUntrustedMessage, resolveTlsOptions, untrustedCertificateCode } from '../utils/tls'; import { isValidEmail, extractEmailAddress } from '../utils/validators'; const logger = createLogger('SMTPClient'); @@ -88,7 +88,8 @@ export class SMTPClient { */ async connect(config: SMTPConfig): Promise { const security = resolveConnectionSecurity(config); - logger.info('[SMTPClient] Connecting to SMTP server:', config.host, `(security: ${security})`); + const tlsOptions = resolveTlsOptions(config); + logger.info('[SMTPClient] Connecting to SMTP server:', config.host, `(security: ${security}, certificate: ${tlsOptions.ca ? 'approved certificate only' : 'system trust'})`); // This client is a reused singleton — smtp:connect re-calls connect() on // every (re)auth / token refresh. Close the previous transporter before @@ -127,15 +128,15 @@ export class SMTPClient { // for 'ssl'; for 'starttls' the upgrade is REQUIRED, so a server that will // not encrypt — or a network that strips STARTTLS — stops the session // before AUTH instead of sending the password or token in cleartext. Only - // the user's explicit 'none' upgrades opportunistically. allowInsecureTLS - // (self-signed certificates) no longer turns the requirement off: it - // relaxes certificate checks (resolveTlsOptions), not encryption. + // the user's explicit 'none' upgrades opportunistically. secure: security === 'ssl', requireTLS: security === 'starttls', opportunisticTLS: security === 'none', auth: auth as any, - // TLS verification ON by default + TLS 1.2 floor (see resolveTlsOptions). - tls: resolveTlsOptions(config), + // Verification always on + TLS 1.2 floor; a pinned password account + // accepts exactly its approved certificate (see resolveTlsOptions). + // nodemailer opens a fresh session per send, each with these options. + tls: tlsOptions, }); // Verify connection @@ -149,6 +150,16 @@ export class SMTPClient { logger.warn(`[SMTPClient] Refused: STARTTLS is required for ${config.host} but the server did not encrypt the session`); throw withStarttlsMessage(error as Error, config.host); } + // The handshake refused the server's certificate (CASA 4.1.2), before + // AUTH: settled until the user approves a certificate, never a blip. + const certificateCode = untrustedCertificateCode(error); + if (certificateCode) { + logger.warn(`[SMTPClient] Refused: the server's certificate is not trusted (${certificateCode})`); + throw Object.assign(new Error(certificateUntrustedMessage('outgoing', config.host, config.port)), { + code: CERTIFICATE_UNTRUSTED, + certificateFailure: certificateCode, + }); + } logger.error('[SMTPClient] Connection failed:', error); throw error; } diff --git a/packages/core/src/test-support/tls-test-servers.ts b/packages/core/src/test-support/tls-test-servers.ts new file mode 100644 index 00000000..c6556e9a --- /dev/null +++ b/packages/core/src/test-support/tls-test-servers.ts @@ -0,0 +1,279 @@ +/** + * Throwaway certificates and minimal TLS mail servers for tests (TEST SUPPORT + * ONLY). Lets the certificate-pinning tests run the REAL handshake — under plain + * Node (OpenSSL) and under Electron-as-Node (BoringSSL), which disagree about + * what verifies — against servers whose certificates the test controls, and + * check what the client wrote before and after the handshake. + * + * const cert = await makeSelfSigned(); + * const server = await startMailServer({ protocol: 'imap', mode: 'ssl', chain: cert.pem, key: cert.key }); + * // … connect to 127.0.0.1:server.port … + * expect(server.credentialCommands).toBe(0); + * await server.close(); + * + * The keys exist only in memory. Certificates are generated with + * @peculiar/x509 over WebCrypto (both runtimes provide it). + */ +import { webcrypto, X509Certificate } from 'node:crypto'; +import { createRequire } from 'node:module'; +import net from 'node:net'; +import tls from 'node:tls'; + +type KeyPair = webcrypto.CryptoKeyPair; + +const require = createRequire(import.meta.url); +require('reflect-metadata'); // must precede @peculiar/x509 (its DI needs the polyfill) +// eslint-disable-next-line @typescript-eslint/no-require-imports +const x509 = require('@peculiar/x509') as typeof import('@peculiar/x509'); +x509.cryptoProvider.set(webcrypto as never); + +const KEY_ALG = { name: 'ECDSA', namedCurve: 'P-256' } as const; +const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' } as const; +const DAY_MS = 86_400_000; + +export interface TestCertificate { + /** PEM, newline-terminated (concatenates into a chain). */ + pem: string; + /** PKCS#8 private key, PEM. */ + key: string; + /** Node's fingerprint256 of the certificate. */ + sha256: string; + /** For issuing (CA) and same-key renewals. */ + keys: KeyPair; + cert: import('@peculiar/x509').X509Certificate; +} + +let serial = 1; +const nextSerial = (): string => (serial++).toString(16).padStart(4, '0'); + +async function keyPem(key: webcrypto.CryptoKey): Promise { + const der = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', key)); + const lines = der.toString('base64').match(/.{1,64}/g) ?? []; + return `-----BEGIN PRIVATE KEY-----\n${lines.join('\n')}\n-----END PRIVATE KEY-----\n`; +} + +async function finish(cert: import('@peculiar/x509').X509Certificate, keys: KeyPair): Promise { + const pem = `${cert.toString('pem')}\n`; + return { pem, key: await keyPem(keys.privateKey), sha256: new X509Certificate(pem).fingerprint256, keys, cert }; +} + +const newKeys = async (): Promise => (await webcrypto.subtle.generateKey(KEY_ALG, true, ['sign', 'verify'])) as KeyPair; + +export interface SelfSignedOptions { + commonName?: string; + /** DNS names; default ['mail.internal']. */ + dnsNames?: string[]; + /** basicConstraints CA flag. Default false — the shape BoringSSL refuses as its own anchor without a partial chain. */ + ca?: boolean; + notBefore?: Date; + notAfter?: Date; + /** Reuse a key pair (a "renewed" certificate with the same key). */ + keys?: KeyPair; +} + +/** A self-signed server certificate. */ +export async function makeSelfSigned(options: SelfSignedOptions = {}): Promise { + const keys = options.keys ?? await newKeys(); + const now = Date.now(); + const cert = await x509.X509CertificateGenerator.createSelfSigned({ + serialNumber: nextSerial(), + name: `CN=${options.commonName ?? 'mail.internal'}`, + notBefore: options.notBefore ?? new Date(now - DAY_MS), + notAfter: options.notAfter ?? new Date(now + 365 * DAY_MS), + signingAlgorithm: SIGN_ALG, + keys, + extensions: [ + new x509.BasicConstraintsExtension(options.ca ?? false, undefined, true), + new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | (options.ca ? x509.KeyUsageFlags.keyCertSign : 0), true), + new x509.SubjectAlternativeNameExtension((options.dnsNames ?? ['mail.internal']).map((value) => ({ type: 'dns' as const, value }))), + ], + }); + return finish(cert, keys); +} + +/** A private (internal) certificate authority. */ +export async function makePrivateCa(commonName = 'Office Root CA'): Promise { + const keys = await newKeys(); + const now = Date.now(); + const cert = await x509.X509CertificateGenerator.createSelfSigned({ + serialNumber: nextSerial(), + name: `CN=${commonName}`, + notBefore: new Date(now - DAY_MS), + notAfter: new Date(now + 3650 * DAY_MS), + signingAlgorithm: SIGN_ALG, + keys, + extensions: [ + new x509.BasicConstraintsExtension(true, undefined, true), + new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), + ], + }); + return finish(cert, keys); +} + +/** A server certificate issued by `ca`. */ +export async function makeLeafFrom(ca: TestCertificate, options: { dnsNames?: string[] } = {}): Promise { + const keys = await newKeys(); + const now = Date.now(); + const cert = await x509.X509CertificateGenerator.create({ + serialNumber: nextSerial(), + subject: 'CN=mail.internal', + issuer: ca.cert.subject, + notBefore: new Date(now - DAY_MS), + notAfter: new Date(now + 365 * DAY_MS), + signingAlgorithm: SIGN_ALG, + publicKey: keys.publicKey, + signingKey: ca.keys.privateKey, + extensions: [ + new x509.BasicConstraintsExtension(false, undefined, true), + new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature, true), + new x509.ExtendedKeyUsageExtension(['1.3.6.1.5.5.7.3.1']), + new x509.SubjectAlternativeNameExtension((options.dnsNames ?? ['mail.internal']).map((value) => ({ type: 'dns' as const, value }))), + ], + }); + return finish(cert, keys); +} + +export interface MailServerOptions { + protocol: 'imap' | 'smtp'; + /** 'ssl' = TLS from the first byte; 'starttls' = plain greeting, then the upgrade. */ + mode: 'ssl' | 'starttls'; + /** The chain the server presents, PEM (leaf first). */ + chain: string; + key: string; +} + +export interface TestMailServer { + port: number; + /** How many LOGIN / AUTHENTICATE / AUTH commands arrived, before or after TLS. */ + readonly credentialCommands: number; + /** Everything clients wrote in plaintext (before any TLS), and inside TLS. */ + readonly plaintext: string; + readonly decrypted: string; + /** Handshakes that completed. */ + readonly handshakes: number; + close(): Promise; +} + +/** The command verb of an IMAP ("A1 LOGIN …") or SMTP ("AUTH PLAIN …") line. */ +const verbOf = (protocol: 'imap' | 'smtp', line: string): string => (line.split(' ')[protocol === 'imap' ? 1 : 0] ?? '').toUpperCase(); +const CREDENTIAL_VERBS = new Set(['LOGIN', 'AUTHENTICATE', 'AUTH']); + +/** + * A mail server just real enough for ImapFlow's and nodemailer's connect: it + * greets, answers CAPABILITY / EHLO / STARTTLS, accepts any LOGIN or AUTH, and + * says OK to everything else. It records every line, so a test can prove what + * a client sent — in particular that no credential command arrived when the + * handshake should have been refused. + */ +export async function startMailServer(options: MailServerOptions): Promise { + const secureContext = tls.createSecureContext({ cert: options.chain, key: options.key }); + const state = { credentialCommands: 0, plaintext: '', decrypted: '', handshakes: 0 }; + const sockets = new Set(); + + const serve = (socket: net.Socket, encrypted: boolean): void => { + let buffered = ''; + /** The tag (IMAP) or '' (SMTP) of an AUTH waiting for its SASL response line. */ + let authContinuation: string | null = null; + const send = (text: string) => { if (!socket.destroyed) socket.write(text); }; + const upgrade = () => { + socket.removeAllListeners('data'); + const secured = new tls.TLSSocket(socket, { isServer: true, secureContext }); + sockets.add(secured); + secured.on('error', () => { /* client refused our certificate */ }); + secured.on('secure', () => { state.handshakes++; }); + serve(secured, true); + }; + const onLine = (line: string) => { + if (encrypted) state.decrypted += `${line}\n`; else state.plaintext += `${line}\n`; + if (authContinuation !== null) { + const tag = authContinuation; + authContinuation = null; + send(options.protocol === 'imap' ? `${tag} OK authenticated\r\n` : '235 2.7.0 Authentication successful\r\n'); + return; + } + const command = verbOf(options.protocol, line); + if (CREDENTIAL_VERBS.has(command)) state.credentialCommands++; + if (options.protocol === 'imap') { + const tag = line.split(' ')[0] || '*'; + if (command === 'CAPABILITY') { + send(`* CAPABILITY IMAP4rev1 AUTH=PLAIN${encrypted ? '' : ' STARTTLS'}\r\n${tag} OK done\r\n`); + } else if (command === 'STARTTLS' && !encrypted) { + send(`${tag} OK begin TLS\r\n`); + upgrade(); + } else if (command === 'AUTHENTICATE' && line.split(' ').length < 4) { + authContinuation = tag; + send('+ \r\n'); + } else if (command === 'LIST') { + send(`* LIST (\\Noselect) "/" ""\r\n${tag} OK done\r\n`); + } else if (command === 'LOGOUT') { + send(`* BYE bye\r\n${tag} OK done\r\n`); + socket.end(); + } else { + send(`${tag} OK done\r\n`); + } + return; + } + if (command === 'EHLO') { + send(`250-mail.internal\r\n250-AUTH PLAIN LOGIN\r\n${encrypted ? '' : '250-STARTTLS\r\n'}250 OK\r\n`); + } else if (command === 'HELO') { + send('250 mail.internal\r\n'); + } else if (command === 'STARTTLS' && !encrypted) { + send('220 2.0.0 Ready to start TLS\r\n'); + upgrade(); + } else if (command === 'AUTH') { + if (line.split(' ').length < 3) { + authContinuation = ''; + send('334 \r\n'); + } else { + send('235 2.7.0 Authentication successful\r\n'); + } + } else if (command === 'QUIT') { + send('221 bye\r\n'); + socket.end(); + } else { + send('250 OK\r\n'); + } + }; + socket.on('data', (chunk: Buffer) => { + buffered += chunk.toString('latin1'); + for (let end = buffered.indexOf('\r\n'); end >= 0; end = buffered.indexOf('\r\n')) { + const line = buffered.slice(0, end); + buffered = buffered.slice(end + 2); + onLine(line); + if (socket.listenerCount('data') === 0) return; // upgraded: TLS owns the rest + } + }); + socket.on('error', () => { /* client went away */ }); + const greeting = options.protocol === 'imap' + ? `* OK [CAPABILITY IMAP4rev1 AUTH=PLAIN${encrypted || options.mode === 'ssl' ? '' : ' STARTTLS'}] ready\r\n` + : '220 mail.internal ESMTP ready\r\n'; + if (!encrypted || options.mode === 'ssl') send(greeting); + }; + + const server = options.mode === 'ssl' + ? tls.createServer({ cert: options.chain, key: options.key }, (socket) => { + state.handshakes++; + sockets.add(socket); + serve(socket, true); + }) + : net.createServer((socket) => { + sockets.add(socket); + serve(socket, false); + }); + // A client that rejects our certificate aborts the handshake; that is the point. + server.on('tlsClientError', () => { /* expected in refusal tests */ }); + server.on('error', () => { /* listener errors surface in the test */ }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as net.AddressInfo).port; + return { + port, + get credentialCommands() { return state.credentialCommands; }, + get plaintext() { return state.plaintext; }, + get decrypted() { return state.decrypted; }, + get handshakes() { return state.handshakes; }, + close: () => new Promise((resolve) => { + for (const socket of sockets) socket.destroy(); + server.close(() => resolve()); + }), + }; +} diff --git a/packages/core/src/types/imap.ts b/packages/core/src/types/imap.ts index c25ea79e..686fb5c8 100644 --- a/packages/core/src/types/imap.ts +++ b/packages/core/src/types/imap.ts @@ -1,4 +1,5 @@ import type { ConnectionSecurity } from '../utils/connection-security'; +import type { CertificatePin } from '../utils/tls'; // IMAP client interface for Sarv Inbox @@ -420,15 +421,15 @@ export interface IMAPConfig { */ resolveBearer?: (forceRefresh?: boolean) => Promise; /** - * Opt-in escape hatch for servers with self-signed / untrusted certs. - * Default (undefined/false) keeps TLS verification ON — disabling it exposes - * credentials and mail to man-in-the-middle attacks, so it must be an explicit - * per-account choice, never the default. - * Ignored for OAuth (resolveTlsOptions). For a saved password the main - * process injects, it is the choice saved WITH that password, not the - * config's (vault-credentials.ts). + * The certificate the user approved for this account's server (a pin), set + * by the MAIN process only, from the account's saved credentials + * (apps/desktop/electron/services/certificate-trust.ts). With it the + * connection accepts exactly that certificate and rejects every other one; + * without it, normal verification against the system trust store. Ignored + * for OAuth (resolveTlsOptions). Plain data, so it reaches every pooled and + * reconnecting connection with the rest of the config. */ - allowInsecureTLS?: boolean; + certificatePin?: CertificatePin; connectionTimeout?: number; // Milliseconds keepalive?: boolean; } diff --git a/packages/core/src/types/smtp.ts b/packages/core/src/types/smtp.ts index 8635fd68..350e7dee 100644 --- a/packages/core/src/types/smtp.ts +++ b/packages/core/src/types/smtp.ts @@ -1,6 +1,7 @@ // SMTP client interface for Sarv Inbox import type { ConnectionSecurity } from '../utils/connection-security'; +import type { CertificatePin } from '../utils/tls'; /** * SMTP configuration @@ -23,16 +24,15 @@ export interface SMTPConfig { accessToken?: string; from?: string; // Default "from" address /** - * Opt-in escape hatch for servers with self-signed / untrusted certs. - * Default (undefined/false) keeps TLS verification ON — disabling it exposes - * credentials and mail to man-in-the-middle attacks, so it must be an explicit - * per-account choice, never the default. It relaxes CERTIFICATE checks only; - * it never makes encryption optional (that is `security: 'none'`). - * Ignored for OAuth (resolveTlsOptions). For a saved password the main - * process injects, it is the choice saved WITH that password, not the - * config's (vault-credentials.ts). + * The certificate the user approved for this account's server (a pin), set + * by the MAIN process only, from the account's saved credentials + * (apps/desktop/electron/services/certificate-trust.ts). With it the + * connection accepts exactly that certificate and rejects every other one; + * without it, normal verification against the system trust store. Ignored + * for OAuth (resolveTlsOptions). Plain data, so it reaches every pooled and + * reconnecting connection with the rest of the config. */ - allowInsecureTLS?: boolean; + certificatePin?: CertificatePin; } /** diff --git a/packages/core/src/utils/certificate-inspection.ts b/packages/core/src/utils/certificate-inspection.ts new file mode 100644 index 00000000..48078393 --- /dev/null +++ b/packages/core/src/utils/certificate-inspection.ts @@ -0,0 +1,245 @@ +// Fetch the certificate a mail server presents, so the user can decide whether +// to trust it. Main-process only (node:net / node:tls). +// +// This is the ONE socket in Sarv Inbox that completes a TLS handshake without +// verifying it — it has to, to show the user a certificate the system does not +// trust. It is safe because it carries nothing: no credentials, no mail. For +// implicit TLS it writes nothing at all; for STARTTLS it writes only the +// protocol's own pre-TLS upgrade request (IMAP `STARTTLS`, SMTP `EHLO` + +// `STARTTLS`). It destroys the socket as soon as the handshake finishes, and its +// result is only ever SHOWN (main's approval dialog). Every connection that logs +// in verifies (resolveTlsOptions, tls.ts) — test/unit/utils/tls-guard.test.ts +// fails if `rejectUnauthorized` is set anywhere else. +import { X509Certificate } from 'node:crypto'; +import net from 'node:net'; +import tls from 'node:tls'; + +import type { ConnectionSecurity } from './connection-security'; +import { isTimeoutError, withTimeout } from './timeout'; + +/** One certificate as the approval dialog shows it and the pin stores it. */ +export interface PresentedCertificate { + /** PEM of the leaf, exactly as presented. */ + pem: string; + /** SHA-256 of its DER, Node's `fingerprint256` form. */ + sha256: string; + subject: string; + issuer: string; + /** As OpenSSL prints it, e.g. "Nov 27 10:00:00 2026 GMT". */ + validFrom: string; + validTo: string; + /** Epoch ms; NaN when unparseable. */ + notBefore: number; + notAfter: number; +} + +export interface CertificateInspection { + leaf: PresentedCertificate; + /** Whether the system trust store (and the hostname check) accepted it. */ + systemTrusted: boolean; + /** Node's code for why not (e.g. DEPTH_ZERO_SELF_SIGNED_CERT), or null. */ + systemError: string | null; +} + +export interface InspectTarget { + host: string; + port: number; + security: ConnectionSecurity; + protocol: 'imap' | 'smtp'; + /** The whole inspection, connect to handshake. Default 10 s. */ + timeoutMs?: number; +} + +export type CertificateInspectionFailure = 'unreachable' | 'no-starttls' | 'no-certificate' | 'too-slow'; + +/** Thrown when no certificate could be fetched. Its message names no host. */ +export class CertificateInspectionError extends Error { + constructor(message: string, public readonly reason: CertificateInspectionFailure) { + super(message); + this.name = 'CertificateInspectionError'; + } +} + +/** More than this before the upgrade is not a mail server this will read. */ +const MAX_PRE_TLS_BYTES = 64 * 1024; +const DEFAULT_TIMEOUT_MS = 10_000; + +/** The leaf as the dialog shows it. Throws when there is none. */ +export function describeCertificate(raw: Buffer | undefined): PresentedCertificate { + if (!Buffer.isBuffer(raw) || raw.length === 0) { + throw new CertificateInspectionError('The server presented no certificate', 'no-certificate'); + } + const x509 = new X509Certificate(raw); + return { + pem: x509.toString(), + sha256: x509.fingerprint256, + subject: x509.subject, + issuer: x509.issuer, + validFrom: x509.validFrom, + validTo: x509.validTo, + notBefore: Date.parse(x509.validFrom), + notAfter: Date.parse(x509.validTo), + }; +} + +/** Why a certificate cannot be trusted at `now` by date alone, or null. Unreadable dates count as expired. */ +export function certificateOutsideValidity( + cert: Pick, + now = Date.now(), +): 'expired' | 'not-yet-valid' | null { + if (!Number.isFinite(cert.notAfter) || now > cert.notAfter) return 'expired'; + if (!Number.isFinite(cert.notBefore) || now < cert.notBefore) return 'not-yet-valid'; + return null; +} + +/** + * CRLF lines from a plain socket. Bounded: a server that sends more than + * MAX_PRE_TLS_BYTES before the upgrade is refused. + */ +function lineReader(socket: net.Socket) { + let buffered = ''; + let total = 0; + const lines: string[] = []; + let waiter: { accept: (line: string) => boolean; resolve: (line: string) => void; reject: (e: Error) => void } | null = null; + let failure: Error | null = null; + + const pump = () => { + if (failure && waiter) { + waiter.reject(failure); + waiter = null; + return; + } + while (waiter && lines.length) { + const line = lines.shift()!; + if (waiter.accept(line)) { + const w = waiter; + waiter = null; + w.resolve(line); + } + } + }; + const fail = (error: Error) => { + failure ??= error; + pump(); + }; + const onData = (chunk: Buffer) => { + total += chunk.length; + if (total > MAX_PRE_TLS_BYTES) { + fail(new CertificateInspectionError('The server sent too much before encrypting', 'no-starttls')); + socket.destroy(); + return; + } + buffered += chunk.toString('latin1'); + for (let end = buffered.indexOf('\r\n'); end >= 0; end = buffered.indexOf('\r\n')) { + lines.push(buffered.slice(0, end)); + buffered = buffered.slice(end + 2); + } + pump(); + }; + const onEnd = () => fail(new CertificateInspectionError('The server closed before encrypting', 'no-starttls')); + socket.on('data', onData); + socket.on('end', onEnd); + socket.on('close', onEnd); + return { + /** The first line `accept` takes; lines before it are consumed. */ + next(accept: (line: string) => boolean): Promise { + return new Promise((resolve, reject) => { + waiter = { accept, resolve, reject }; + pump(); + }); + }, + /** Stop reading so TLS can take the socket over. */ + detach() { + socket.removeListener('data', onData); + socket.removeListener('end', onEnd); + socket.removeListener('close', onEnd); + waiter = null; + }, + }; +} + +/** The last line of an SMTP reply ("250 ok", not "250-PIPELINING"). */ +const smtpFinal = (line: string): boolean => line.length >= 3 && line[3] !== '-'; +const smtpCode = (line: string): string => line.slice(0, 3); + +/** Ask for the TLS upgrade. Nothing about the account is ever written. */ +async function negotiateStartTls(socket: net.Socket, protocol: 'imap' | 'smtp'): Promise { + const reader = lineReader(socket); + try { + if (protocol === 'imap') { + await reader.next((line) => line.startsWith('* ')); + socket.write('A1 STARTTLS\r\n'); + const reply = await reader.next((line) => line.startsWith('A1 ')); + if (!reply.toUpperCase().startsWith('A1 OK')) throw new CertificateInspectionError('The server refused STARTTLS', 'no-starttls'); + return; + } + if (smtpCode(await reader.next(smtpFinal)) !== '220') throw new CertificateInspectionError('The server did not greet', 'no-starttls'); + socket.write('EHLO localhost\r\n'); + if (smtpCode(await reader.next(smtpFinal)) !== '250') throw new CertificateInspectionError('The server refused EHLO', 'no-starttls'); + socket.write('STARTTLS\r\n'); + if (smtpCode(await reader.next(smtpFinal)) !== '220') throw new CertificateInspectionError('The server refused STARTTLS', 'no-starttls'); + } finally { + reader.detach(); + } +} + +const errnoCode = (e: unknown): string => (e as NodeJS.ErrnoException)?.code ?? 'error'; + +/** + * Connect to a mail server, complete the TLS handshake WITHOUT trusting it, and + * return the leaf certificate it presented, plus whether the system trust store + * would have accepted it. Never sends credentials (see the file comment). + */ +export async function inspectServerCertificate(target: InspectTarget): Promise { + const servername = net.isIP(target.host) ? undefined : target.host; + const sockets: net.Socket[] = []; + + const run = async (): Promise => { + let plain: net.Socket | undefined; + if (target.security !== 'ssl') { + const socket = net.connect({ host: target.host, port: target.port }); + // A late second error (after the one awaited below) must not become an + // uncaught 'error' event in the main process. + socket.on('error', () => { /* reported through the promise */ }); + sockets.push(socket); + plain = socket; + await new Promise((resolve, reject) => { + socket.once('connect', () => resolve()); + socket.once('error', (e) => reject(new CertificateInspectionError(`Could not reach the server (${errnoCode(e)})`, 'unreachable'))); + }); + await negotiateStartTls(socket, target.protocol); + } + return new Promise((resolve, reject) => { + const socket = tls.connect({ + ...(plain ? { socket: plain } : { host: target.host, port: target.port }), + servername, + // Inspection only — see the file comment. Nothing is written on this + // socket after the handshake, and it is destroyed right below. + rejectUnauthorized: false, + minVersion: 'TLSv1.2', + }); + socket.on('error', () => { /* reported through the promise */ }); + sockets.push(socket); + socket.once('secureConnect', () => { + try { + const leaf = describeCertificate(socket.getPeerCertificate(true)?.raw); + resolve({ leaf, systemTrusted: socket.authorized, systemError: socket.authorized ? null : String(socket.authorizationError ?? 'UNTRUSTED') }); + } catch (error) { + reject(error); + } finally { + socket.destroy(); + } + }); + socket.once('error', (e) => reject(new CertificateInspectionError(`Could not complete the handshake (${errnoCode(e)})`, 'unreachable'))); + }); + }; + + try { + return await withTimeout(run(), target.timeoutMs ?? DEFAULT_TIMEOUT_MS, 'The server took too long to present its certificate'); + } catch (error) { + if (isTimeoutError(error)) throw new CertificateInspectionError(error.message, 'too-slow'); + throw error; + } finally { + for (const socket of sockets) socket.destroy(); + } +} diff --git a/packages/core/src/utils/connection-security.ts b/packages/core/src/utils/connection-security.ts index 564bf555..b33388da 100644 --- a/packages/core/src/utils/connection-security.ts +++ b/packages/core/src/utils/connection-security.ts @@ -52,63 +52,55 @@ export function starttlsUnavailableMessage(server: 'incoming' | 'outgoing', host } /** - * The two ways a mail connection can be weaker than verified-and-encrypted: - * accepting a certificate nobody vouches for (`allowInsecureTLS`, for a - * self-signed server) and not requiring encryption at all (`security: 'none'`). - * Both are per-account choices the user makes in the account form. + * The one way a mail connection can be weaker than verified-and-encrypted: not + * requiring encryption at all (`security: 'none'`), a per-account choice the + * user makes in the account form. * - * Where a SAVED password is involved they are not the config's to make: the - * config comes from the window, which also renders untrusted email, so the + * There used to be a second one, accepting any certificate ("allow + * self-signed", `allowInsecureTLS`). It is gone (CASA 4.1.2): every connection + * verifies, and a server with its own certificate is trusted only for the exact + * certificate the user approved in main (resolveTlsOptions, tls.ts). A config's + * `allowInsecureTLS` is ignored everywhere. + * + * Where a SAVED password is involved the relaxation is not the config's to make: + * the config comes from the window, which also renders untrusted email, so the * choice is saved WITH the password in main's vault and applied from there * (apps/desktop/electron/services/vault-credentials.ts). */ export interface TransportOptIns { - allowInsecureTLS: boolean; allowPlaintext: boolean; } -/** Verified certificates, encryption required. */ -export const STRICT_TRANSPORT: Readonly = Object.freeze({ allowInsecureTLS: false, allowPlaintext: false }); +/** Encryption required. */ +export const STRICT_TRANSPORT: Readonly = Object.freeze({ allowPlaintext: false }); /** The parts of a config that ask for a weaker transport. */ -export interface TransportResolvable extends SecurityResolvable { - allowInsecureTLS?: unknown; -} +export type TransportResolvable = SecurityResolvable; -/** - * The relaxations a config asks for. Only the boolean `true` opts out of - * certificate checks, and an OAuth sign-in asks for neither (it always - * verifies and never goes unencrypted). - */ +/** The relaxation a config asks for. An OAuth sign-in never goes unencrypted. */ export function transportOptInsOf(config: TransportResolvable): TransportOptIns { - const oauth = config.authMethod === 'oauth2'; - return { - allowInsecureTLS: !oauth && config.allowInsecureTLS === true, - allowPlaintext: resolveConnectionSecurity(config) === 'none', - }; + return { allowPlaintext: resolveConnectionSecurity(config) === 'none' }; } -/** The first relaxation `requested` asks for that `granted` does not allow, or null. */ +/** The relaxation `requested` asks for that `granted` does not allow, or null. */ export function transportOptInBeyond( requested: TransportOptIns, granted: TransportOptIns, -): 'insecure-tls' | 'plaintext' | null { - if (requested.allowInsecureTLS && !granted.allowInsecureTLS) return 'insecure-tls'; - if (requested.allowPlaintext && !granted.allowPlaintext) return 'plaintext'; - return null; +): 'plaintext' | null { + return requested.allowPlaintext && !granted.allowPlaintext ? 'plaintext' : null; } /** - * The config with its transport limited to what `granted` allows: each - * relaxation applies only when the config asks for it AND it is granted, so a - * config can tighten what was granted but never loosen it. A 'none' that is - * not granted becomes a required STARTTLS on the same port. + * The config with its transport limited to what `granted` allows: 'none' applies + * only when the config asks for it AND it is granted, so a config can tighten + * what was granted but never loosen it. A 'none' that is not granted becomes a + * required STARTTLS on the same port. A legacy `allowInsecureTLS` is dropped. */ export function limitTransport(config: C, granted: TransportOptIns): C { + const { allowInsecureTLS: _ignored, ...rest } = config as C & { allowInsecureTLS?: unknown }; const requested = transportOptInsOf(config); return { - ...config, - allowInsecureTLS: requested.allowInsecureTLS && granted.allowInsecureTLS, + ...rest, ...(requested.allowPlaintext && !granted.allowPlaintext ? { security: 'starttls' } : {}), - }; + } as C; } diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index a1fab51d..0d55c75e 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -44,6 +44,7 @@ export * from './log-paths'; export * from './tags'; export * from './ai-actions'; export * from './tls'; +export * from './certificate-inspection'; export * from './connection-security'; export * from './filters'; export * from './ai-error'; diff --git a/packages/core/src/utils/tls.ts b/packages/core/src/utils/tls.ts index fc7f7053..0e46d5e5 100644 --- a/packages/core/src/utils/tls.ts +++ b/packages/core/src/utils/tls.ts @@ -1,40 +1,192 @@ -// Single source of truth for "should this connection verify its TLS cert?". -// Previously the `{ rejectUnauthorized: false }` decision was copy-pasted across -// the SMTP client, both IMAP/SMTP IPC handlers, and several UI config builders — -// which is exactly how an insecure default silently spreads. Centralize it so -// the secure-by-default policy lives in one place. +// Single source of truth for how a mail connection verifies its TLS certificate. +// The `{ rejectUnauthorized: false }` decision used to be copy-pasted across the +// SMTP client, both IMAP/SMTP IPC handlers, and several UI config builders — +// which is exactly how an insecure default silently spreads. Then it was one +// per-account switch ("allow self-signed") that accepted ANY certificate. Now +// there is no switch at all (CASA 4.1.2): every connection verifies, and a +// server with its own certificate is trusted only for the exact certificate the +// user approved for it (a pin). +import type { PeerCertificate } from 'node:tls'; -/** The subset of an IMAP/SMTP config that determines TLS verification. */ -export interface TlsResolvable { +/** + * A certificate the user approved for one server of one account. The main + * process stores it with the account's saved credentials and sets it on the + * connect config (apps/desktop/electron/services/certificate-trust.ts); the + * window can neither supply nor change it. + */ +export interface CertificatePin { /** - * Per-account opt-in for self-signed / untrusted certs. Default - * (undefined/false) → verification ON. Disabling exposes credentials and mail - * to man-in-the-middle attacks, so it must be a deliberate choice. + * SHA-256 of the approved LEAF certificate's DER encoding, in Node's + * `fingerprint256` form: 32 upper-case hex pairs joined by ':'. */ - allowInsecureTLS?: boolean; - /** 'oauth2' always verifies. */ + sha256: string; + /** The approved leaf certificate itself, PEM — the only trust anchor. */ + pem: string; +} + +/** The subset of an IMAP/SMTP config that decides TLS verification. */ +export interface TlsResolvable { + /** 'oauth2' never uses a pin: every provider has a publicly trusted certificate. */ authMethod?: string; + /** Set by the main process only, from the account's approved certificate. */ + certificatePin?: CertificatePin | null; +} + +/** What every mail connection hands to `tls.connect`. */ +export interface MailTlsOptions { + /** Always true: no mail connection runs with verification off. */ + rejectUnauthorized: true; + minVersion: 'TLSv1.2'; + /** With a pin: the approved certificate replaces the system trust store. */ + ca?: string[]; + /** + * With a pin: lets the approved certificate anchor the chain even when it is + * not a CA (a self-signed `CA:FALSE` leaf, or a leaf issued by a private CA). + * BoringSSL, which Electron's Node is built on, will not verify a `CA:FALSE` + * self-signed leaf against `ca: [leaf]` without it, where OpenSSL does — + * measured in test/integration/utils/certificate-pin.integration.test.ts. + */ + allowPartialTrustChain?: true; + /** With a pin: accepts exactly the approved leaf and nothing else. */ + checkServerIdentity?: (hostname: string, cert: PeerCertificate) => Error | undefined; +} + +/** The error code of a handshake refused because the leaf is not the approved one. */ +export const CERTIFICATE_PIN_MISMATCH = 'ERR_CERTIFICATE_PIN_MISMATCH'; + +const HEX_DIGITS = '0123456789ABCDEF'; + +/** + * A SHA-256 fingerprint in Node's `fingerprint256` form (upper-cased), or null + * when `value` is not one: 32 hex pairs joined by ':'. + */ +export function normalizeFingerprint(value: unknown): string | null { + if (typeof value !== 'string') return null; + const pairs = value.trim().toUpperCase().split(':'); + if (pairs.length !== 32) return null; + const valid = pairs.every((pair) => pair.length === 2 && HEX_DIGITS.includes(pair[0]) && HEX_DIGITS.includes(pair[1])); + return valid ? pairs.join(':') : null; +} + +/** + * The `checkServerIdentity` of a pinned connection. Node calls it during the + * handshake, after the chain verified against the approved certificate and + * before 'secureConnect', so a refusal here destroys the socket before ImapFlow + * or nodemailer can write LOGIN/AUTH on it. + * + * It accepts only a leaf whose SHA-256 is the pin. Only then does it skip the + * hostname check: a self-signed server's certificate rarely names the address + * the user connects to, and the pin is already bound to this account, server + * and port by the store that holds it. A pin that is not a well-formed + * fingerprint accepts nothing. + */ +export function pinnedServerIdentityCheck(pinSha256: string): (hostname: string, cert: PeerCertificate) => Error | undefined { + const expected = normalizeFingerprint(pinSha256); + return (_hostname, cert) => { + const presented = normalizeFingerprint(cert?.fingerprint256); + if (expected !== null && presented === expected) return undefined; + return Object.assign( + new Error('The server presented a certificate other than the one approved for this account'), + { code: CERTIFICATE_PIN_MISMATCH }, + ); + }; } /** - * Resolve the TLS options for a mail connection. Verification is ON unless the - * account has opted into `allowInsecureTLS` (the boolean `true` — a "true" - * string that round-tripped through storage does not count). Also pins a TLS - * 1.2 floor so the connection can never negotiate down to the broken SSLv3 / - * TLS 1.0 / 1.1 protocols, regardless of the runtime default. + * Resolve the TLS options for a mail connection. + * + * - Verification is always on (`rejectUnauthorized: true`), with a TLS 1.2 + * floor so the connection can never negotiate down to SSLv3 / TLS 1.0 / 1.1. + * - No pin: the system (Node) trust store and the normal hostname check. + * - A pin (password accounts only): the approved certificate is the ONLY + * trust anchor (`ca`), and `checkServerIdentity` accepts only that exact + * leaf. Every other certificate — another self-signed one, one a public CA + * issued, a renewed one — fails the handshake. * - * An OAuth sign-in always verifies: every provider has a publicly trusted + * An OAuth sign-in ignores any pin: every provider has a publicly trusted * certificate, so a config saying otherwise — stale, or sent by a compromised - * window — must not be able to hand the user's token to whoever answers. + * window — must not narrow or redirect what the user's token is sent to. * - * There is deliberately no per-config override (the old - * `tlsOptions.rejectUnauthorized` won over everything, and it travelled in from - * the renderer like the rest of the config). The main process decides - * `allowInsecureTLS` for every connection that carries a secret it injected. - */ -export function resolveTlsOptions( - config: TlsResolvable, -): { rejectUnauthorized: boolean; minVersion: 'TLSv1.2' } { - const insecure = config.allowInsecureTLS === true && config.authMethod !== 'oauth2'; - return { rejectUnauthorized: !insecure, minVersion: 'TLSv1.2' }; + * The old `allowInsecureTLS` opt-in and `tlsOptions.rejectUnauthorized` + * override are not read at all: nothing in a config can turn verification off. + */ +export function resolveTlsOptions(config: TlsResolvable): MailTlsOptions { + const pin = config.authMethod === 'oauth2' ? null : config.certificatePin; + if (!pin || typeof pin.pem !== 'string' || !pin.pem || typeof pin.sha256 !== 'string') { + return { rejectUnauthorized: true, minVersion: 'TLSv1.2' }; + } + return { + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + ca: [pin.pem], + allowPartialTrustChain: true, + checkServerIdentity: pinnedServerIdentityCheck(pin.sha256), + }; +} + +/** Error code of a connect refused because the server's certificate is not trusted. */ +export const CERTIFICATE_UNTRUSTED = 'CERTIFICATE_UNTRUSTED'; + +/** + * The handshake failures a user could resolve by approving the certificate the + * server presented (or that say it cannot be approved: expired, not yet valid). + * Node reports OpenSSL's and BoringSSL's verify results under these codes. + */ +const UNTRUSTED_CERTIFICATE_CODES: ReadonlySet = new Set([ + 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'SELF_SIGNED_CERT_IN_CHAIN', + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', + 'UNABLE_TO_GET_ISSUER_CERT', + 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', + 'UNABLE_TO_DECRYPT_CERT_SIGNATURE', + 'CERT_SIGNATURE_FAILURE', + 'CERT_UNTRUSTED', + 'CERT_REJECTED', + 'INVALID_CA', + 'CERT_HAS_EXPIRED', + 'CERT_NOT_YET_VALID', + 'ERR_TLS_CERT_ALTNAME_INVALID', + CERTIFICATE_PIN_MISMATCH, +]); + +type CodedError = { code?: unknown; originalCode?: unknown; cause?: unknown }; + +/** + * The certificate verification failure behind `error`, as its code, or null. + * Looks at the error's `code`, nodemailer's `originalCode` (it re-codes socket + * errors as ESOCKET) and the `cause` chain, a few levels deep. + */ +export function untrustedCertificateCode(error: unknown): string | null { + let current: unknown = error; + for (let depth = 0; depth < 5 && current && typeof current === 'object'; depth++) { + const e = current as CodedError; + for (const code of [e.code, e.originalCode]) { + if (typeof code === 'string' && UNTRUSTED_CERTIFICATE_CODES.has(code)) return code; + } + current = e.cause; + } + return null; +} + +/** + * True when a connect failed because the server's certificate is not trusted: + * either a client's re-worded refusal (code CERTIFICATE_UNTRUSTED) or the raw + * handshake error. Settled until the user approves a certificate, so it is + * neither a blip to retry nor a rejected password. + */ +export function isCertificateUntrustedError(error: unknown): boolean { + if (!error || typeof error !== 'object') return false; + if ((error as CodedError).code === CERTIFICATE_UNTRUSTED) return true; + return untrustedCertificateCode(error) !== null; +} + +/** + * The message for a connect refused over its certificate. Worded to stay clear + * of the transient-network and auth classifiers (no "socket", "timeout", + * "connection closed", "login failed", …): a settled fact, not a blip to retry + * and not a rejected password. + */ +export function certificateUntrustedMessage(server: 'incoming' | 'outgoing', host: string, port: number): string { + return `The ${server} mail server ${host}:${port} presented a certificate Sarv Inbox does not trust, ` + + 'so it stopped before sending your password. To review that certificate, open Settings → Accounts and reconnect the account.'; } diff --git a/packages/core/test/integration/utils/certificate-pin.integration.test.ts b/packages/core/test/integration/utils/certificate-pin.integration.test.ts new file mode 100644 index 00000000..677dfbdd --- /dev/null +++ b/packages/core/test/integration/utils/certificate-pin.integration.test.ts @@ -0,0 +1,360 @@ +/** + * Certificate pinning over REAL TLS (CASA 4.1.2): a connection with a pin + * accepts exactly the approved certificate and rejects every other one, before + * any credential is sent; without a pin, normal verification. + * + * Runs under plain Node (OpenSSL) in CI, and must also pass under Electron as + * Node (BoringSSL — what the shipped app runs on), from packages/core: + * + * ELECTRON_RUN_AS_NODE=1 ../../node_modules/.bin/electron ../../node_modules/vitest/vitest.mjs run test/integration/utils/certificate-pin.integration.test.ts + * + * The two TLS stacks disagree: BoringSSL will not verify a self-signed CA:FALSE + * leaf against `ca: [leaf]`, where OpenSSL does. That is why resolveTlsOptions + * sets `allowPartialTrustChain` — the "self-signed CA:FALSE" cases below are + * what fail under Electron without it. + */ +import tls from 'node:tls'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { IMAPConnectionPool } from '../../../src/imap/connection-pool'; +import { isSecurityRefusalError } from '../../../src/imap/imap-errors'; +import { ImapFlowClient } from '../../../src/imap/imapflow-client'; +import { SMTPClient } from '../../../src/smtp/smtp-client'; +import { + makeLeafFrom, + makePrivateCa, + makeSelfSigned, + startMailServer, + type TestCertificate, + type TestMailServer, +} from '../../../src/test-support/tls-test-servers'; +import { inspectServerCertificate } from '../../../src/utils/certificate-inspection'; +import { + CERTIFICATE_PIN_MISMATCH, + CERTIFICATE_UNTRUSTED, + isCertificateUntrustedError, + resolveTlsOptions, + type CertificatePin, +} from '../../../src/utils/tls'; + +const pinOf = (cert: TestCertificate): CertificatePin => ({ sha256: cert.sha256, pem: cert.pem }); +const PASSWORD = 'pinning-test-password-5f2a'; + +/** Handshake with a bare tls.connect using exactly the options a mail client gets. */ +async function handshake(chain: string, key: string, options: ReturnType): Promise<{ ok: true; fingerprint: string } | { ok: false; code: string }> { + const server = tls.createServer({ cert: chain, key }, (socket) => socket.end()); + server.on('tlsClientError', () => { /* the client refused us */ }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + return await new Promise((resolve) => { + const socket = tls.connect({ host: '127.0.0.1', port: (server.address() as { port: number }).port, servername: 'mail.internal', ...options }); + socket.once('secureConnect', () => { + resolve({ ok: true, fingerprint: socket.getPeerCertificate().fingerprint256 }); + socket.destroy(); + }); + socket.once('error', (error: NodeJS.ErrnoException) => resolve({ ok: false, code: String(error.code) })); + }); + } finally { + server.close(); + } +} + +let selfSignedLeaf: TestCertificate; // CA:FALSE — BoringSSL's hard case +let selfSignedCa: TestCertificate; // CA:TRUE — what `openssl req -x509` makes +let otherSelfSigned: TestCertificate; +let privateCa: TestCertificate; +let caLeaf: TestCertificate; +let siblingLeaf: TestCertificate; +let expired: TestCertificate; +let wrongName: TestCertificate; + +beforeAll(async () => { + selfSignedLeaf = await makeSelfSigned(); + selfSignedCa = await makeSelfSigned({ ca: true }); + otherSelfSigned = await makeSelfSigned(); + privateCa = await makePrivateCa(); + caLeaf = await makeLeafFrom(privateCa); + siblingLeaf = await makeLeafFrom(privateCa); + const now = Date.now(); + expired = await makeSelfSigned({ notBefore: new Date(now - 20 * 86_400_000), notAfter: new Date(now - 10 * 86_400_000) }); + wrongName = await makeSelfSigned({ commonName: 'other.example', dnsNames: ['other.example'] }); +}); + +describe('the TLS layer — what a pinned connection accepts', () => { + // Breaks: the approved self-signed server cannot be reached at all (the + // CA:FALSE case is the one BoringSSL refuses without allowPartialTrustChain). + it('accepts the pinned self-signed certificate, CA:FALSE or CA:TRUE', async () => { + for (const cert of [selfSignedLeaf, selfSignedCa]) { + await expect(handshake(cert.pem, cert.key, resolveTlsOptions({ certificatePin: pinOf(cert) }))) + .resolves.toEqual({ ok: true, fingerprint: cert.sha256 }); + } + }); + + // THE finding. Breaks: a pin trusts more than the one certificate — any + // self-signed certificate an attacker presents would be accepted. + it('rejects every other self-signed certificate', async () => { + const result = await handshake(otherSelfSigned.pem, otherSelfSigned.key, resolveTlsOptions({ certificatePin: pinOf(selfSignedLeaf) })); + expect(result.ok).toBe(false); + }); + + // Breaks: an internal server whose certificate comes from a private CA can't + // be pinned (the leaf is not self-signed), with or without the CA in the chain. + it('accepts a pinned leaf issued by a private CA, whether or not the server sends the CA', async () => { + const options = resolveTlsOptions({ certificatePin: pinOf(caLeaf) }); + await expect(handshake(caLeaf.pem, caLeaf.key, options)).resolves.toEqual({ ok: true, fingerprint: caLeaf.sha256 }); + await expect(handshake(caLeaf.pem + privateCa.pem, caLeaf.key, options)).resolves.toEqual({ ok: true, fingerprint: caLeaf.sha256 }); + }); + + // Breaks: pinning a leaf silently trusts everything its issuer signs. + it('rejects another certificate from the same private CA', async () => { + const result = await handshake(siblingLeaf.pem + privateCa.pem, siblingLeaf.key, resolveTlsOptions({ certificatePin: pinOf(caLeaf) })); + expect(result.ok).toBe(false); + }); + + // Breaks: a pin adds to the trust store instead of replacing it, so a + // certificate any trusted authority issued (or a mis-issued one) still works. + // The control proves the CA-issued certificate verifies when its CA is trusted. + it('rejects a CA-issued certificate when the account has a pin', async () => { + const trustingTheCa = { ...resolveTlsOptions({}), ca: [privateCa.pem] }; + await expect(handshake(caLeaf.pem + privateCa.pem, caLeaf.key, trustingTheCa)).resolves.toMatchObject({ ok: true }); + const pinned = await handshake(caLeaf.pem + privateCa.pem, caLeaf.key, resolveTlsOptions({ certificatePin: pinOf(selfSignedLeaf) })); + expect(pinned.ok).toBe(false); + }); + + // Breaks: a renewed certificate — new key, or the same key re-signed — is + // accepted without the user seeing it. Same key + same name is the case only + // the exact-fingerprint check catches. + it('rejects a renewed certificate, with a new key or the same one', async () => { + const pin = resolveTlsOptions({ certificatePin: pinOf(selfSignedCa) }); + const newKey = await makeSelfSigned({ ca: true }); + const sameKey = await makeSelfSigned({ ca: true, keys: selfSignedCa.keys, notAfter: new Date(Date.now() + 400 * 86_400_000) }); + expect(sameKey.sha256).not.toBe(selfSignedCa.sha256); + expect((await handshake(newKey.pem, newKey.key, pin)).ok).toBe(false); + expect((await handshake(sameKey.pem, sameKey.key, pin)).ok).toBe(false); + }); + + // Breaks: the fingerprint check runs only when the chain check passes — + // proven here on its own: with the chain check satisfied, a leaf that is not + // the pin is still refused with our code. + it('refuses a leaf that is not the pin even when the chain verifies', async () => { + const chainOk = { ...resolveTlsOptions({ certificatePin: pinOf(selfSignedLeaf) }), ca: [otherSelfSigned.pem] }; + await expect(handshake(otherSelfSigned.pem, otherSelfSigned.key, chainOk)).resolves.toEqual({ ok: false, code: CERTIFICATE_PIN_MISMATCH }); + }); + + // Breaks: an approved certificate that has since expired keeps working. + it('rejects a pinned certificate once it has expired', async () => { + await expect(handshake(expired.pem, expired.key, resolveTlsOptions({ certificatePin: pinOf(expired) }))) + .resolves.toEqual({ ok: false, code: 'CERT_HAS_EXPIRED' }); + }); + + // Breaks: a self-signed server whose certificate names another host (common: + // it was made for the machine name, the user types an IP) can't be pinned. + // The pin is bound to this host and port by the store that holds it. + it('ignores the certificate name for the pinned certificate only', async () => { + await expect(handshake(wrongName.pem, wrongName.key, resolveTlsOptions({ certificatePin: pinOf(wrongName) }))) + .resolves.toMatchObject({ ok: true }); + await expect(handshake(wrongName.pem, wrongName.key, { ...resolveTlsOptions({}), ca: [wrongName.pem], allowPartialTrustChain: true })) + .resolves.toEqual({ ok: false, code: 'ERR_TLS_CERT_ALTNAME_INVALID' }); + }); + + // Breaks: an unpinned connection accepts a self-signed certificate. + it('rejects a self-signed certificate with no pin', async () => { + expect((await handshake(selfSignedLeaf.pem, selfSignedLeaf.key, resolveTlsOptions({}))).ok).toBe(false); + }); + + // Breaks: an OAuth token goes to a server the user pinned (or a pin sent by a + // compromised window narrows an OAuth connection onto an attacker's cert). + it('ignores a pin on an OAuth connection', async () => { + const result = await handshake(selfSignedLeaf.pem, selfSignedLeaf.key, resolveTlsOptions({ authMethod: 'oauth2', certificatePin: pinOf(selfSignedLeaf) })); + expect(result.ok).toBe(false); + }); +}); + +const imapConfig = (port: number, extra: Record = {}) => ({ + host: '127.0.0.1', + port, + secure: true, + security: 'ssl' as const, + username: 'pin-user@mail.internal', + password: PASSWORD, + authMethod: 'password' as const, + connectionTimeout: 5000, + ...extra, +}); + +describe('IMAP (ImapFlow) — the pin reaches the socket, refusals come before LOGIN', () => { + const servers: TestMailServer[] = []; + const serve = async (mode: 'ssl' | 'starttls', cert: TestCertificate) => { + const server = await startMailServer({ protocol: 'imap', mode, chain: cert.pem, key: cert.key }); + servers.push(server); + return server; + }; + afterAll(async () => { await Promise.all(servers.map((s) => s.close())); }); + + for (const mode of ['ssl', 'starttls'] as const) { + // Breaks: the approved server cannot be used for mail. + it(`connects to the pinned server and logs in (${mode})`, async () => { + const server = await serve(mode, selfSignedLeaf); + const client = new ImapFlowClient(); + await client.connect(imapConfig(server.port, { security: mode, secure: mode === 'ssl', certificatePin: pinOf(selfSignedLeaf) })); + expect(server.credentialCommands).toBe(1); + await client.disconnect(); + }); + + // THE finding, end to end. Breaks: the password goes to a server presenting + // a certificate other than the approved one. + it(`refuses another certificate before sending LOGIN (${mode})`, async () => { + const server = await serve(mode, otherSelfSigned); + const client = new ImapFlowClient(); + const error = await client.connect(imapConfig(server.port, { security: mode, secure: mode === 'ssl', certificatePin: pinOf(selfSignedLeaf) })).catch((e) => e); + expect(error).toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + expect(isSecurityRefusalError(error)).toBe(true); + expect(server.credentialCommands).toBe(0); + expect(server.plaintext + server.decrypted).not.toContain(PASSWORD); + if (mode === 'starttls') expect(server.plaintext.split('\n').filter(Boolean).map((l) => l.split(' ')[1])).toEqual(['STARTTLS']); + }); + + // Breaks: a self-signed server with no approval is logged in to. + it(`refuses an unpinned self-signed certificate before LOGIN (${mode})`, async () => { + const server = await serve(mode, selfSignedLeaf); + const client = new ImapFlowClient(); + const error = await client.connect(imapConfig(server.port, { security: mode, secure: mode === 'ssl' })).catch((e) => e); + expect(isCertificateUntrustedError(error)).toBe(true); + expect(server.credentialCommands).toBe(0); + }); + } + + // Breaks: an old "allow self-signed" account keeps connecting to anything — + // the opt-in must be inert now (CASA 4.1.2 migration). + it('ignores the retired allowInsecureTLS opt-in', async () => { + const server = await serve('ssl', selfSignedLeaf); + const error = await new ImapFlowClient().connect(imapConfig(server.port, { allowInsecureTLS: true })).catch((e) => e); + expect(isCertificateUntrustedError(error)).toBe(true); + expect(server.credentialCommands).toBe(0); + }); + + // Breaks: pooled (background-role) connections dial without the pin, so + // sync/backfill either fails against the approved server or — worse — runs + // with weaker checks than the primary. Functions don't survive cloning, so + // the pin travels as data and each socket builds its own check. + it('carries the pin into every pooled connection', async () => { + const server = await serve('ssl', selfSignedLeaf); + const pool = new IMAPConnectionPool({ maxConnections: 2, connectionTimeout: 5000, idleTimeout: 60_000 }); + const config = imapConfig(server.port, { certificatePin: pinOf(selfSignedLeaf) }); + await pool.initialize(config); + const first = await pool.acquire(); + const second = await pool.acquire(); + expect(server.credentialCommands).toBe(2); + first.release(); + second.release(); + await pool.close(); + }); + + // Breaks: a pool keeps dialling (one refused connect per queued item) against + // a server whose certificate changed, instead of latching the refusal. + it('latches a pooled certificate refusal and reports it once', async () => { + const server = await serve('ssl', otherSelfSigned); + const refusals: Error[] = []; + const pool = new IMAPConnectionPool({ maxConnections: 2, connectionTimeout: 5000, idleTimeout: 60_000, onSecurityError: (e) => refusals.push(e) }); + // A permanent refusal surfaces from the warm-up (as a bad password does)… + await expect(pool.initialize(imapConfig(server.port, { certificatePin: pinOf(selfSignedLeaf) }))) + .rejects.toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + // …and later acquires get the latched refusal without dialling again. + await expect(pool.acquire()).rejects.toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + await expect(pool.acquire()).rejects.toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + expect(refusals).toHaveLength(1); + expect(server.credentialCommands).toBe(0); + await pool.close(); + }); +}); + +const smtpConfig = (port: number, extra: Record = {}) => ({ + host: '127.0.0.1', + port, + secure: true, + security: 'ssl' as const, + username: 'pin-user@mail.internal', + password: PASSWORD, + authMethod: 'password' as const, + ...extra, +}); + +describe('SMTP (nodemailer) — the pin reaches the socket, refusals come before AUTH', () => { + const servers: TestMailServer[] = []; + const serve = async (mode: 'ssl' | 'starttls', cert: TestCertificate) => { + const server = await startMailServer({ protocol: 'smtp', mode, chain: cert.pem, key: cert.key }); + servers.push(server); + return server; + }; + afterAll(async () => { await Promise.all(servers.map((s) => s.close())); }); + + for (const mode of ['ssl', 'starttls'] as const) { + // Breaks: mail to a self-signed sending server the user approved can't be sent. + it(`connects to the pinned server and authenticates (${mode})`, async () => { + const server = await serve(mode, selfSignedLeaf); + const client = new SMTPClient(); + await client.connect(smtpConfig(server.port, { security: mode, secure: mode === 'ssl', certificatePin: pinOf(selfSignedLeaf) })); + expect(server.credentialCommands).toBe(1); + await client.disconnect(); + }); + + // Breaks: the sending password goes to a server presenting another certificate. + it(`refuses another certificate before AUTH (${mode})`, async () => { + const server = await serve(mode, otherSelfSigned); + const error = await new SMTPClient().connect(smtpConfig(server.port, { security: mode, secure: mode === 'ssl', certificatePin: pinOf(selfSignedLeaf) })).catch((e) => e); + expect(error).toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + expect(server.credentialCommands).toBe(0); + expect(server.plaintext + server.decrypted).not.toContain(PASSWORD); + if (mode === 'starttls') expect(server.plaintext.split('\n').filter(Boolean).map((l) => l.split(' ')[0])).toEqual(['EHLO', 'STARTTLS']); + }); + } + + // Breaks: an unpinned self-signed sending server is sent the password, or the + // retired opt-in still turns verification off. + it('refuses an unpinned self-signed certificate, opt-in or not', async () => { + const server = await serve('ssl', selfSignedLeaf); + for (const extra of [{}, { allowInsecureTLS: true }]) { + const error = await new SMTPClient().connect(smtpConfig(server.port, extra)).catch((e) => e); + expect(error).toMatchObject({ code: CERTIFICATE_UNTRUSTED }); + } + expect(server.credentialCommands).toBe(0); + }); +}); + +describe('inspectServerCertificate — fetching what the user is asked to approve', () => { + const servers: TestMailServer[] = []; + afterAll(async () => { await Promise.all(servers.map((s) => s.close())); }); + + for (const protocol of ['imap', 'smtp'] as const) { + for (const mode of ['ssl', 'starttls'] as const) { + // Breaks: the approval dialog can't show (or shows the wrong) certificate, + // or the inspection itself sends something about the account. + it(`returns the presented leaf and sends no credentials (${protocol}, ${mode})`, async () => { + const server = await startMailServer({ protocol, mode, chain: caLeaf.pem + privateCa.pem, key: caLeaf.key }); + servers.push(server); + const inspection = await inspectServerCertificate({ host: '127.0.0.1', port: server.port, security: mode, protocol }); + expect(inspection.leaf.sha256).toBe(caLeaf.sha256); + expect(inspection.leaf.pem.trim()).toBe(caLeaf.pem.trim()); + expect(inspection.leaf.subject).toContain('CN=mail.internal'); + expect(inspection.leaf.issuer).toContain('CN=Office Root CA'); + expect(inspection.systemTrusted).toBe(false); + expect(inspection.systemError).toBeTruthy(); + expect(server.credentialCommands).toBe(0); + expect(server.decrypted).toBe(''); + }); + } + } + + // Breaks: what was inspected and what is then pinned differ — the pin made + // from an inspection must open the very same server. + it('yields a pin that the real client accepts', async () => { + const server = await startMailServer({ protocol: 'imap', mode: 'ssl', chain: selfSignedLeaf.pem, key: selfSignedLeaf.key }); + servers.push(server); + const { leaf } = await inspectServerCertificate({ host: '127.0.0.1', port: server.port, security: 'ssl', protocol: 'imap' }); + const client = new ImapFlowClient(); + await client.connect(imapConfig(server.port, { certificatePin: { sha256: leaf.sha256, pem: leaf.pem } })); + expect(server.credentialCommands).toBe(1); + await client.disconnect(); + }); +}); diff --git a/packages/core/test/unit/imap/imap-errors.test.ts b/packages/core/test/unit/imap/imap-errors.test.ts index 4c885fb1..ba82af61 100644 --- a/packages/core/test/unit/imap/imap-errors.test.ts +++ b/packages/core/test/unit/imap/imap-errors.test.ts @@ -10,9 +10,11 @@ import { isQuotaError, isRateLimited, isUpstreamError, + isSecurityRefusalError, isStartTlsUnavailableError, STARTTLS_UNAVAILABLE, } from '../../../src/imap/imap-errors'; +import { CERTIFICATE_UNTRUSTED } from '../../../src/utils/tls'; // These classifiers decide whether a failure is RETRIED, RECONNECTED, BACKED OFF // or dead-lettered — every past misclassification here turned into either a @@ -392,3 +394,21 @@ describe('isStartTlsUnavailableError (CASA M-5)', () => { expect(isQuotaError(refusal)).toBe(false); }); }); + +describe('isSecurityRefusalError (CASA M-5 + 4.1.2)', () => { + // Breaks: an untrusted certificate is re-dialled by the reconnect ladder and + // the pool (one refused handshake per queued item) instead of being latched + // until the user approves a certificate, exactly as a STARTTLS refusal is. + it('matches a STARTTLS refusal and an untrusted certificate, raw or re-worded', () => { + expect(isSecurityRefusalError(Object.assign(new Error('x'), { code: STARTTLS_UNAVAILABLE }))).toBe(true); + expect(isSecurityRefusalError(Object.assign(new Error('x'), { code: CERTIFICATE_UNTRUSTED }))).toBe(true); + expect(isSecurityRefusalError(Object.assign(new Error('self-signed certificate'), { code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }))).toBe(true); + }); + + // Breaks: a network blip or a rejected password latches the account as refused. + it('does not match a blip, an auth failure or a non-error', () => { + expect(isSecurityRefusalError(Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }))).toBe(false); + expect(isSecurityRefusalError(new Error('Invalid credentials'))).toBe(false); + expect(isSecurityRefusalError(undefined)).toBe(false); + }); +}); diff --git a/packages/core/test/unit/imap/imapflow-client-starttls.test.ts b/packages/core/test/unit/imap/imapflow-client-starttls.test.ts index 53004ab0..bc108203 100644 --- a/packages/core/test/unit/imap/imapflow-client-starttls.test.ts +++ b/packages/core/test/unit/imap/imapflow-client-starttls.test.ts @@ -29,7 +29,8 @@ vi.mock('imapflow', () => ({ ImapFlow: FakeFlow })); const { ImapFlowClient } = await import('../../../src/imap/imapflow-client'); const { __resetConnectionBudgets } = await import('../../../src/imap/connection-budget'); -const { isStartTlsUnavailableError, isConnectionError, isAuthError, STARTTLS_UNAVAILABLE } = await import('../../../src/imap/imap-errors'); +const { isStartTlsUnavailableError, isSecurityRefusalError, isConnectionError, isAuthError, STARTTLS_UNAVAILABLE } = await import('../../../src/imap/imap-errors'); +const { CERTIFICATE_UNTRUSTED, certificateUntrustedMessage } = await import('../../../src/utils/tls'); const cfg = (over: Record = {}) => ({ host: 'mail.example.org', port: 143, secure: false, @@ -60,15 +61,30 @@ describe('ImapFlowClient — connection security options', () => { // IMAP client goes back to reading its own override (which arrived from the // renderer and switched verification off for a saved password or an OAuth // token), or drops the TLS 1.2 floor it used to lose on the way to ImapFlow. +// +// Changed deliberately (certificate pinning, CASA 4.1.2): 'an account that +// opted out' used to expect verification OFF for `allowInsecureTLS: true`. The +// opt-in is retired — nothing turns verification off — so every row now +// verifies, and a pinned account gets the approved certificate as its only +// anchor plus the exact-leaf check. describe('ImapFlowClient — certificate verification', () => { it.each([ - ['a default account', {}, true], - ['an account that opted out', { allowInsecureTLS: true }, false], - ['an OAuth account whose config opts out', { allowInsecureTLS: true, authMethod: 'oauth2', oauthProvider: 'gmail', accessToken: 't' }, true], - ['a config carrying the old override', { tlsOptions: { rejectUnauthorized: false } }, true], - ])('verifies for %s exactly when it should, with the TLS 1.2 floor', async (_label, over, verifies) => { + ['a default account', {}], + ['an account carrying the retired opt-in', { allowInsecureTLS: true }], + ['an OAuth account whose config opts out', { allowInsecureTLS: true, authMethod: 'oauth2', oauthProvider: 'gmail', accessToken: 't' }], + ['a config carrying the old override', { tlsOptions: { rejectUnauthorized: false } }], + ['an OAuth account carrying a pin', { certificatePin: { sha256: 'AB', pem: 'PEM' }, authMethod: 'oauth2', oauthProvider: 'gmail', accessToken: 't' }], + ])('verifies against the system trust store for %s, with the TLS 1.2 floor', async (_label, over) => { await new ImapFlowClient().connect(cfg(over) as never); - expect(lastOptions?.tls).toEqual({ rejectUnauthorized: verifies, minVersion: 'TLSv1.2' }); + expect(lastOptions?.tls).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); + }); + + // Breaks: a pinned password account's connection is built without its pin, + // so it either can't reach the approved server or trusts something else. + it('hands a pinned password account exactly its approved certificate', async () => { + await new ImapFlowClient().connect(cfg({ certificatePin: { sha256: 'AB', pem: 'PEM' } }) as never); + expect(lastOptions?.tls).toMatchObject({ rejectUnauthorized: true, minVersion: 'TLSv1.2', ca: ['PEM'], allowPartialTrustChain: true }); + expect(typeof (lastOptions?.tls as { checkServerIdentity?: unknown }).checkServerIdentity).toBe('function'); }); }); @@ -98,11 +114,41 @@ describe('ImapFlowClient — a required STARTTLS the server will not do', () => }); // A certificate failure after an accepted upgrade is a different problem: - // None would not help, so it must not be told to switch. - it('leaves other TLS failures as connection errors', async () => { + // None would not help, so it must not be told to switch. Changed deliberately + // (certificate pinning, CASA 4.1.2): it used to stay a generic + // CONNECTION_ERROR, which the reconnect ladder retried forever; it is now its + // own settled refusal (see the next block). + it('does not report a certificate failure as a STARTTLS refusal', async () => { connectImpl = async () => { throw Object.assign(new Error('self-signed certificate'), { tlsFailed: true, code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }); }; const error = await new ImapFlowClient().connect(cfg() as never).catch((e: unknown) => e as Error & { code?: string }); - expect(error.code).toBe('CONNECTION_ERROR'); + expect(error.code).not.toBe(STARTTLS_UNAVAILABLE); expect(error.message).not.toContain('Connection security'); }); + + // Breaks: any non-certificate TLS failure (a protocol alert) is mistaken for + // a certificate the user could approve, and an approval dialog opens for it. + it('leaves other TLS failures as connection errors', async () => { + connectImpl = async () => { throw Object.assign(new Error('wrong version number'), { code: 'ERR_SSL_WRONG_VERSION_NUMBER' }); }; + const error = await new ImapFlowClient().connect(cfg() as never).catch((e: unknown) => e as Error & { code?: string }); + expect(error.code).toBe('CONNECTION_ERROR'); + }); +}); + +// CASA 4.1.2. Breaks: a certificate refusal is retried by the reconnect ladder +// as a network blip, forgotten as a bad password, or shown with no way forward. +describe('ImapFlowClient — a certificate the account does not trust', () => { + it.each(['DEPTH_ZERO_SELF_SIGNED_CERT', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'SELF_SIGNED_CERT_IN_CHAIN', 'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_HAS_EXPIRED', 'ERR_CERTIFICATE_PIN_MISMATCH'])( + 'turns %s into a CERTIFICATE_UNTRUSTED refusal that says what to do, and closes the socket', + async (code) => { + connectImpl = async () => { throw Object.assign(new Error('certificate problem'), { code }); }; + const error = await new ImapFlowClient().connect(cfg() as never).catch((e: unknown) => e as Error & { code?: string; serverResponse?: string }); + expect(error.code).toBe(CERTIFICATE_UNTRUSTED); + expect(error.serverResponse).toBe(code); + expect(error.message).toBe(certificateUntrustedMessage('incoming', 'mail.example.org', 143)); + expect(isSecurityRefusalError(error)).toBe(true); + expect(isConnectionError(error)).toBe(false); + expect(isAuthError(error)).toBe(false); + expect(closed).toBe(1); + }, + ); }); diff --git a/packages/core/test/unit/smtp/smtp-client.test.ts b/packages/core/test/unit/smtp/smtp-client.test.ts index 18205357..b8b86e91 100644 --- a/packages/core/test/unit/smtp/smtp-client.test.ts +++ b/packages/core/test/unit/smtp/smtp-client.test.ts @@ -45,7 +45,8 @@ vi.mock('nodemailer', () => ({ // Imported AFTER the mock so the client picks up the stubbed transport. const { SMTPClient, smtpClient } = await import('../../../src/smtp/smtp-client'); -const { OutgoingMimeError } = await import('../../../src/smtp/smtp-errors'); +const { OutgoingMimeError, isStarttlsRefusedError } = await import('../../../src/smtp/smtp-errors'); +const { CERTIFICATE_UNTRUSTED, certificateUntrustedMessage } = await import('../../../src/utils/tls'); const baseConfig = (over: Partial = {}): SMTPConfig => ({ host: 'smtp.sarv.com', @@ -108,28 +109,38 @@ describe('SMTPClient.connect — transport + TLS policy', () => { expect(opts.tls.rejectUnauthorized).toBe(true); // still verified }); - // Verification may only be dropped by an EXPLICIT per-account opt-in — never - // as a side effect of anything else. Changed deliberately (CASA M-5): the - // opt-in used to turn the STARTTLS requirement off as well, so ticking "allow - // self-signed certificates" let anyone on the network strip STARTTLS and - // read the password. It relaxes certificate checks only now. - it('only disables certificate verification on the explicit allowInsecureTLS opt-in, and still requires STARTTLS', async () => { + // Changed deliberately (certificate pinning, CASA 4.1.2): this used to pin + // that the explicit `allowInsecureTLS` opt-in turned verification OFF (while + // still requiring STARTTLS, CASA M-5). The opt-in is retired: nothing turns + // verification off. Breaks: an old "allow self-signed" account keeps sending + // its password to whatever certificate answers. + it('ignores the retired allowInsecureTLS opt-in: still verifies, still requires STARTTLS', async () => { const client = new SMTPClient(); await client.connect(baseConfig({ port: 587, secure: false, allowInsecureTLS: true })); - expect(lastTransportOptions().tls.rejectUnauthorized).toBe(false); + expect(lastTransportOptions().tls).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); expect(lastTransportOptions().requireTLS).toBe(true); }); + // Breaks: a pinned sending account's transport is built without its pin. + it('hands a pinned password account exactly its approved certificate', async () => { + const client = new SMTPClient(); + await client.connect(baseConfig({ certificatePin: { sha256: 'AB', pem: 'PEM' } })); + expect(lastTransportOptions().tls).toMatchObject({ rejectUnauthorized: true, minVersion: 'TLSv1.2', ca: ['PEM'], allowPartialTrustChain: true }); + expect(typeof lastTransportOptions().tls.checkServerIdentity).toBe('function'); + }); + // Changed deliberately (renderer-supplied TLS relaxation): the second half of // the test above used to pin that `tlsOptions` overrode the opt-in; that // override travelled in from the renderer and is gone. In its place: an // OAuth token is never sent over an unverified connection. Breaks: a config // carrying allowInsecureTLS (stale, or from a compromised window) hands the // token to a man-in-the-middle. - it('verifies the certificate for an OAuth account even when the config opts out', async () => { + it('verifies the certificate for an OAuth account even when the config opts out or carries a pin', async () => { const client = new SMTPClient(); await client.connect(baseConfig({ allowInsecureTLS: true, authMethod: 'oauth2', accessToken: 't', oauthProvider: 'gmail' })); expect(lastTransportOptions().tls).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); + await client.connect(baseConfig({ certificatePin: { sha256: 'AB', pem: 'PEM' }, authMethod: 'oauth2', accessToken: 't', oauthProvider: 'gmail' })); + expect(lastTransportOptions().tls).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); }); // The account's connection security decides the transport (CASA M-5). Breaks: @@ -516,6 +527,17 @@ describe('SMTPClient.connect — a required STARTTLS the server will not do (CAS h.state.verifyError = Object.assign(new Error('Error initiating TLS - self-signed certificate'), { code: 'ETLS', command: 'STARTTLS' }); await expect(new SMTPClient().connect(baseConfig())).rejects.toThrow('Error initiating TLS - self-signed certificate'); }); + + // CASA 4.1.2. nodemailer re-codes a socket error as ESOCKET and keeps the TLS + // code in `originalCode`. Breaks: an untrusted certificate reaches the user as + // a raw OpenSSL string and main never offers to review the certificate. + it('turns an untrusted certificate into a CERTIFICATE_UNTRUSTED refusal that says what to do', async () => { + h.state.verifyError = Object.assign(new Error('self-signed certificate'), { code: 'ESOCKET', originalCode: 'DEPTH_ZERO_SELF_SIGNED_CERT', command: 'CONN' }); + const error = await new SMTPClient().connect(baseConfig({ port: 587 })).catch((e) => e); + expect(error).toMatchObject({ code: CERTIFICATE_UNTRUSTED, certificateFailure: 'DEPTH_ZERO_SELF_SIGNED_CERT' }); + expect(error.message).toBe(certificateUntrustedMessage('outgoing', 'smtp.sarv.com', 587)); + expect(isStarttlsRefusedError(error)).toBe(false); + }); }); describe('SMTPClient.sendEmail — read receipt + identity', () => { diff --git a/packages/core/test/unit/utils/certificate-inspection.test.ts b/packages/core/test/unit/utils/certificate-inspection.test.ts new file mode 100644 index 00000000..b9b9d519 --- /dev/null +++ b/packages/core/test/unit/utils/certificate-inspection.test.ts @@ -0,0 +1,130 @@ +import net from 'node:net'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { + CertificateInspectionError, + certificateOutsideValidity, + describeCertificate, + inspectServerCertificate, +} from '../../../src/utils/certificate-inspection'; + +// The failure paths of fetching a certificate for the approval dialog (the +// happy paths, over real TLS, are in +// test/integration/utils/certificate-pin.integration.test.ts). What breaks if +// this fails: a server that refuses STARTTLS, never answers, floods, or is not +// there hangs main's approval flow or crashes it with an unhandled socket +// error, instead of settling to "no certificate to show". + +const servers: net.Server[] = []; +afterEach(async () => { + await Promise.all(servers.splice(0).map((s) => new Promise((resolve) => s.close(() => resolve())))); +}); + +/** A plaintext server that runs `script` on each connection. */ +async function plainServer(script: (socket: net.Socket) => void): Promise { + const server = net.createServer((socket) => { + socket.on('error', () => { /* client went away */ }); + // Keep reading, so the client's close is seen and server.close() can finish. + socket.resume(); + script(socket); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return (server.address() as net.AddressInfo).port; +} + +const failureOf = (promise: Promise) => promise.then(() => null, (e: unknown) => e as CertificateInspectionError); + +describe('inspectServerCertificate — when there is no certificate to show', () => { + // Breaks: an IMAP server answering NO to STARTTLS leaves the dialog waiting. + it('settles "no-starttls" when an IMAP server refuses the upgrade', async () => { + const port = await plainServer((socket) => { + socket.write('* OK ready\r\n'); + socket.on('data', () => socket.write('* BYE not now\r\nA1 NO STARTTLS unavailable\r\n')); + }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'starttls', protocol: 'imap' })); + expect(error).toMatchObject({ name: 'CertificateInspectionError', reason: 'no-starttls' }); + }); + + // Breaks: each refusal point of the SMTP exchange (greeting, EHLO, STARTTLS) + // leaves the dialog waiting or is read as success. + it.each([ + ['a refused greeting', ['554 go away\r\n']], + ['a refused EHLO', ['220 hi\r\n', '500 no\r\n']], + ['a refused STARTTLS', ['220-hi\r\n220 there\r\n', '250-x\r\n250 ok\r\n', '454 TLS not available\r\n']], + ])('settles "no-starttls" for %s from an SMTP server', async (_label, replies) => { + const port = await plainServer((socket) => { + const queue = [...replies]; + socket.write(queue.shift()!); + socket.on('data', () => { if (queue.length) socket.write(queue.shift()!); }); + }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'starttls', protocol: 'smtp' })); + expect(error).toMatchObject({ reason: 'no-starttls' }); + }); + + // Breaks: a server that closes mid-exchange leaves the dialog waiting. + it('settles "no-starttls" when the server hangs up before the upgrade', async () => { + const port = await plainServer((socket) => { socket.end('* OK ready\r\n'); }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'none', protocol: 'imap' })); + expect(error).toMatchObject({ reason: 'no-starttls' }); + }); + + // Breaks: a hostile server streams megabytes before the upgrade and main buffers them all. + it('stops reading a server that floods before encrypting', async () => { + const port = await plainServer((socket) => { + socket.write(`* OK ${'x'.repeat(70 * 1024)}\r\n`); + }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'starttls', protocol: 'imap' })); + expect(error).toMatchObject({ reason: 'no-starttls' }); + }); + + // Breaks: a silent server holds the approval flow open forever. + it('gives up on a server that never answers', async () => { + const port = await plainServer(() => { /* silence */ }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'starttls', protocol: 'smtp', timeoutMs: 200 })); + expect(error).toMatchObject({ reason: 'too-slow' }); + }); + + // Breaks: an unreachable server is reported as a certificate problem, or throws raw. + it('settles "unreachable" when nothing listens, for either kind of connection', async () => { + const port = await plainServer(() => {}); + await new Promise((resolve) => servers.pop()!.close(() => resolve())); + for (const security of ['ssl', 'starttls'] as const) { + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security, protocol: 'imap' })); + expect(error).toMatchObject({ reason: 'unreachable' }); + } + }); + + // Breaks: a plain-text server on an "SSL" port is read as a certificate problem. + it('settles "unreachable" when the "TLS" server speaks plain text', async () => { + const port = await plainServer((socket) => { socket.end('* OK not tls at all\r\n'); }); + const error = await failureOf(inspectServerCertificate({ host: '127.0.0.1', port, security: 'ssl', protocol: 'imap' })); + expect(error).toMatchObject({ reason: 'unreachable' }); + }); +}); + +describe('describeCertificate', () => { + // Breaks: a handshake with no peer certificate crashes the dialog instead of settling. + it('refuses an empty certificate', () => { + expect(() => describeCertificate(undefined)).toThrow(CertificateInspectionError); + expect(() => describeCertificate(Buffer.alloc(0))).toThrow(CertificateInspectionError); + }); +}); + +describe('certificateOutsideValidity', () => { + const now = Date.parse('2026-11-28T00:00:00Z'); + // Breaks: an expired or not-yet-valid certificate is offered for approval, or + // a valid one is refused. + it('says why a certificate cannot be trusted by date alone', () => { + expect(certificateOutsideValidity({ notBefore: now - 1, notAfter: now + 1 }, now)).toBeNull(); + expect(certificateOutsideValidity({ notBefore: now - 10, notAfter: now - 1 }, now)).toBe('expired'); + expect(certificateOutsideValidity({ notBefore: now + 1, notAfter: now + 10 }, now)).toBe('not-yet-valid'); + }); + + // Breaks: a certificate whose dates could not be read counts as valid. + it('treats unreadable dates as not trustable', () => { + expect(certificateOutsideValidity({ notBefore: now - 1, notAfter: Number.NaN }, now)).toBe('expired'); + expect(certificateOutsideValidity({ notBefore: Number.NaN, notAfter: now + 1 }, now)).toBe('not-yet-valid'); + }); +}); diff --git a/packages/core/test/unit/utils/connection-security.test.ts b/packages/core/test/unit/utils/connection-security.test.ts index 2f2e8039..33052b1e 100644 --- a/packages/core/test/unit/utils/connection-security.test.ts +++ b/packages/core/test/unit/utils/connection-security.test.ts @@ -80,32 +80,33 @@ describe('starttlsUnavailableMessage', () => { // A saved password only goes out over the transport the user saved it with // (vault-credentials.ts); these decide what a config asks for and what it may // have. Breaks: a config from the window loosens the transport main dials a -// saved password over — a self-signed opt-in or 'none' it was never saved with. +// saved password over — a 'none' it was never saved with. +// +// Changed deliberately (certificate pinning, CASA 4.1.2): these used to cover +// a second relaxation, `allowInsecureTLS` ("allow self-signed", granted as +// 'insecure-tls'). It is retired — nothing turns certificate checks off, a +// server's own certificate is trusted only by a pin main stores — so the +// transport opt-ins are encryption only, and a config's allowInsecureTLS is +// dropped rather than granted or refused. describe('transportOptInsOf', () => { - it('reads both relaxations off a password config', () => { - expect(transportOptInsOf({ allowInsecureTLS: true, security: 'none' })).toEqual({ allowInsecureTLS: true, allowPlaintext: true }); + it('reads the plaintext relaxation off a password config, and nothing for the retired opt-in', () => { + expect(transportOptInsOf({ allowInsecureTLS: true, security: 'none' } as never)).toEqual({ allowPlaintext: true }); + expect(transportOptInsOf({ allowInsecureTLS: true, security: 'ssl' } as never)).toEqual(STRICT_TRANSPORT); expect(transportOptInsOf({ security: 'starttls' })).toEqual(STRICT_TRANSPORT); // A legacy secure:false account is a REQUIRED STARTTLS, not plaintext. expect(transportOptInsOf({ secure: false }).allowPlaintext).toBe(false); }); - // Only a real boolean opts out; settings round-trip through JSON and IPC. - it('does not read a truthy non-boolean as the opt-in', () => { - for (const value of ['true', 1, {}]) expect(transportOptInsOf({ allowInsecureTLS: value }).allowInsecureTLS).toBe(false); - }); - - // An OAuth sign-in never asks for either, whatever its config carries. + // An OAuth sign-in never asks to go unencrypted, whatever its config carries. it('asks for nothing for OAuth', () => { - expect(transportOptInsOf({ authMethod: 'oauth2', allowInsecureTLS: true, security: 'none' })).toEqual(STRICT_TRANSPORT); + expect(transportOptInsOf({ authMethod: 'oauth2', security: 'none' })).toEqual(STRICT_TRANSPORT); }); }); describe('transportOptInBeyond', () => { - const all = { allowInsecureTLS: true, allowPlaintext: true }; + const all = { allowPlaintext: true }; it('names the relaxation asked for but not granted', () => { - expect(transportOptInBeyond({ allowInsecureTLS: true, allowPlaintext: false }, STRICT_TRANSPORT)).toBe('insecure-tls'); - expect(transportOptInBeyond({ allowInsecureTLS: false, allowPlaintext: true }, STRICT_TRANSPORT)).toBe('plaintext'); - expect(transportOptInBeyond({ allowInsecureTLS: false, allowPlaintext: true }, { allowInsecureTLS: true, allowPlaintext: false })).toBe('plaintext'); + expect(transportOptInBeyond({ allowPlaintext: true }, STRICT_TRANSPORT)).toBe('plaintext'); }); // Tightening is always allowed: a stricter request is never refused. @@ -117,20 +118,26 @@ describe('transportOptInBeyond', () => { }); describe('limitTransport', () => { - const asksAll = { host: 'h', allowInsecureTLS: true, security: 'none' as const }; + const asksNone = { host: 'h', security: 'none' as const }; it('keeps what is both asked for and granted', () => { - expect(limitTransport(asksAll, { allowInsecureTLS: true, allowPlaintext: true })).toEqual(asksAll); + expect(limitTransport(asksNone, { allowPlaintext: true })).toEqual(asksNone); }); // Breaks: a relaxation nobody granted reaches the client. it('drops what is asked for but not granted, turning None into a required STARTTLS', () => { - expect(limitTransport(asksAll, STRICT_TRANSPORT)).toEqual({ host: 'h', allowInsecureTLS: false, security: 'starttls' }); + expect(limitTransport(asksNone, STRICT_TRANSPORT)).toEqual({ host: 'h', security: 'starttls' }); }); // A request can tighten: granted-but-not-asked never switches a relaxation on. it('never adds a relaxation the config did not ask for', () => { const strict = { host: 'h', security: 'ssl' as const }; - expect(limitTransport(strict, { allowInsecureTLS: true, allowPlaintext: true })).toEqual({ ...strict, allowInsecureTLS: false }); + expect(limitTransport(strict, { allowPlaintext: true })).toEqual(strict); + }); + + // Breaks: the retired opt-in survives into the config main dials with, where + // anything still reading it would relax the connection again. + it('drops a legacy allowInsecureTLS from the config', () => { + expect(limitTransport({ host: 'h', security: 'ssl' as const, allowInsecureTLS: true } as never, { allowPlaintext: true })).toEqual({ host: 'h', security: 'ssl' }); }); }); diff --git a/packages/core/test/unit/utils/tls-guard.test.ts b/packages/core/test/unit/utils/tls-guard.test.ts new file mode 100644 index 00000000..c13a9f00 --- /dev/null +++ b/packages/core/test/unit/utils/tls-guard.test.ts @@ -0,0 +1,97 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, sep } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +// CASA 4.1.2: "Connections to and from the server shall use trusted TLS +// certificates." What breaks if this fails: someone turns certificate checks +// off (or replaces them) in product code again — the copy-paste that once +// spread an unverified default across the SMTP client, the IPC handlers and the +// account forms, and later came back as the "allow self-signed" switch. +// +// In product code: +// - `rejectUnauthorized` may be SET (`:` or `=`) in exactly two files: +// packages/core/src/utils/tls.ts (resolveTlsOptions, only ever `true`) and +// packages/core/src/utils/certificate-inspection.ts (`false`: the one socket +// that fetches an untrusted certificate to SHOW the user and carries no +// credential — see that file and the integration test); +// - `checkServerIdentity` may appear only in tls.ts (the exact-pin check); +// - `NODE_TLS_REJECT_UNAUTHORIZED` (which turns checks off process-wide) may +// appear nowhere. +// Comment lines are not code and are skipped. + +const repo = join(__dirname, '../../../../..'); +const ROOTS = ['packages/core/src', 'packages/storage-node/src', 'apps/desktop/electron', 'apps/desktop/src', 'apps/desktop/vite']; +const SKIP = new Set(['node_modules', 'dist', 'dist-electron', '__testing__', 'test-support']); +const TLS = 'packages/core/src/utils/tls.ts'; +const INSPECTION = 'packages/core/src/utils/certificate-inspection.ts'; + +function sourceFiles(dir: string): string[] { + const out: string[] = []; + for (const name of readdirSync(dir)) { + if (SKIP.has(name)) continue; + const path = join(dir, name); + if (statSync(path).isDirectory()) out.push(...sourceFiles(path)); + else if (/\.(ts|tsx|mts|cts|js|mjs|cjs)$/.test(name)) out.push(path); + } + return out; +} + +const isComment = (line: string): boolean => { + const t = line.trim(); + return t.startsWith('*') || t.startsWith('//') || t.startsWith('/*'); +}; + +/** Every non-comment product line, by repo-relative path. */ +function productLines(): Array<{ rel: string; line: string }> { + const out: Array<{ rel: string; line: string }> = []; + for (const root of ROOTS) { + for (const file of sourceFiles(join(repo, root))) { + const rel = relative(repo, file).split(sep).join('/'); + for (const line of readFileSync(file, 'utf8').split('\n')) if (!isComment(line)) out.push({ rel, line }); + } + } + return out; +} + +/** Sets the option: `rejectUnauthorized:`, `rejectUnauthorized =`, `'rejectUnauthorized':`, `["rejectUnauthorized"] =`. */ +const SETS_REJECT = /rejectUnauthorized['"]?\]?\s*(?::|=(?!=))/; + +describe('certificate verification is decided in one place', () => { + const lines = productLines(); + + it('lets only resolveTlsOptions (true) and the certificate inspection (false) set rejectUnauthorized', () => { + const offenders = lines + .filter(({ line }) => SETS_REJECT.test(line)) + .filter(({ rel, line }) => !((rel === TLS && /rejectUnauthorized: true/.test(line)) || (rel === INSPECTION && /rejectUnauthorized: false/.test(line)))) + .map(({ rel, line }) => `${rel}: ${line.trim()}`); + expect(offenders).toEqual([]); + }); + + // Breaks: a second identity check is installed somewhere that accepts more + // than the pin (or skips the hostname check for every certificate). + it('lets only tls.ts touch checkServerIdentity', () => { + const offenders = lines.filter(({ rel, line }) => rel !== TLS && line.includes('checkServerIdentity')).map(({ rel, line }) => `${rel}: ${line.trim()}`); + expect(offenders).toEqual([]); + }); + + // Breaks: certificate checks are switched off for the whole process. + it('never mentions NODE_TLS_REJECT_UNAUTHORIZED', () => { + const offenders = lines.filter(({ line }) => line.includes('NODE_TLS_REJECT_UNAUTHORIZED')).map(({ rel, line }) => `${rel}: ${line.trim()}`); + expect(offenders).toEqual([]); + }); + + // Breaks: the guards above silently stop scanning (a moved folder) and pass + // on nothing, or the patterns stop matching the forms they forbid. + it('actually scans the product files and recognises every forbidden form', () => { + expect(lines.some(({ rel, line }) => rel === TLS && /rejectUnauthorized: true/.test(line))).toBe(true); + expect(lines.some(({ rel, line }) => rel === TLS && line.includes('checkServerIdentity'))).toBe(true); + expect(lines.some(({ rel, line }) => rel === INSPECTION && /rejectUnauthorized: false/.test(line))).toBe(true); + expect(lines.some(({ rel }) => rel.startsWith('apps/desktop/electron/'))).toBe(true); + for (const form of ['tls: { rejectUnauthorized: false }', 'options.rejectUnauthorized = false', "opts['rejectUnauthorized'] = false", '{ "rejectUnauthorized": false }']) { + expect(SETS_REJECT.test(form)).toBe(true); + } + expect(SETS_REJECT.test('if (socket.rejectUnauthorized === false)')).toBe(false); + expect(isComment(' * rejectUnauthorized: false in a comment')).toBe(true); + }); +}); diff --git a/packages/core/test/unit/utils/tls.test.ts b/packages/core/test/unit/utils/tls.test.ts index d61aca1a..8eb83fca 100644 --- a/packages/core/test/unit/utils/tls.test.ts +++ b/packages/core/test/unit/utils/tls.test.ts @@ -1,84 +1,169 @@ import { describe, it, expect } from 'vitest'; -import { resolveTlsOptions } from '../../../src/utils/tls'; +import { isAuthError, isConnectionError } from '../../../src/imap/imap-errors'; +import { + CERTIFICATE_PIN_MISMATCH, + CERTIFICATE_UNTRUSTED, + certificateUntrustedMessage, + isCertificateUntrustedError, + normalizeFingerprint, + pinnedServerIdentityCheck, + resolveTlsOptions, + untrustedCertificateCode, +} from '../../../src/utils/tls'; import type { TlsResolvable } from '../../../src/utils/tls'; -// SECURITY BOUNDARY. This function is the ONLY place that decides whether a mail +// SECURITY BOUNDARY. This function is the ONLY place that decides how a mail // connection verifies its certificate. `rejectUnauthorized: false` used to be // copy-pasted across the SMTP client, both IPC handlers and several UI config -// builders — which is exactly how an insecure default spreads unnoticed. Every -// test below asserts one direction of "secure unless the user explicitly opted -// out", plus the TLS 1.2 floor. +// builders — which is exactly how an insecure default spreads unnoticed — and +// later one per-account "allow self-signed" switch accepted ANY certificate. +// Since CASA 4.1.2 nothing turns verification off: a pin narrows trust to one +// certificate, and that is the only exception. Real handshakes (OpenSSL and +// BoringSSL) are in test/integration/utils/certificate-pin.integration.test.ts. -describe('resolveTlsOptions — secure by default', () => { +const FP = 'AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89'; +const PIN = { sha256: FP, pem: '-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n' }; + +describe('resolveTlsOptions — always verifies', () => { it('verifies certificates for a bare config', () => { expect(resolveTlsOptions({})).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); }); - it('verifies certificates when allowInsecureTLS is undefined or false', () => { - expect(resolveTlsOptions({ allowInsecureTLS: undefined }).rejectUnauthorized).toBe(true); - expect(resolveTlsOptions({ allowInsecureTLS: false }).rejectUnauthorized).toBe(true); + // Changed deliberately (certificate pinning, CASA 4.1.2): `allowInsecureTLS: + // true` used to turn verification OFF for a password account ("explicit + // opt-out" block, removed). The switch accepted any certificate at all, which + // the assessment rejected. Breaks: an account saved with the old switch — or a + // compromised window sending it — gets an unverified connection again. + it('ignores the retired allowInsecureTLS opt-in, whatever its value', () => { + for (const value of [true, 'true', 'false', 1, {}, false, undefined]) { + const config = { allowInsecureTLS: value } as unknown as TlsResolvable; + expect(resolveTlsOptions(config)).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); + } }); - // Changed deliberately (renderer-supplied TLS relaxation): this used to pin - // that an empty `tlsOptions` kept verification on, because a set - // `tlsOptions.rejectUnauthorized` won over everything. That override came in - // from the renderer with the rest of the config, so it is gone: no - // `tlsOptions` value can turn verification off. Breaks: a compromised window - // sends `tlsOptions: { rejectUnauthorized: false }` and main dials the user's - // saved password to whoever answers. + // Changed deliberately (renderer-supplied TLS relaxation, then certificate + // pinning): no `tlsOptions` value, and no combination with the retired opt-in, + // can turn verification off. Breaks: a compromised window sends + // `tlsOptions: { rejectUnauthorized: false }` and main dials the user's saved + // password to whoever answers. it('ignores a tlsOptions override in either direction', () => { const off = { tlsOptions: { rejectUnauthorized: false } } as unknown as TlsResolvable; expect(resolveTlsOptions(off).rejectUnauthorized).toBe(true); const on = { allowInsecureTLS: true, tlsOptions: { rejectUnauthorized: true } } as unknown as TlsResolvable; - expect(resolveTlsOptions(on).rejectUnauthorized).toBe(false); + expect(resolveTlsOptions(on).rejectUnauthorized).toBe(true); }); - // Changed deliberately (renderer-supplied TLS relaxation): this used to test - // non-boolean `tlsOptions.rejectUnauthorized` values; it now tests the opt-in - // itself, which used to be read as truthy. Settings round-trip through - // JSON/IPC and can arrive as strings. Breaks: a stored "false" (truthy) - // turns verification off. - it('only the boolean true opts out — "true", "false", 1 and {} do not', () => { - for (const value of ['true', 'false', 1, {}]) { - const config = { allowInsecureTLS: value } as unknown as TlsResolvable; - expect(resolveTlsOptions(config).rejectUnauthorized).toBe(true); + // Pinned regardless of the Node/OpenSSL runtime default, so the connection can + // never negotiate down to SSLv3 / TLS 1.0 / 1.1 — with or without a pin. + it('always pins minVersion to TLSv1.2', () => { + expect(resolveTlsOptions({}).minVersion).toBe('TLSv1.2'); + expect(resolveTlsOptions({ certificatePin: PIN }).minVersion).toBe('TLSv1.2'); + expect(resolveTlsOptions({ authMethod: 'oauth2' }).minVersion).toBe('TLSv1.2'); + }); + + // Callers spread the result straight into an ImapFlow/nodemailer config, so an + // unpinned connection must carry exactly these two keys (no stray `ca` that + // would replace the system trust store). + it('returns only the two TLS keys it owns when there is no pin', () => { + expect(Object.keys(resolveTlsOptions({})).sort()).toEqual(['minVersion', 'rejectUnauthorized']); + }); +}); + +describe('resolveTlsOptions — a pinned certificate', () => { + // Breaks: a pin adds to the system trust store instead of replacing it (any + // public CA's certificate would still be accepted), or BoringSSL refuses the + // approved CA:FALSE self-signed certificate (no partial chain). + it('makes the approved certificate the only anchor and checks the exact leaf', () => { + const options = resolveTlsOptions({ authMethod: 'password', certificatePin: PIN }); + expect(options).toMatchObject({ rejectUnauthorized: true, minVersion: 'TLSv1.2', ca: [PIN.pem], allowPartialTrustChain: true }); + expect(options.checkServerIdentity?.('any.host', { fingerprint256: FP } as never)).toBeUndefined(); + expect(options.checkServerIdentity?.('any.host', { fingerprint256: FP.replace('AB', '00') } as never)).toMatchObject({ code: CERTIFICATE_PIN_MISMATCH }); + }); + + // An OAuth token never goes over a pinned (narrowed or redirected) connection: + // every provider has a public certificate. Breaks: a pin sent by a compromised + // window points the user's Gmail token at the attacker's certificate. + it('ignores a pin on an OAuth sign-in', () => { + expect(resolveTlsOptions({ authMethod: 'oauth2', certificatePin: PIN })).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); + }); + + // Breaks: a damaged stored pin (no PEM) produces `ca: [undefined]` and a + // connection that crashes, or trusts nothing it can explain. It falls back to + // the system trust store, which still rejects any self-signed certificate. + it('falls back to normal verification for a pin with no certificate', () => { + for (const pin of [{ sha256: FP, pem: '' }, { sha256: FP }, { pem: PIN.pem }, null]) { + expect(resolveTlsOptions({ certificatePin: pin as never })).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' }); } }); +}); - // An OAuth token never goes over an unverified connection (the audit's - // "known issue"). Every provider has a public certificate, so nothing - // legitimate needs the opt-in. Breaks: a config carrying allowInsecureTLS — - // stale, or from a compromised window — hands the Gmail token to a - // man-in-the-middle. - it('always verifies for an OAuth sign-in, whatever the config says', () => { - expect(resolveTlsOptions({ authMethod: 'oauth2', allowInsecureTLS: true }).rejectUnauthorized).toBe(true); - expect(resolveTlsOptions({ authMethod: 'password', allowInsecureTLS: true }).rejectUnauthorized).toBe(false); +describe('pinnedServerIdentityCheck', () => { + // Breaks: the exact-leaf check accepts a near miss, a lower-case form of the + // pin is refused, or a malformed pin accepts everything. + it('accepts only the pinned fingerprint, in any case, and nothing for a malformed pin', () => { + const check = pinnedServerIdentityCheck(FP.toLowerCase()); + expect(check('h', { fingerprint256: FP } as never)).toBeUndefined(); + expect(check('h', { fingerprint256: `${FP}:00` } as never)).toBeInstanceOf(Error); + expect(check('h', {} as never)).toBeInstanceOf(Error); + expect(check('h', undefined as never)).toBeInstanceOf(Error); + const broken = pinnedServerIdentityCheck('not-a-fingerprint'); + expect(broken('h', { fingerprint256: FP } as never)).toBeInstanceOf(Error); + expect(broken('h', { fingerprint256: 'not-a-fingerprint' } as never)).toBeInstanceOf(Error); }); }); -describe('resolveTlsOptions — explicit opt-out', () => { - // The per-account escape hatch for self-signed corporate servers. It must work - // (users depend on it) but only when deliberately set. - it('disables verification when the account opted into allowInsecureTLS', () => { - expect(resolveTlsOptions({ allowInsecureTLS: true }).rejectUnauthorized).toBe(false); +describe('normalizeFingerprint', () => { + // Breaks: a stored or presented fingerprint in another case is compared as different. + it('upper-cases a well-formed SHA-256 fingerprint', () => { + expect(normalizeFingerprint(` ${FP.toLowerCase()} `)).toBe(FP); + }); + + // Breaks: a truncated, padded or non-hex value passes for a fingerprint. + it('rejects anything that is not 32 hex pairs', () => { + for (const value of ['', 'AB', `${FP}:`, FP.replace('AB', 'AG'), FP.replace('AB', 'ABC'), FP.replaceAll(':', ''), 42, null]) { + expect(normalizeFingerprint(value)).toBeNull(); + } }); }); -describe('resolveTlsOptions — protocol floor', () => { - // Pinned regardless of what the Node/OpenSSL runtime default is, so the - // connection can never negotiate down to SSLv3 / TLS 1.0 / 1.1. - // Changed deliberately (renderer-supplied TLS relaxation): the third case - // used a tlsOptions override, which no longer exists; it is an OAuth config now. - it('always pins minVersion to TLSv1.2, even when verification is disabled', () => { - expect(resolveTlsOptions({}).minVersion).toBe('TLSv1.2'); - expect(resolveTlsOptions({ allowInsecureTLS: true }).minVersion).toBe('TLSv1.2'); - expect(resolveTlsOptions({ authMethod: 'oauth2' }).minVersion).toBe('TLSv1.2'); +describe('untrustedCertificateCode / isCertificateUntrustedError', () => { + // Breaks: an untrusted certificate is not recognised — on the raw TLS error, + // nodemailer's re-coded one (originalCode), or one wrapped as a cause — so the + // user is never offered the certificate to review. + it('finds the verification failure on the error, its originalCode or its cause chain', () => { + expect(untrustedCertificateCode(Object.assign(new Error('x'), { code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }))).toBe('DEPTH_ZERO_SELF_SIGNED_CERT'); + expect(untrustedCertificateCode(Object.assign(new Error('x'), { code: 'ESOCKET', originalCode: 'SELF_SIGNED_CERT_IN_CHAIN' }))).toBe('SELF_SIGNED_CERT_IN_CHAIN'); + expect(untrustedCertificateCode(Object.assign(new Error('x'), { cause: { cause: { code: CERTIFICATE_PIN_MISMATCH } } }))).toBe(CERTIFICATE_PIN_MISMATCH); + expect(isCertificateUntrustedError(Object.assign(new Error('x'), { code: CERTIFICATE_UNTRUSTED }))).toBe(true); + expect(isCertificateUntrustedError(Object.assign(new Error('x'), { code: 'ERR_TLS_CERT_ALTNAME_INVALID' }))).toBe(true); }); - // Callers spread the result straight into an ImapFlow/nodemailer config, so the - // shape must stay exactly these two keys. - it('returns only the two TLS keys it owns', () => { - expect(Object.keys(resolveTlsOptions({})).sort()).toEqual(['minVersion', 'rejectUnauthorized']); + // Breaks: a network blip or a rejected password opens a certificate dialog. + it('says no to everything else', () => { + for (const error of [new Error('self-signed certificate'), Object.assign(new Error('x'), { code: 'ECONNRESET' }), Object.assign(new Error('x'), { code: 'EAUTH' }), 'DEPTH_ZERO_SELF_SIGNED_CERT', null, undefined]) { + expect(untrustedCertificateCode(error)).toBeNull(); + expect(isCertificateUntrustedError(error)).toBe(false); + } + }); + + // Breaks: a cyclic cause chain (an error that is its own cause) hangs the classifier. + it('stops on a cyclic cause chain', () => { + const cyclic: { code: string; cause?: unknown } = { code: 'ECONNRESET' }; + cyclic.cause = cyclic; + expect(untrustedCertificateCode(cyclic)).toBeNull(); + }); +}); + +describe('certificateUntrustedMessage', () => { + // Breaks: the refusal reads as a network blip (retried forever) or a rejected + // password (forgotten, re-auth prompt) instead of a settled certificate fact. + it('names the server and what to do, and matches neither the network nor the auth classifier', () => { + const message = certificateUntrustedMessage('outgoing', 'smtp.office.lan', 587); + expect(message).toContain('smtp.office.lan:587'); + expect(message).toContain('Settings → Accounts'); + const error = new Error(message); + expect(isConnectionError(error)).toBe(false); + expect(isAuthError(error)).toBe(false); }); }); From 2f4cb74797e3c5f40efdfa0b71f46d14e4781a55 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Wed, 2 Dec 2026 22:44:40 +0530 Subject: [PATCH 09/13] fix(accounts): a named account is that account or an error, never another CASA 3.1.3 / 3.1.4 (found while building the IPC object-identifier inventory for TAC's review of 25 Nov): an account that could not be resolved fell back to the ACTIVE mailbox, and an unknown account id could create an empty mailbox database. - The lenient resolveAccountTarget is gone. Every handler resolves a renderer-named account with resolveNamedOrActiveAccountTarget: no id is the active account; a named one is exactly that account's runtime or an error. Trusting a sender, drafts by thread, labels, server search, quota, attachments and thread summaries (now per account) can no longer land in another mailbox. - ensureAccountRuntime opens or creates a mailbox DB only for an id the registry lists (isRegisteredAccountId over the throwing readRegistryAccounts; an unreadable registry refuses). The add flow is the one exception: accounts:setActive {adding: true} is accepted only for the account main itself just verified (a single-use proof from imap:probeCredentials, 10 minutes), never adopts a legacy database, and an abandoned add's runtime is closed. - accounts:setActive is transactional: open first, point second, and any failure restores the previous pointer, saved active account and outbox binding, so success:false means main did not move. The window stays on its account when main refuses; a failed add's rollback checks main's answer. - Removing the active account tries the remaining accounts in turn, else clears to no account. A removed account gets a tombstone in main that account saves honour, so a stale snapshot cannot bring it back; only a verified add clears it. - Compacting the active account points main back at it after reopening (it was left on an empty slot), and the reopen retries a transient registry read error. - Panel requests check own properties only; legacy agent decisions validate their status and action. Pre-existing tests changed deliberately: account-target (the fallback test now expects a refusal; strict results include accountId), accounts-runtime (ids must be registered; option renamed registryChecked), draft-calendar-metadata and email-thread-ownership (one strict resolver), connection-remove-account (selectAccount resolves true), smtp-vault-password and smtp-oauth-host-binding (connectFor refuses a missing runtime), db-compact (models the active pointer), imap-oauth-host-binding (clears add proofs). Seventeen suites only renamed the mocked resolver, and several registry mocks gained isRegisteredAccountId or markAccountRemoved. --- CHANGELOG.md | 24 ++ CLAUDE.md | 21 + .../desktop/electron/ipc/accounts-handlers.ts | 166 +++++++- apps/desktop/electron/ipc/agent-handlers.ts | 16 +- apps/desktop/electron/ipc/ai-handlers.ts | 20 +- apps/desktop/electron/ipc/draft-handlers.ts | 53 ++- apps/desktop/electron/ipc/email-handlers.ts | 41 +- .../electron/ipc/image-trust-handlers.ts | 5 +- apps/desktop/electron/ipc/label-handlers.ts | 46 +-- apps/desktop/electron/ipc/pgp-handlers.ts | 4 +- apps/desktop/electron/ipc/spam-handlers.ts | 29 +- apps/desktop/electron/ipc/sync-handlers.ts | 18 +- apps/desktop/electron/main.ts | 26 +- apps/desktop/electron/preload.ts | 29 +- .../electron/services/account-add-proof.ts | 52 +++ .../electron/services/account-target.ts | 111 ++---- .../electron/services/accounts-registry.ts | 88 ++++- .../electron/services/accounts-runtime.ts | 70 +++- .../services/agent-decision-values.ts | 77 ++++ .../electron/services/attachment-cache.ts | 4 +- apps/desktop/electron/services/db-compact.ts | 54 ++- apps/desktop/electron/shared.ts | 7 +- apps/desktop/src/components/ThreadSummary.tsx | 16 +- .../components/email-detail/EmailDetail.tsx | 1 + .../components/onboarding/EmailSetupStep.tsx | 10 +- apps/desktop/src/store/helpers.ts | 19 +- .../src/store/slices/connection-slice.ts | 76 +++- apps/desktop/src/store/types.ts | 6 +- .../ipc/accounts-remove-attachments.test.ts | 2 + .../ipc/accounts-remove-signout.test.ts | 29 ++ .../electron/ipc/accounts-set-active.test.ts | 352 +++++++++++++++++ .../ipc/agent-draft-reply-context.test.ts | 13 +- .../ipc/agent-resolve-decision.test.ts | 138 +++++++ .../ipc/ai-handlers-first-split.test.ts | 78 +++- .../electron/ipc/attachment-handlers.test.ts | 8 +- .../electron/ipc/draft-attachments.test.ts | 20 +- .../electron/ipc/draft-badge-refresh.test.ts | 12 +- .../ipc/draft-calendar-metadata.test.ts | 10 +- .../ipc/draft-caller-message-id.test.ts | 10 +- .../electron/ipc/draft-change-events.test.ts | 12 +- .../electron/ipc/draft-encryption.test.ts | 8 +- .../ipc/draft-handlers-logging.test.ts | 34 +- .../electron/ipc/draft-msgid-window.test.ts | 10 +- .../electron/ipc/draft-sent-copy-kept.test.ts | 16 +- .../electron/ipc/draft-server-delete.test.ts | 16 +- .../unit/electron/ipc/email-handlers.test.ts | 65 ++- .../ipc/email-thread-ownership.test.ts | 7 +- .../ipc/imap-connect-security.test.ts | 50 ++- .../ipc/imap-oauth-host-binding.test.ts | 22 ++ .../ipc/inbox-assistant-handlers.test.ts | 13 +- .../ipc/local-mirror-content-hash.test.ts | 2 +- .../unit/electron/ipc/pgp-handlers.test.ts | 2 +- .../unit/electron/ipc/send-pgp-wiring.test.ts | 2 +- .../unit/electron/ipc/sent-append.test.ts | 2 +- .../electron/ipc/sent-attachments.test.ts | 2 +- .../ipc/smtp-oauth-host-binding.test.ts | 7 +- .../electron/ipc/smtp-vault-password.test.ts | 20 +- .../ipc/strict-account-targets.test.ts | 373 ++++++++++++++++++ .../services/account-add-proof.test.ts | 77 ++++ .../electron/services/account-target.test.ts | 112 +++--- .../services/accounts-registry.test.ts | 107 +++++ .../services/accounts-runtime.test.ts | 193 ++++++++- .../services/attachment-cache-legacy.test.ts | 2 +- .../services/attachment-cache-store.test.ts | 2 +- .../services/attachment-protocol.test.ts | 2 +- .../unit/electron/services/db-compact.test.ts | 112 +++++- .../components/ThreadSummary.account.test.tsx | 89 +++++ .../onboarding/EmailSetupStep.test.tsx | 35 ++ .../connection-account-activation.test.ts | 271 +++++++++++++ .../slices/connection-remove-account.test.ts | 5 +- packages/core/src/extensions/panel-bridge.ts | 12 +- .../unit/extensions/extension-hooks.test.ts | 24 +- 72 files changed, 3055 insertions(+), 412 deletions(-) create mode 100644 apps/desktop/electron/services/account-add-proof.ts create mode 100644 apps/desktop/electron/services/agent-decision-values.ts create mode 100644 apps/desktop/test/unit/electron/ipc/accounts-set-active.test.ts create mode 100644 apps/desktop/test/unit/electron/ipc/agent-resolve-decision.test.ts create mode 100644 apps/desktop/test/unit/electron/ipc/strict-account-targets.test.ts create mode 100644 apps/desktop/test/unit/electron/services/account-add-proof.test.ts create mode 100644 apps/desktop/test/unit/src/components/ThreadSummary.account.test.tsx create mode 100644 apps/desktop/test/unit/src/store/slices/connection-account-activation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d8230072..8e694aea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 them; you then see the certificate their server presents, once. Approve it and they carry on as before. +### Fixed +- **A change you make for one mailbox never lands in another.** With more than + one account, trusting a sender, removing a trusted sender, saving or + discarding a draft, reopening a reply draft, creating or applying a label, + and caching a conversation summary could, if that account was briefly + unavailable (for example while it was being compacted), be applied to the + mailbox you had open instead. A trusted sender's mail skips the spam filter, + so that one could let a sender's mail through in the wrong account. These now + stop with an error, and nothing changes in the other mailbox. Thread + summaries are also kept per account now, so a summary made in All Inboxes is + shown only on that account's copy of the conversation. +- **A removed account no longer comes back.** A late request for an account + you had removed (a background check, a switch, a sending connection) could + recreate a blank database for it, and a change saved while the removal was + still finishing could put the account back in the list at the next start. The + app now opens a mailbox only for an account that is set up on this computer, + and a removed account stays removed until you add it again. +- **Switching accounts that cannot be opened keeps you where you were.** If the + account you pick (or, after you remove the open account, the next one) cannot + be opened right now, the app stays on a working mailbox, or shows no account, + instead of showing one account's name over another account's mail. +- **Compressing the database of the account you have open** no longer leaves + the app without a mailbox until you restart it. + ## [1.5.0] - 2026-11-25 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index f2783ad8..f8e1c804 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -287,6 +287,27 @@ Established shared helpers (extend this list as you add more): conversation-level star writes to: the LATEST message when starring, every row when unstarring (Outlook / Sarv Mail behaviour). Use it for any new thread-wide star control instead of passing the whole thread's ids. +- `resolveNamedOrActiveAccountTarget(accountId?)` / `requireNamedOrActiveStorage(accountId?)` / + `requireAccountStorage(accountId)` — `apps/desktop/electron/services/account-target.ts`. + The ONLY way a handler resolves a renderer-named account: no id is the active + account; a named one is exactly that account's runtime (opened only if the + registry lists it) or a throw — never a fall back to the active mailbox + (thread ids, Message-IDs, addresses and label names exist in every account). + There is no lenient resolver; do not add one. +- `isRegisteredAccountId(id)` — `apps/desktop/electron/services/accounts-registry.ts`. + Whether an id is a configured account, read through the THROWING + `readRegistryAccounts`. `ensureAccountRuntime` gates on it, so no path opens + (or creates) a mailbox DB for an unlisted id; only `accounts:setActive` passes + `registryChecked` — after its own registry read, or for an ADD backed by + main's sign-in proof (`noteVerifiedAccount` / `takeVerifiedAccount`, + `apps/desktop/electron/services/account-add-proof.ts`: recorded by a + successful `imap:probeCredentials`, one use, ten minutes). A removed id is + tombstoned (`markAccountRemoved`) so no snapshot or seed writes its row back; + only a verified re-add clears it. +- `accounts:setActive` is TRANSACTIONAL: `success: false` means main did not + move (open first, point second; a failure after the pointer moved puts it, + the persisted pointer and the outbox back). Renderer code may rely on that — + `selectAccount` resolves `false` on a refusal and leaves the view alone. - `applyDbKey(db, key)` / `encryptPlaintextDb(db, key, schema?)` — `packages/storage-node/src/db-encryption.ts` (import `@sarvinbox/storage-node/db-encryption` from the desktop app; it has its own diff --git a/apps/desktop/electron/ipc/accounts-handlers.ts b/apps/desktop/electron/ipc/accounts-handlers.ts index 69a5bddf..5d9381d2 100644 --- a/apps/desktop/electron/ipc/accounts-handlers.ts +++ b/apps/desktop/electron/ipc/accounts-handlers.ts @@ -9,6 +9,8 @@ * `accounts:unifiedInbox` / `accounts:unreadSummary` fan a READ across accounts * for the unified "All Inboxes" view + per-account badges. They read each * account's own SQLite DB (no IMAP connection needed) and never mutate anything. + * Each id goes through `ensureAccountRuntime`, which opens only accounts the + * registry lists: a stale id reads as an empty account, never a new blank DB. * * DB ownership is deterministic (see ensureAccountRuntime): the persisted PRIMARY * account owns the legacy `sarvinbox.db`; every other account gets its own @@ -19,9 +21,13 @@ import type { EmailRecord, SearchQuery, ViewFilter } from '@sarvinbox/core'; import { accountLogLabel, createLogger, errorDiagnostic, redactAccountIds } from '@sarvinbox/core'; import { ipcMain } from 'electron'; +import { takeVerifiedAccount } from '../services/account-add-proof'; import { settleRevocation, type AccountRevocation } from '../services/account-revocation'; import { + clearAccountRemoved, + isRegisteredAccountId, listRegistryAccounts, + markAccountRemoved, oauthIdentityOf, readRegistryAccounts, upsertRegistryAccounts, @@ -33,7 +39,7 @@ import { deleteAppSetting, type RegistryAccount, } from '../services/accounts-registry'; -import { ensureAccountRuntime, loadPrimaryAccountId, savePrimaryAccountId, accountInboxUnread, rekeyAccount, deleteAccountData, legacyDbExists, cleanupOrphanedAccountDbs } from '../services/accounts-runtime'; +import { ensureAccountRuntime, loadPrimaryAccountId, savePrimaryAccountId, clearPrimaryAccountId, accountInboxUnread, rekeyAccount, deleteAccountData, legacyDbExists, cleanupOrphanedAccountDbs, quiesceAccountRuntime } from '../services/accounts-runtime'; import { peekAntivirusScanService } from '../services/antivirus-scan-service'; import { cleanupOrphanedAttachmentStores, removeAllCachedAttachments } from '../services/attachment-cache'; import { clearUnscannedWarningPreference } from '../services/attachment-warning-preferences'; @@ -53,6 +59,78 @@ async function findInbox(storage: { getFolders: () => Promise }): Promise return folders.find((f) => f.path === 'INBOX' || f.name?.toLowerCase() === 'inbox') ?? null; } +/** + * The account a verified ADD activated before its registry row existed — kept + * so the runtime that activation opened is closed if the add is abandoned + * (rolled back, or replaced by another add) instead of lingering as an open, + * unlisted database with a sync engine nobody closes. + */ +let addingAccountId: string | null = null; + +/** Close the runtime an abandoned add left open. Best-effort; never throws. */ +async function closeAbandonedAdd(nowActive: string): Promise { + const pending = addingAccountId; + if (!pending || pending === nowActive) return; + try { + // Completed: its registry row landed (the add's connect succeeded). + if (isRegisteredAccountId(pending)) { + addingAccountId = null; + return; + } + } catch { + return; // could not find out — never close an account on a guess + } + addingAccountId = null; + try { + await quiesceAccountRuntime(pending, 'abandoned add'); + logger.info('[Accounts] closed the runtime of an abandoned add', accountLogLabel(pending)); + } catch (error) { + logger.warn('[Accounts] closing an abandoned add failed:', errorDiagnostic(error)); + } +} + +/** + * Put main back where a failed `accounts:setActive` found it: the active + * pointer, the persisted pointer, the outbox, a legacy adopt that opened + * nothing, and the runtime a failed ADD opened. Each step is best-effort and + * logged; none throws. + */ +async function undoActivation(step: { + accountId: string; + previousId: string | null; + previousPersisted: string | null; + adding: boolean; + adopted: boolean; + opened: boolean; + pointed: boolean; + persisted: boolean; +}): Promise { + if (step.pointed) { + setCurrentAccount(step.previousId); + try { rebindOutboxStorage(); } catch (error) { + logger.warn('[Accounts] restoring the outbox after a failed switch failed:', errorDiagnostic(error)); + } + } + if (step.persisted) { + try { setRegistryActiveAccountId(step.previousPersisted); } catch (error) { + logger.warn('[Accounts] restoring the persisted active account failed:', errorDiagnostic(error)); + } + } + // An adopt whose runtime never opened: nothing claimed sarvinbox.db for this + // account, so the decision is undone. (One that did open keeps it — the file + // is now this account's open database.) + if (step.adopted && !step.opened) { + try { clearPrimaryAccountId(); } catch (error) { + logger.warn('[Accounts] undoing the legacy adopt failed:', errorDiagnostic(error)); + } + } + if (step.adding && step.opened) { + try { await quiesceAccountRuntime(step.accountId, 'failed add'); } catch (error) { + logger.warn('[Accounts] closing a failed add failed:', errorDiagnostic(error)); + } + } +} + export function registerAccountsHandlers(): void { // ===== Durable accounts registry (DB-backed source of truth) ============= // The account list + active pointer live in an encrypted main-process DB @@ -178,7 +256,10 @@ export function registerAccountsHandlers(): void { try { wasRegistered = readRegistryAccounts().some((a) => a.id === accountId); } catch { /* stays false */ } await deleteAccountData(accountId); // Drop it from the durable registry too, so it doesn't reappear on the - // next hydrate/seed. + // next hydrate/seed. Tombstoned FIRST: the window keeps the account in its + // list until this handler returns (the revocation wait below), and a + // snapshot it mirrors meanwhile must not write the row straight back. + markAccountRemoved(accountId); removeRegistryAccount(accountId); // Now the registry is authoritative (we just dropped this account from it), @@ -275,12 +356,49 @@ export function registerAccountsHandlers(): void { } }); - ipcMain.handle('accounts:setActive', async (_event, accountId: string) => { + // `options.adding`: the renderer is ADDING this account (addAccount). Only then + // may the id be one the registry does not list yet — the add flow points main + // at the new account before its first connect, and the registry row is written + // once that connect succeeds — and only when main itself saw that account sign + // in (a successful imap:probeCredentials, account-add-proof): one activation + // per proof, within its window. Every other activation (a switch, startup, an + // add's rollback) must name a configured account: otherwise a stale id (a + // removed account the renderer still remembers) re-created a blank mailbox and + // made it the active one. + // + // TRANSACTIONAL: `success: false` means main is exactly where it was. The + // runtime is opened BEFORE the pointer moves (a runtime that cannot be opened + // is a failure, never an empty active slot), and anything that fails after the + // pointer moved puts back the previous pointer, persisted pointer and outbox. + // The renderer relies on that: it keeps showing the previous account. + ipcMain.handle('accounts:setActive', async (_event, accountId: string, options?: { adding?: boolean }) => { + if (!accountId || typeof accountId !== 'string') return { success: false, error: 'No accountId provided' }; + if (getCurrentAccountId() === accountId && hasAccountRuntime(accountId)) { + return { success: true }; + } + + const previousId = getCurrentAccountId(); + let previousPersisted: string | null = null; + let adding = false; + let adopted = false; + let opened = false; + let pointed = false; + let persisted = false; try { - if (!accountId) return { success: false, error: 'No accountId provided' }; - if (getCurrentAccountId() === accountId && hasAccountRuntime(accountId)) { - return { success: true }; + // One registry read decides; an unreadable registry throws: refused. + const registered = isRegisteredAccountId(accountId); + if (!registered) { + if (options?.adding !== true) { + logger.warn('[Accounts] setActive refused: not a configured account', accountLogLabel(accountId)); + return { success: false, error: 'That account is not configured.' }; + } + if (!takeVerifiedAccount(accountId)) { + logger.warn('[Accounts] setActive refused: an add with no sign-in proof', accountLogLabel(accountId)); + return { success: false, error: 'This account has not signed in yet. Check its details and add it again.' }; + } + adding = true; } + previousPersisted = getRegistryActiveAccountId(); // NOTE: we deliberately do NOT disconnect the previous account's engine on // switch. Tearing it down made switching BACK slow (full reconnect → @@ -291,26 +409,48 @@ export function registerAccountsHandlers(): void { // LEGACY ONLY: adopt the existing sarvinbox.db for the first account that // activates AND only when that file already exists. A fresh install has no // sarvinbox.db, so no primary is set and every account uses its per-id DB. - if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(accountId); + // Never for an account being ADDED: a new account must not take over an + // existing install's mailbox. (With no primary recorded and the legacy file + // present, ensureAccountRuntime then refuses to guess, and the add fails.) + if (registered && !loadPrimaryAccountId() && legacyDbExists()) { + savePrimaryAccountId(accountId); + adopted = true; + } - // Flip the pointer, then ensure this account's runtime exists (claims the - // startup sarvinbox.db for the primary; opens sarvinbox-.db otherwise). - setCurrentAccount(accountId); + // Open first (claims the startup sarvinbox.db for the primary; opens + // sarvinbox-.db otherwise), point second. The membership was decided + // above, so the registry is not read again. if (!hasAccountRuntime(accountId)) { - await ensureAccountRuntime(accountId); + if (!(await ensureAccountRuntime(accountId, { registryChecked: true }))) { + throw new Error('That account could not be opened right now. Try again in a moment.'); + } + opened = true; } + setCurrentAccount(accountId); + pointed = true; // Persist the active pointer durably so main can auto-activate this // account on the next launch without waiting on the renderer. + persisted = true; setRegistryActiveAccountId(accountId); // Drain/send from the now-active account's outbox. rebindOutboxStorage(); - return { success: true }; + + // Being added again after a removal: its registry row may be written now. + if (adding) clearAccountRemoved(accountId); } catch (error) { - logger.error('[Accounts] setActive failed:', error); + logger.error('[Accounts] setActive failed — the previous account stays active:', errorDiagnostic(error)); + await undoActivation({ accountId, previousId, previousPersisted, adding, adopted, opened, pointed, persisted }); return { success: false, error: (error as Error).message }; } + + // An add that was abandoned (rolled back, or replaced by another add) leaves + // a runtime open for an account nobody listed: close it. After the switch, + // so it can never be the account now active. + await closeAbandonedAdd(accountId); + if (adding) addingAccountId = accountId; + return { success: true }; }); // Merged INBOX across the given accounts, tagged with accountId and sorted diff --git a/apps/desktop/electron/ipc/agent-handlers.ts b/apps/desktop/electron/ipc/agent-handlers.ts index be529f0f..80bebd15 100644 --- a/apps/desktop/electron/ipc/agent-handlers.ts +++ b/apps/desktop/electron/ipc/agent-handlers.ts @@ -12,6 +12,7 @@ import { ipcMain } from 'electron'; import { openAccountStorages, requireNamedOrActiveStorage, requireTargetAccountId } from '../services/account-target'; import { resolveAccountIdentity } from '../services/accounts-registry'; import { saveAgentConfig, loadAgentConfig } from '../services/agent-config-store'; +import { decisionActualAction, resolvedDecisionStatus } from '../services/agent-decision-values'; import { forgetAiActions, recordAiActions } from '../services/ai-action-record'; import { refreshContactClassifications } from '../services/contact-classification-service'; import { buildThreadMessages } from '../services/thread-context'; @@ -292,10 +293,15 @@ export function registerAgentHandlers(): void { } }); - ipcMain.handle('agent:resolveDecision', async (_event, decisionId: string, status: string, actualAction?: string, feedback?: string) => { + ipcMain.handle('agent:resolveDecision', async (_event, decisionId: string, status: unknown, actualAction?: unknown, feedback?: string) => { try { + // Only the enums' own values reach the row (see agent-decision-values). + const resolved = resolvedDecisionStatus(status); + if (!resolved) return { success: false, error: 'Unknown decision status' }; + const action = decisionActualAction(actualAction); + if (!action.ok) return { success: false, error: 'Unknown action' }; const agentRepo = getAgentRepo(); - await agentRepo.updateDecisionStatus(decisionId, status as any, actualAction as any, feedback); + await agentRepo.updateDecisionStatus(decisionId, resolved, action.action ?? undefined, feedback); return { success: true }; } catch (error) { return { success: false, error: (error as Error).message }; @@ -513,10 +519,12 @@ export function registerAgentHandlers(): void { } catch (error) { return { success: false, error: (error as Error).message }; } }); - ipcMain.handle('agent:resolveProposal', async (_event, proposalId: string, approved: boolean, actualAction?: string, feedback?: string) => { + ipcMain.handle('agent:resolveProposal', async (_event, proposalId: string, approved: boolean, actualAction?: unknown, feedback?: string) => { try { + const action = decisionActualAction(actualAction); + if (!action.ok) return { success: false, error: 'Unknown action' }; const agentRepo = getAgentRepo(); - await agentRepo.updateDecisionStatus(proposalId, approved ? 'approved' : 'rejected', actualAction as any, feedback); + await agentRepo.updateDecisionStatus(proposalId, approved ? 'approved' : 'rejected', action.action ?? undefined, feedback); return { success: true }; } catch (error) { return { success: false, error: (error as Error).message }; } }); diff --git a/apps/desktop/electron/ipc/ai-handlers.ts b/apps/desktop/electron/ipc/ai-handlers.ts index d5dd1463..1e5ab9f2 100644 --- a/apps/desktop/electron/ipc/ai-handlers.ts +++ b/apps/desktop/electron/ipc/ai-handlers.ts @@ -303,11 +303,17 @@ export function registerAIHandlers(): void { }); /** - * Get thread summary + * Get thread summary, from the account that owns the thread. + * + * The cache is keyed by thread id, and the same thread id exists in every + * account that received the conversation — so it takes the owning account + * (All Inboxes shows other accounts' threads) and resolves it STRICTLY: an + * unavailable account is an error, never the active account's summary of + * its own copy. No id means the active account. */ - ipcMain.handle('ai:getThreadSummary', async (_event, threadId: string) => { + ipcMain.handle('ai:getThreadSummary', async (_event, threadId: string, accountId?: string) => { try { - const storage = requireStorage(); + const storage = await requireNamedOrActiveStorage(accountId); const summary = await storage.getThreadSummary(threadId); return { success: true, data: summary }; } catch (error) { @@ -317,11 +323,13 @@ export function registerAIHandlers(): void { }); /** - * Save thread summary + * Save thread summary into the account that owns the thread — strictly, as + * above: account B's summary must never land in account A's cache under a + * thread id both share. */ - ipcMain.handle('ai:saveThreadSummary', async (_event, summary: any) => { + ipcMain.handle('ai:saveThreadSummary', async (_event, summary: any, accountId?: string) => { try { - const storage = requireStorage(); + const storage = await requireNamedOrActiveStorage(accountId); await storage.upsertThreadSummary(summary); return { success: true }; } catch (error) { diff --git a/apps/desktop/electron/ipc/draft-handlers.ts b/apps/desktop/electron/ipc/draft-handlers.ts index b8e966a2..1d4c87dd 100644 --- a/apps/desktop/electron/ipc/draft-handlers.ts +++ b/apps/desktop/electron/ipc/draft-handlers.ts @@ -14,7 +14,7 @@ import MailComposer from 'nodemailer/lib/mail-composer'; import pLimit from 'p-limit'; import type { LocalCalendarAvailability } from '../../src/types/local-calendar'; -import { requireAccountStorage, requireTargetAccountId, resolveAccountTarget, resolveNamedOrActiveAccountTarget } from '../services/account-target'; +import { requireAccountStorage, requireTargetAccountId, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { seedAttachmentCache } from '../services/attachment-cache'; import { deleteDraftCalendarAvailability, readDraftCalendarAvailability, saveDraftCalendarAvailability, validateDraftCalendarAvailability } from '../services/draft-calendar-metadata'; import { logPgpFailure } from '../services/pgp-failure'; @@ -270,13 +270,16 @@ export async function saveDraftToIMAP(draft: { /** Local-only scheduling evidence; never included in the IMAP MIME. */ calendarAvailability?: LocalCalendarAvailability; }, options: { messageId?: string } = {}): Promise<{ success: boolean; folderPath?: string; messageId?: string; error?: string }> { - // Resolve the TARGET account's storage + sync engine (falls back to the active - // account when no accountId is given). + // Resolve the TARGET account's storage + sync engine: the active account when + // no accountId is given; a named one strictly. A draft is keyed by its + // thread id and In-Reply-To, which exist in every account's database, so an + // unavailable named account is an error — never a draft written into (or + // replacing a draft of) the active mailbox's copy of the same conversation. const proposal = draft.calendarAvailability === undefined ? undefined : validateDraftCalendarAvailability(draft.calendarAvailability); const strictOwner = proposal ? requireTargetAccountId(draft.accountId) : undefined; const { storage, syncEngine, accountId: owner } = strictOwner ? { ...await resolveNamedOrActiveAccountTarget(strictOwner), accountId: strictOwner } - : await resolveAccountTarget(draft.accountId); + : await resolveNamedOrActiveAccountTarget(draft.accountId); if (!syncEngine) { return { success: false, error: 'No sync engine for account' }; } @@ -667,13 +670,18 @@ export async function writeLocalDraftRow(storage: ReturnType { +export async function deleteDraftsForThread(accountId: string | null | undefined, threadId: string): Promise { if (!threadId) return; - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) return; @@ -743,7 +751,8 @@ export function registerDraftHandlers(): void { // Get the drafts folder name ipcMain.handle('drafts:get-folder', async (_event, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); + // Strict: another mailbox's Drafts path is not this account's answer. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); const folderPath = await findDraftsFolderPath(storage); return { success: true, data: folderPath }; } catch (error: any) { @@ -784,7 +793,9 @@ export function registerDraftHandlers(): void { if (!Array.isArray(messageIds) || messageIds.length === 0) { return { success: true, data: null }; } - const { storage } = await resolveAccountTarget(accountId); + // Strict: Message-IDs exist in every account that got the thread, so a + // fallback would reopen ANOTHER mailbox's draft in this composer. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) return { success: true, data: null }; const placeholders = messageIds.map(() => '?').join(','); @@ -837,11 +848,21 @@ export function registerDraftHandlers(): void { namedAccount: !!options.accountId, namedAccountIsActive: options.accountId ? options.accountId === getCurrentAccountId() : null, }); - // Resolve the draft's OWNING account (falls back to active). Without this the - // delete ran against the active account's DB/engine — the wrong ones when the - // draft belongs to another account (e.g. opened from All Inboxes) — so it - // removed 0 rows and the draft was undeletable ("immortal draft"). - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(options.accountId); + // Resolve the draft's OWNING account (the active one when none is named). + // Without this the delete ran against the active account's DB/engine — the + // wrong ones when the draft belongs to another account (e.g. opened from All + // Inboxes) — so it removed 0 rows and the draft was undeletable ("immortal + // draft"). STRICT: a discard is keyed by thread id or Message-ID, which + // exist in every account, so an unavailable named account is refused rather + // than deleting the active account's drafts of the same conversation. + let resolved: Awaited>; + try { + resolved = await resolveNamedOrActiveAccountTarget(options.accountId); + } catch (error) { + draftLog('delete:refused', { error: errorDiagnostic(error) }); + return { success: false, error: (error as Error).message }; + } + const { storage, syncEngine, accountId: owner } = resolved; draftLog('delete:resolved', { dbFile: dbFileOf(storage), hasSyncEngine: !!syncEngine, @@ -1036,7 +1057,9 @@ export function registerDraftHandlers(): void { const targets = accountIds.length ? accountIds : [undefined as any]; for (const accountId of targets) { try { - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + // Strict: a named account that cannot be resolved is reported as that + // account's error below — never a sweep of the ACTIVE account's drafts. + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) continue; diff --git a/apps/desktop/electron/ipc/email-handlers.ts b/apps/desktop/electron/ipc/email-handlers.ts index ec5b02f3..3af635cf 100644 --- a/apps/desktop/electron/ipc/email-handlers.ts +++ b/apps/desktop/electron/ipc/email-handlers.ts @@ -10,7 +10,7 @@ import { folderLogLabel, createDeferredFetchError, errorDiagnostic, fetchBodyQue import { app, ipcMain, dialog, shell, type IpcMainInvokeEvent } from 'electron'; import ICAL from 'ical.js'; -import { resolveAccountTarget, resolveNamedOrActiveAccountTarget, requireTargetAccountId } from '../services/account-target'; +import { resolveNamedOrActiveAccountTarget, requireTargetAccountId } from '../services/account-target'; import { getAntivirusScanService } from '../services/antivirus-scan-service'; import { attachmentErrorMessage, MAX_ATTACHMENT_BYTES, readCachedAttachment, resolveAttachmentFile } from '../services/attachment-cache'; import { AttachmentDownloadProtection, downloadScanners, setAttachmentOperationProtection, writeProtectedAttachment } from '../services/attachment-download-protection'; @@ -743,7 +743,7 @@ export function registerEmailHandlers(): void { deferBodyPrefetch(); // Unified view: read/fetch from the email's own account (DB + engine). - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1236,7 +1236,7 @@ export function registerEmailHandlers(): void { params: { query: ParsedSearchQuery; folderId?: string; accountId?: string; maxFetch?: number }, ) => { try { - const { storage, syncEngine } = await resolveAccountTarget(params.accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(params.accountId); if (!syncEngine) return { success: false, error: 'No sync engine for account' }; if (typeof (syncEngine as any).serverSearch !== 'function') { return { success: false, error: 'Server search unsupported' }; @@ -1271,7 +1271,7 @@ export function registerEmailHandlers(): void { ipcMain.handle('emails:markRead', async (_event, emailId: string, read: boolean, accountId?: string) => { try { // Route to the row's own account (unified view) or the active one. - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1325,7 +1325,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:markStarred', async (_event, emailId: string, starred: boolean, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1417,7 +1417,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToFolder', async (_event, emailId: string, destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const res = await moveOrCopyOne(storage, syncEngine, emailId, destinationFolderId, 'move'); if (!res.ok) return { success: false, error: res.error }; // Recount once. Await so the renderer's follow-up loadFolders() reads fresh @@ -1434,7 +1434,7 @@ export function registerEmailHandlers(): void { /** Restore tagged Trash members to Inbox, including rows whose primary copy is elsewhere. */ ipcMain.handle('emails:restoreFromTrash', async (_event, emailIds: string[], accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const data = await restoreEmailsFromTrash(storage, syncEngine, emailIds); return { success: data.failedIds.length === 0, data }; } catch (error) { @@ -1449,7 +1449,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:copyToFolder', async (_event, emailId: string, destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const res = await moveOrCopyOne(storage, syncEngine, emailId, destinationFolderId, 'copy'); if (!res.ok) return { success: false, error: res.error }; try { await storage.recalculateFolderCounts(); } catch (err) { logger.error('[email-handlers] recalculateFolderCounts failed:', err); } @@ -1463,7 +1463,7 @@ export function registerEmailHandlers(): void { /** Bulk Move / Copy many emails to one destination folder (toolbar/bulk-bar picker). */ ipcMain.handle('emails:bulkMoveToFolder', async (_event, emailIds: string[], destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); let moved = 0; for (const id of emailIds) { const res = await moveOrCopyOne(storage, syncEngine, id, destinationFolderId, 'move'); @@ -1479,7 +1479,7 @@ export function registerEmailHandlers(): void { ipcMain.handle('emails:bulkCopyToFolder', async (_event, emailIds: string[], destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); let copied = 0; for (const id of emailIds) { const res = await moveOrCopyOne(storage, syncEngine, id, destinationFolderId, 'copy'); @@ -1496,7 +1496,7 @@ export function registerEmailHandlers(): void { /** Mailbox storage quota (bytes) for the account, or null when unavailable. */ ipcMain.handle('account:getQuota', async (_event, accountId?: string) => { try { - const { syncEngine } = await resolveAccountTarget(accountId); + const { syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const quota = syncEngine ? await syncEngine.getQuota() : null; return { success: true, data: quota }; } catch (error) { @@ -1510,7 +1510,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToTrash', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1583,7 +1583,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToSpam', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const outcome = await applyUserSpamVerdict({ storage, queue: (syncEngine as any)?.operationQueue ?? null, @@ -1609,7 +1609,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveFromSpam', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const outcome = await applyUserSpamVerdict({ storage, queue: (syncEngine as any)?.operationQueue ?? null, @@ -1627,7 +1627,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:archive', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1694,7 +1694,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:delete', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1832,10 +1832,11 @@ export function registerEmailHandlers(): void { if (typeof emailId !== 'string' || !emailId) { return { success: false, error: 'Invalid emailId' }; } - // Route to the email's OWNING account (falls back to active). In All + // Route to the email's OWNING account (the active one when none is named; + // a named one that cannot be resolved is an error). In All // Inboxes the opened mail can belong to a non-active account, so // requireStorage() (active account) missed it → "Email not found". - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) return { success: false, error: 'Email not found' }; @@ -1891,7 +1892,7 @@ export function registerEmailHandlers(): void { return await downloads.operations.run(emailId, targetAccountId, 'calendar-event.ics', async operation => { // Owning-account routing — otherwise "Add to calendar" on an All-Inboxes // mail from a non-active account failed with "Email not found". - const { storage, syncEngine } = await resolveAccountTarget(targetAccountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(targetAccountId); await operation.assertCurrent(); const email = await storage.getEmail(emailId); await operation.assertCurrent(); @@ -1958,7 +1959,7 @@ export function registerEmailHandlers(): void { return { success: false, error: 'Invalid emailId' }; } // Owning-account routing so the persisted flag lands in the RIGHT DB. - const { storage } = await resolveAccountTarget(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); await storage.updateEmail(emailId, { calendarAdded: Boolean(added) }); return { success: true }; } catch (error) { diff --git a/apps/desktop/electron/ipc/image-trust-handlers.ts b/apps/desktop/electron/ipc/image-trust-handlers.ts index dd606e85..edbc3aa2 100644 --- a/apps/desktop/electron/ipc/image-trust-handlers.ts +++ b/apps/desktop/electron/ipc/image-trust-handlers.ts @@ -6,8 +6,9 @@ * Every channel takes an optional `accountId`. The reading pane can show a * message of an account that is not the active one (the unified "All Inboxes" * view), and "Load images" on it must be remembered in THAT account's database - * — a sender address exists in every mailbox, so the lenient resolver's - * fall-back-to-active would silently file account B's choice under account A. + * — a sender address exists in every mailbox, so a fall-back-to-active (what + * the since-removed lenient resolver did) would silently file account B's + * choice under account A. * A named account is therefore resolved strictly (an unknown one is an error * the renderer sees and retries); no id means the active account, as before. */ diff --git a/apps/desktop/electron/ipc/label-handlers.ts b/apps/desktop/electron/ipc/label-handlers.ts index df5427ed..3fb4a5ae 100644 --- a/apps/desktop/electron/ipc/label-handlers.ts +++ b/apps/desktop/electron/ipc/label-handlers.ts @@ -9,38 +9,24 @@ import { failureCause, labelLogLabel, createLogger, type LabelInput } from '@sarvinbox/core'; import { ipcMain } from 'electron'; -import { ensureAccountRuntime } from '../services/accounts-runtime'; +import { resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { setEmailLabel } from '../services/email-labels'; -import { requireStorage, getCurrentAccountId, getSyncEngine } from '../shared'; +import { requireStorage } from '../shared'; const logger = createLogger('label-handlers'); -// Labels live in each account's own DB. Resolve the target account's storage so -// the unified "All Inboxes" view can list/create labels for the account a -// message actually belongs to, not just the active one. -async function labelStorageFor(accountId?: string) { - if (accountId && accountId !== getCurrentAccountId()) { - const rt = await ensureAccountRuntime(accountId); - if (rt?.storage) return rt.storage; - } - return requireStorage(); -} - -// The sync engine for the label's account — used to mirror an opt-in label to -// the server. Active account uses the live engine; a foreign account uses its -// runtime's engine (which may not be connected — caller handles that). -async function labelEngineFor(accountId?: string) { - if (accountId && accountId !== getCurrentAccountId()) { - const rt = await ensureAccountRuntime(accountId); - return rt?.syncEngine ?? null; - } - return getSyncEngine(); -} +// Labels live in each account's own DB. Resolve the target account's storage +// (and engine, to mirror an opt-in label to the server) so the unified "All +// Inboxes" view can list/create labels for the account a message actually +// belongs to, not just the active one. STRICT: a label is keyed by its name, +// which can exist in every account, so a named account that cannot be resolved +// is an error the renderer sees — never a label listed from, created in, or +// tagged onto the ACTIVE mailbox instead. No id means the active account. export function registerLabelHandlers(): void { ipcMain.handle('labels:list', async (_event, accountId?: string) => { try { - const storage = await labelStorageFor(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); return { success: true, data: await storage.getLabels() }; } catch (error) { return { success: false, error: (error as Error).message }; @@ -49,7 +35,9 @@ export function registerLabelHandlers(): void { ipcMain.handle('labels:create', async (_event, input: LabelInput, accountId?: string) => { try { - const storage = await labelStorageFor(accountId); + // The engine belongs to the same account; it may not be connected — + // handled below. + const { storage, syncEngine: engine } = await resolveNamedOrActiveAccountTarget(accountId); const name = (input?.name || '').trim(); if (!name) return { success: false, error: 'Label name is required' }; // Opt-in: also CREATE the label as a folder on the mail server so it shows @@ -58,7 +46,6 @@ export function registerLabelHandlers(): void { let syncedToServer = false; if (input?.syncToServer) { try { - const engine = await labelEngineFor(accountId); if (engine?.isConnected?.()) { syncedToServer = await engine.createServerLabel(name); } else { @@ -102,10 +89,9 @@ export function registerLabelHandlers(): void { ipcMain.handle('emails:setLabel', async (_event, emailId: string, label: string, on: boolean, accountId?: string) => { try { // Route to the email's own account (unified "All Inboxes" rows can belong - // to a non-active account) so the tag is written to the right DB. - const storage = accountId && accountId !== getCurrentAccountId() - ? ((await ensureAccountRuntime(accountId))?.storage ?? requireStorage()) - : requireStorage(); + // to a non-active account) so the tag is written to the right DB — and + // only there: an unavailable named account is an error, not the active DB. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); if (!(label || '').trim()) return { success: false, error: 'Label is required' }; if (await setEmailLabel(storage, emailId, label, on) === 'missing') return { success: false, error: 'Email not found' }; return { success: true }; diff --git a/apps/desktop/electron/ipc/pgp-handlers.ts b/apps/desktop/electron/ipc/pgp-handlers.ts index 60aaa218..8cdeea94 100644 --- a/apps/desktop/electron/ipc/pgp-handlers.ts +++ b/apps/desktop/electron/ipc/pgp-handlers.ts @@ -16,7 +16,7 @@ import { createLogger, errorDiagnostic, waitForAbortableOperation } from '@sarvi import { PGP_ENCRYPTED_PLACEHOLDER, PGP_FAILURE_MESSAGE, type PgpFlowCode } from '@sarvinbox/core/pgp'; import { dialog, ipcMain } from 'electron'; -import { requireTargetAccountId, resolveAccountTarget } from '../services/account-target'; +import { requireTargetAccountId, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { attachmentScanRequired, getAttachmentOperationProtection, writeProtectedAttachment, type ProtectedAttachmentOperation } from '../services/attachment-download-protection'; import { markDownloadedFromInternet } from '../services/mark-downloaded'; import { lockedSigningKeyFor, logPgpFailure, pgpFlowCode } from '../services/pgp-failure'; @@ -270,7 +270,7 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { /** The stored message's raw source and sender, from the account that owns it. */ export async function storedSourceFor(emailId: string, accountId?: string): Promise { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) return null; const fromAddress = email.fromAddress ?? null; diff --git a/apps/desktop/electron/ipc/spam-handlers.ts b/apps/desktop/electron/ipc/spam-handlers.ts index dd526ef2..be5d7426 100644 --- a/apps/desktop/electron/ipc/spam-handlers.ts +++ b/apps/desktop/electron/ipc/spam-handlers.ts @@ -6,11 +6,18 @@ * section of the settings blob (Security > Blocklists), which main reads from * the core DB mirror and hears about through `appSettings:set` — see * reputation-service.ts. + * + * Every channel's optional `accountId` is resolved STRICTLY: a named account + * that cannot be resolved is an error the renderer sees, never the active + * mailbox. The trusted-sender list is keyed by a sender address, which exists + * in every mailbox, and a trusted sender's authenticated mail bypasses the + * filter — so a fallback would have switched the filter off for that sender in + * the wrong account. No id means the active account, as before. */ -import { SUSPICIOUS_THRESHOLD, createLogger, type SpamUserVerdict } from '@sarvinbox/core'; +import { SUSPICIOUS_THRESHOLD, accountLogLabel, createLogger, errorDiagnostic, type SpamUserVerdict } from '@sarvinbox/core'; import { ipcMain } from 'electron'; -import { resolveAccountTarget } from '../services/account-target'; +import { requireNamedOrActiveStorage, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { reportSenderVerdict } from '../services/reputation-service'; import { getSpamReputationState, kickSpamReputation } from '../services/spam-reputation-service'; import { applyUserSpamVerdict, trustSender, type VerdictDeps } from '../services/spam-verdict-actions'; @@ -26,7 +33,7 @@ export function verdictDepsOf(storage: VerdictDeps['storage'], syncEngine: unkno /** What a verdict needs for one account: its storage, its server queue, the report hook. */ async function verdictDepsFor(accountId?: string): Promise { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); return verdictDepsOf(storage, syncEngine); } @@ -41,7 +48,7 @@ export function registerSpamHandlers(): void { // Everything the filter had an opinion on — for the Security page's Spam tab. ipcMain.handle('spam:listJudged', async (_event, limit?: number, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); return { success: true, data: storage.getSpamJudgedEmails(typeof limit === 'number' ? limit : 200, SUSPICIOUS_THRESHOLD) }; } catch (error) { return fail(error); @@ -56,7 +63,7 @@ export function registerSpamHandlers(): void { const outcome = await applyUserSpamVerdict(deps, emailId, verdict); return outcome.success ? { success: true, data: { moved: outcome.moved } } : { success: false, error: outcome.error }; } catch (error) { - logger.error('spam:setUserVerdict failed:', error); + logger.error(`spam:setUserVerdict failed for account ${accountLogLabel(accountId, '(active)')}:`, errorDiagnostic(error)); return fail(error); } }); @@ -64,11 +71,11 @@ export function registerSpamHandlers(): void { // "Trust this sender": their authenticated mail bypasses the filter from now on. ipcMain.handle('spam:trustSender', async (_event, address: string, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - await trustSender(storage, address); + await trustSender(await requireNamedOrActiveStorage(accountId), address); return { success: true }; } catch (error) { - logger.error('spam:trustSender failed:', error); + // Class and code only: the message names the account (an address). + logger.error(`spam:trustSender failed for account ${accountLogLabel(accountId, '(active)')}:`, errorDiagnostic(error)); return fail(error); } }); @@ -76,16 +83,14 @@ export function registerSpamHandlers(): void { // The Security page's list, and its remove. ipcMain.handle('spam:listTrustedSenders', async (_event, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - return { success: true, data: await storage.getTrustedSenders() }; + return { success: true, data: await (await requireNamedOrActiveStorage(accountId)).getTrustedSenders() }; } catch (error) { return fail(error); } }); ipcMain.handle('spam:untrustSender', async (_event, address: string, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - await storage.untrustSender(address); + await (await requireNamedOrActiveStorage(accountId)).untrustSender(address); return { success: true }; } catch (error) { return fail(error); diff --git a/apps/desktop/electron/ipc/sync-handlers.ts b/apps/desktop/electron/ipc/sync-handlers.ts index 5177760f..7324c877 100644 --- a/apps/desktop/electron/ipc/sync-handlers.ts +++ b/apps/desktop/electron/ipc/sync-handlers.ts @@ -9,6 +9,7 @@ import { failureCause, folderLogLabel, accountLogLabel, withTimeout, limitTransp import { ipcMain } from 'electron'; import { identifyClient } from '../sentry'; +import { noteVerifiedAccount } from '../services/account-add-proof'; import { ensureAccountRuntime, accountInboxUnread, accountDbExists } from '../services/accounts-runtime'; // Static import (not require()): the bundled main.js has no on-disk services // file, so a runtime require() throws "Cannot find module". @@ -422,9 +423,11 @@ export function registerSyncHandlers(): void { // never runs and EVERY IPC fails "Storage not initialized" — the app bricks // despite the account's DB being safe on disk. The renderer still hands us // the accountId here, so activate it ourselves. Guarded by accountDbExists - // so we only REUSE an existing DB, never create a blank one. - if (!getSyncEngine() && accountId && accountDbExists(accountId)) { - await ensureAccountRuntime(accountId); + // so we only REUSE an existing DB, never create a blank one, and by the + // registry (inside ensureAccountRuntime) so a configured account's DB is + // the only one adopted. The pointer moves only once the runtime opened: + // an id that was refused must not leave main on an empty slot. + if (!getSyncEngine() && accountId && accountDbExists(accountId) && await ensureAccountRuntime(accountId)) { setCurrentAccount(accountId); logger.info(`[Main] imap:connect self-activated account ${accountLogLabel(accountId)} (storage was uninitialized)`); } @@ -854,7 +857,12 @@ export function registerSyncHandlers(): void { } } probeConfig = await applyCertificatePin(probeConfig, 'imap', vaultIdCandidates(accountId, config.username, config.host)); - return probeImapCredentials(probeConfig); + const probe = await probeImapCredentials(probeConfig); + // Main's own proof that this address signed in: the one thing that lets + // accounts:setActive open a database for an account not yet in the + // registry (the add flow). See account-add-proof. + if (probe.success) noteVerifiedAccount(config.username, config.host); + return probe; }, () => imapCertificateRequest(event, config, accountId))); /** @@ -1371,6 +1379,8 @@ export function registerSyncHandlers(): void { return { success: true, data: { unread: await totalUnread(getStorageFor(accountId) ?? getStorage()), skipped: true } }; } + // Registry-checked inside: an account that is not configured (a removed + // one the renderer's timer still names) gets no runtime and no database. const rt = await ensureAccountRuntime(accountId); if (!rt?.storage || !rt.syncEngine) return { success: false, error: 'Runtime unavailable' }; const engine = rt.syncEngine; diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 93e51587..da35ec4b 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -40,11 +40,8 @@ import { } from './services/accounts-registry'; import { PRIMARY_DB_FILE, - ensureAccountRuntime, + activatePersistedAccount, loadPrimaryAccountId, - savePrimaryAccountId, - legacyDbExists, - accountDbExists, cleanupOrphanedAccountDbs, cleanupStaleUserDataArtifacts, } from './services/accounts-runtime'; @@ -156,8 +153,6 @@ import { setSystemSuspended, getAccountIdForStorage, sendToWindow, - setCurrentAccount, - hasAccountRuntime, } from './shared'; import { resolveAppIconPath } from './utils/app-icon'; import { devServerUrlFor, isDevBuild, isReleaseBundle } from './utils/dev-mode'; @@ -752,22 +747,9 @@ async function initializeAccountRegistry(): Promise { const activeId = getRegistryActiveAccountId(); if (!activeId) return; - // Mirror accounts:setActive's legacy-adopt rule: the FIRST account to - // activate claims the existing sarvinbox.db (only when it already exists); - // fresh installs never create it and use per-id DBs. - if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(activeId); - - // Only activate when the account's DB can be resolved — the recorded primary - // (legacy sarvinbox.db) or an existing per-id DB. Never spin up a blank - // mailbox for an id whose data isn't on disk. - const isPrimary = loadPrimaryAccountId() === activeId && legacyDbExists(); - if (!isPrimary && !accountDbExists(activeId)) { - logger.info('[Main] Persisted active account has no DB yet — deferring to renderer:', accountLogLabel(activeId)); - return; - } - - setCurrentAccount(activeId); - if (!hasAccountRuntime(activeId)) await ensureAccountRuntime(activeId); + // Registry-checked, and the pointer moves only once the runtime is open: + // see activatePersistedAccount. + if (!(await activatePersistedAccount(activeId))) return; rebindOutboxStorage(); logger.info('[Main] Auto-activated persisted account:', accountLogLabel(activeId)); } catch (e) { diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index 292b5012..254d74e0 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -807,10 +807,10 @@ contextBridge.exposeInMainWorld('electronAPI', { upsertCategoryDefinition: (def: any) => ipcRenderer.invoke('ai:upsertCategoryDefinition', def), deleteCategoryDefinition: (slug: string) => ipcRenderer.invoke('ai:deleteCategoryDefinition', slug), toggleCategoryDefinition: (slug: string, enabled: boolean) => ipcRenderer.invoke('ai:toggleCategoryDefinition', slug, enabled), - getThreadSummary: (threadId: string) => - ipcRenderer.invoke('ai:getThreadSummary', threadId), - saveThreadSummary: (summary: any) => - ipcRenderer.invoke('ai:saveThreadSummary', summary), + getThreadSummary: (threadId: string, accountId?: string) => + ipcRenderer.invoke('ai:getThreadSummary', threadId, accountId), + saveThreadSummary: (summary: any, accountId?: string) => + ipcRenderer.invoke('ai:saveThreadSummary', summary, accountId), // First-email split cache — every call names its account (never the active one by default). getFirstSplit: (accountId: string, threadId: string, options?: { withSource?: boolean }) => ipcRenderer.invoke('ai:firstSplit:get', accountId, threadId, options), @@ -894,7 +894,7 @@ contextBridge.exposeInMainWorld('electronAPI', { // Multi-account: flip the active account (main resolves storage/sync/SMTP to it) accounts: { - setActive: (accountId: string) => ipcRenderer.invoke('accounts:setActive', accountId), + setActive: (accountId: string, options?: { adding?: boolean }) => ipcRenderer.invoke('accounts:setActive', accountId, options), rekey: (oldId: string, newId: string) => ipcRenderer.invoke('accounts:rekey', oldId, newId), remove: (accountId: string) => ipcRenderer.invoke('accounts:remove', accountId), // Durable DB-backed registry (source of truth). list → hydrate on startup; @@ -1818,9 +1818,16 @@ export interface ElectronAPI { Promise<{ success: boolean; data?: { deleted: boolean }; error?: string }>; toggleCategoryDefinition: (slug: string, enabled: boolean) => Promise<{ success: boolean; error?: string }>; - getThreadSummary: (threadId: string) => + /** + * The cached summary of a thread, in the account that owns it (the + * active one when `accountId` is omitted). Thread ids repeat across + * accounts, so a named account that cannot be resolved fails rather than + * answering from the active account's cache. + */ + getThreadSummary: (threadId: string, accountId?: string) => Promise<{ success: boolean; data?: ThreadSummaryRecord | null; error?: string }>; - saveThreadSummary: (summary: any) => + /** Cache a summary in the account that owns the thread — strictly, as above. */ + saveThreadSummary: (summary: any, accountId?: string) => Promise<{ success: boolean; error?: string }>; /** * The first-email split cache row plus main's CURRENT key for the thread @@ -1913,7 +1920,13 @@ export interface ElectronAPI { discardAll: () => Promise<{ success: boolean; data?: { removed: number }; error?: string }>; }; accounts: { - setActive: (accountId: string) => Promise<{ success: boolean; error?: string }>; + /** + * Point main at a configured account. `adding: true` only from the add + * flow, whose new account is not in the registry until its first connect + * succeeds; any other id the registry does not list is refused + * (`success: false`) and main stays where it was. + */ + setActive: (accountId: string, options?: { adding?: boolean }) => Promise<{ success: boolean; error?: string }>; rekey: (oldId: string, newId: string) => Promise<{ success: boolean; error?: string }>; /** * `revocation` (OAuth accounts only): what happened to the grant at the diff --git a/apps/desktop/electron/services/account-add-proof.ts b/apps/desktop/electron/services/account-add-proof.ts new file mode 100644 index 00000000..90b8555f --- /dev/null +++ b/apps/desktop/electron/services/account-add-proof.ts @@ -0,0 +1,52 @@ +/** + * Main's own proof that an account being ADDED really signed in. + * + * `accounts:setActive` opens (and creates) a mailbox database only for an + * account the registry lists — except while one is being added: the add flow + * points main at the new account before its first connect, and the renderer + * writes the registry row only once that connect succeeds. That exception used + * to rest on the renderer's word alone (`{ adding: true }`), so any id could be + * activated unregistered, any number of times, each one a new database, an + * open storage and a sync engine nobody closed. + * + * Now the exception needs a proof main recorded itself: a successful + * `imap:probeCredentials` for that address and host. Every add path probes + * first — `addAccount` itself, and the onboarding steps that pass + * `alreadyVerified` (email setup, Sarv sign-in) probe just before. A proof + * names exactly one account id (`accountIdFor(username, host)`, the id the add + * flow mints), is good for one activation, and expires. + */ +import { accountIdFor } from '@sarvinbox/core'; + +/** How long after its probe an add may still activate the new account. */ +export const ADD_PROOF_TTL_MS = 10 * 60_000; +/** Proofs kept at once; the oldest goes first. Bounded: they are cheap, but not free. */ +const MAX_PROOFS = 16; + +/** account id → when its probe succeeded. Memory only: a proof never outlives the process. */ +const proofs = new Map(); + +/** Record that `username` on `host` just signed in (a successful probe). */ +export function noteVerifiedAccount(username: unknown, host: unknown, now: number = Date.now()): void { + if (typeof username !== 'string' || typeof host !== 'string' || !username.trim() || !host.trim()) return; + const id = accountIdFor(username, host); + proofs.delete(id); // re-insert as the newest + proofs.set(id, now); + while (proofs.size > MAX_PROOFS) proofs.delete(proofs.keys().next().value as string); +} + +/** + * Whether `accountId` has an unused, unexpired proof — and USE it: a proof + * admits one activation. An expired one is dropped either way. + */ +export function takeVerifiedAccount(accountId: string, now: number = Date.now()): boolean { + const at = proofs.get(accountId); + if (at === undefined) return false; + proofs.delete(accountId); + return now - at >= 0 && now - at <= ADD_PROOF_TTL_MS; +} + +/** Forget every proof. Tests only. */ +export function clearVerifiedAccounts(): void { + proofs.clear(); +} diff --git a/apps/desktop/electron/services/account-target.ts b/apps/desktop/electron/services/account-target.ts index 656b5853..f2bd5a5e 100644 --- a/apps/desktop/electron/services/account-target.ts +++ b/apps/desktop/electron/services/account-target.ts @@ -7,26 +7,16 @@ import { getCurrentAccountId, } from '../shared'; -import { readRegistryAccounts } from './accounts-registry'; +import { isRegisteredAccountId } from './accounts-registry'; import { ensureAccountRuntime } from './accounts-runtime'; type AccountStorage = ReturnType; type AccountSyncEngine = ReturnType; -/** - * Is `accountId` one of the configured accounts? Read with the THROWING - * registry reader: an unreadable registry and an empty one are the same value - * and opposite facts, so "could not find out" must surface as an error, never - * as "not registered" (nor as "registered"). - */ -function isRegisteredAccount(accountId: string): boolean { - return readRegistryAccounts().some((account) => account.id === accountId); -} - /** Resolve a download's owner once, without falling back from a named mailbox. */ export function requireTargetAccountId(accountId?: string): string { const target = accountId === undefined ? getCurrentAccountId() : accountId; - if (typeof target !== 'string' || !target || !isRegisteredAccount(target)) { + if (typeof target !== 'string' || !target || !isRegisteredAccountId(target)) { throw new Error('The attachment account is unavailable. Select its mailbox and try again.'); } return target; @@ -34,26 +24,21 @@ export function requireTargetAccountId(accountId?: string): string { /** * The storage + sync engine of one SPECIFIC, non-active account: its open - * runtime, or one opened now. Null when the account cannot be resolved (unknown, - * held for maintenance, primary not established yet). The one lookup both - * resolvers below share, so the lenient and the strict answer can never - * disagree about which database an account id names. + * runtime, or — only when the registry lists it — one opened now. Null when + * the account cannot be resolved (unknown or removed, held for maintenance, + * primary not established yet). A registry that cannot be read throws. * - * `strict` opens a runtime only for an account the registry lists. - * `ensureAccountRuntime` creates a new, migrated, EMPTY database (plus a sync - * engine and a registered runtime) for any id it is handed — so a removed - * account's id arriving late (a background request queued before the account - * was deleted) would recreate a blank mailbox under the dead id, which then - * joins every all-accounts loop. A registry that cannot be read throws. + * The registry is checked HERE as well as inside `ensureAccountRuntime`, so + * this module's promise ("never a database created for an id that is not + * configured") does not rest on a check two modules away. */ async function lookupAccountRuntime( accountId: string, - { strict = false }: { strict?: boolean } = {}, ): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine } | null> { let storage = getStorageFor(accountId); let syncEngine = getSyncEngineFor(accountId); if (!storage) { - if (strict && !isRegisteredAccount(accountId)) return null; + if (!isRegisteredAccountId(accountId)) return null; const rt = await ensureAccountRuntime(accountId); storage = rt?.storage ?? null; syncEngine = rt?.syncEngine ?? null; @@ -62,48 +47,40 @@ async function lookupAccountRuntime( } /** - * Resolve the storage + sync engine for an operation, honoring a per-row - * `accountId` when acting on a message from the unified "All Inboxes" view (whose - * rows can belong to non-active accounts). Falls back to the active account when - * no accountId is given (the normal single-account path). Ensures the target - * account's runtime exists first, so we never silently hit the wrong DB — the - * root cause of the mark-read "Email not found" loop across accounts. + * Resolve an operation's storage and sync engine, honoring a per-row + * `accountId` (the unified "All Inboxes" view shows rows of non-active + * accounts). With no id, or the active account's id, it is the active account + * (the single-account path). A NAMED account must resolve to its own runtime: + * an unknown, removed or unavailable one is an error the caller sees, NEVER a + * fall back to the active mailbox. + * + * There used to be a lenient twin that fell back to the active account. For an + * email-id key that only turned into "Email not found" (email ids are random + * per insert, so another account's id is in no other database) — but thread + * ids, Message-IDs, sender addresses, label and folder names exist in EVERY + * account's database, and on that fallback "trust this sender" bypassed the + * spam filter in the wrong mailbox, a discard deleted the active account's + * drafts of the same conversation, and a label was created in the wrong + * mailbox. No flow needed the fallback, so it is gone; every caller resolves + * strictly. * - * LENIENT: an account that cannot be resolved also falls back to the active - * one. Anything that WRITES data keyed by ids that exist in every account (a - * thread id is derived from headers, so the same one lives in each account's - * database) must use {@link requireAccountStorage} instead. + * `accountId` in the result says whose storage it is: the named account, or + * the active account's id (null on the pre-account default slot) — what + * per-account stores (the attachment cache, draft meeting metadata) key by. * * Lives here rather than in the IPC module because the `sarv-attachment://` * protocol handler needs the same resolution and must not import the IPC layer. */ -export async function resolveAccountTarget( - accountId?: string, -): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine; accountId: string | null }> { - if (accountId && accountId !== getCurrentAccountId()) { - const found = await lookupAccountRuntime(accountId); - if (found) return { ...found, accountId }; - } - // `accountId` says whose storage this is after the fallback (null on the - // pre-account default slot) — what per-account stores key by. - return { storage: requireStorage(), syncEngine: getSyncEngine(), accountId: getCurrentAccountId() }; -} - -/** - * Resolve a mutation's storage and sync engine. A named account must resolve - * to its own runtime; an unavailable or removed account is an error instead - * of a fallback to the active mailbox. Requests without an id use the active - * account, preserving the single-account path. - */ export async function resolveNamedOrActiveAccountTarget( - accountId?: string, -): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine }> { - if (!accountId || accountId === getCurrentAccountId()) { - return { storage: requireStorage(), syncEngine: getSyncEngine() }; + accountId?: string | null, +): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine; accountId: string | null }> { + const activeId = getCurrentAccountId(); + if (!accountId || accountId === activeId) { + return { storage: requireStorage(), syncEngine: getSyncEngine(), accountId: activeId }; } - const found = await lookupAccountRuntime(accountId, { strict: true }); + const found = await lookupAccountRuntime(accountId); if (!found) throw new Error(`Account ${accountId} is not available`); - return found; + return { ...found, accountId }; } /** @@ -116,18 +93,17 @@ export async function resolveNamedOrActiveAccountTarget( * * anything else (an unknown or removed account, maintenance, no id) → * throws; an unreadable registry throws too. * - * The lenient {@link resolveAccountTarget} falls back to the active account, - * which is right for a click on a row and wrong for a cache keyed by thread id: - * the same thread id exists in every account's database, so a fallback would - * silently read account A's cached split for account B's thread, or write B's - * result into A's database. A failed lookup has to be an error the caller sees. + * A cache keyed by thread id is why: the same thread id exists in every + * account's database, so a fallback would silently read account A's cached + * split for account B's thread, or write B's result into A's database. A + * failed lookup has to be an error the caller sees. */ export async function requireAccountStorage(accountId: string): Promise { if (typeof accountId !== 'string' || accountId === '') { throw new Error('requireAccountStorage: an account id is required'); } if (accountId === getCurrentAccountId()) return requireStorage(); - const found = await lookupAccountRuntime(accountId, { strict: true }); + const found = await lookupAccountRuntime(accountId); if (!found) throw new Error(`Account ${accountId} is not available`); return found.storage; } @@ -138,10 +114,9 @@ export async function requireAccountStorage(accountId: string): Promise { return accountId ? requireAccountStorage(accountId) : requireStorage(); diff --git a/apps/desktop/electron/services/accounts-registry.ts b/apps/desktop/electron/services/accounts-registry.ts index cd053e45..74ea2d21 100644 --- a/apps/desktop/electron/services/accounts-registry.ts +++ b/apps/desktop/electron/services/accounts-registry.ts @@ -121,6 +121,20 @@ export function readRegistryAccounts(): RegistryAccount[] { return rows.map(rowToAccount); } +/** + * Is `accountId` one of the configured accounts? Read with the THROWING + * {@link readRegistryAccounts}: "I could not read the registry" surfaces as an + * error, never as "not configured" (nor as "configured"). + * + * The one membership check for anything that opens a mailbox database or + * resolves a named account, so every such path refuses the same ids: a removed + * account's id arriving late, a mistyped one, or one never added. + */ +export function isRegisteredAccountId(accountId: string): boolean { + if (typeof accountId !== 'string' || accountId === '') return false; + return readRegistryAccounts().some((account) => account.id === accountId); +} + /** All accounts in the registry (secrets already excluded). `[]` if the read * fails — only safe for callers that merely DISPLAY or hydrate. */ export function listRegistryAccounts(): RegistryAccount[] { @@ -132,9 +146,70 @@ export function listRegistryAccounts(): RegistryAccount[] { } } -/** Insert or update ONE account (by id). Secrets are stripped before writing. */ +// ===== Removed accounts (tombstones) ========================================== +// +// `accounts:remove` drops the registry row early, but the window keeps the +// account in its own list until the removal returns — which waits for the +// provider to confirm the OAuth sign-out. Any snapshot the window mirrors in that +// time (`accounts:save` after a reconnect or a sending-setup change) used to +// upsert the row straight back, and on the next launch the removed account was +// "configured" again: in the switcher, in every all-accounts loop, its database +// recreated on first touch. A token still on disk did the same through seeding. +// +// So a removed id is remembered, durably, and every upsert drops it. Only adding +// that account again through the add flow (accounts:setActive with a verified +// `adding`) clears it. +const REMOVED_META_KEY = 'removed_account_ids'; +/** Tombstones kept; the oldest goes first. A re-add clears its own anyway. */ +const MAX_REMOVED_IDS = 200; + +function readRemovedAccountIds(): string[] { + const raw = getMeta(REMOVED_META_KEY); + if (!raw) return []; + try { + const parsed: unknown = JSON.parse(raw); + return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string' && id !== '') : []; + } catch { + return []; + } +} + +function writeRemovedAccountIds(ids: string[]): void { + setMeta(REMOVED_META_KEY, ids.length ? JSON.stringify(ids.slice(-MAX_REMOVED_IDS)) : null); +} + +/** Remember that `id` was removed, so no snapshot or seed can re-add it. */ +export function markAccountRemoved(id: string): void { + if (!id) return; + writeRemovedAccountIds([...readRemovedAccountIds().filter((removed) => removed !== id), id]); +} + +/** Forget `id`'s removal: the user is adding that account again. */ +export function clearAccountRemoved(id: string): void { + if (!id) return; + const ids = readRemovedAccountIds(); + if (ids.includes(id)) writeRemovedAccountIds(ids.filter((removed) => removed !== id)); +} + +/** Whether `id` was removed and not added again since. */ +export function isAccountRemoved(id: string): boolean { + return !!id && readRemovedAccountIds().includes(id); +} + +/** + * Insert or update ONE account (by id). Secrets are stripped before writing. + * A removed account (see the tombstones above) is not written. + */ export function upsertRegistryAccount(a: RegistryAccount): void { if (!a?.id || !a.email) return; + if (isAccountRemoved(a.id)) { + logger.info('[Registry] not re-adding a removed account', accountLogLabel(a.id)); + return; + } + writeRegistryRow(a); +} + +function writeRegistryRow(a: RegistryAccount): void { const imap = stripSecrets(a.imapConfig); const smtp = stripSecrets(a.smtpConfig); const now = Date.now(); @@ -177,10 +252,17 @@ export function upsertRegistryAccount(a: RegistryAccount): void { */ export function upsertRegistryAccounts(accounts: RegistryAccount[]): void { if (!Array.isArray(accounts) || accounts.length === 0) return; + // Removed accounts are dropped from the snapshot (read once, not per row). + const removed = new Set(readRemovedAccountIds()); + const kept = accounts.filter((a) => !a?.id || !removed.has(a.id)); + if (kept.length < accounts.length) { + logger.info(`[Registry] snapshot mirror skipped ${accounts.length - kept.length} removed account(s)`); + } + if (kept.length === 0) return; const tx = getCoreDb().transaction((list: RegistryAccount[]) => { - for (const a of list) upsertRegistryAccount(a); + for (const a of list) if (a?.id && a.email) writeRegistryRow(a); }); - try { tx(accounts); } catch (e) { logger.error('[Registry] bulk upsert failed:', e); } + try { tx(kept); } catch (e) { logger.error('[Registry] bulk upsert failed:', e); } } /** Permanently remove one account row (on account deletion). Idempotent. */ diff --git a/apps/desktop/electron/services/accounts-runtime.ts b/apps/desktop/electron/services/accounts-runtime.ts index b5a1e249..d02bb265 100644 --- a/apps/desktop/electron/services/accounts-runtime.ts +++ b/apps/desktop/electron/services/accounts-runtime.ts @@ -18,10 +18,10 @@ import { SHARED_CONTACTS_FILE, SQLiteStorage } from '@sarvinbox/storage-node'; import { app } from 'electron'; import type { AccountRuntime } from '../shared'; -import { claimDefaultRuntime, getAccountIdForStorage, getAccountRuntime, hasAccountRuntime, registerAccountRuntime, rekeyRuntime, sendToWindow, unregisterRuntime } from '../shared'; +import { claimDefaultRuntime, getAccountIdForStorage, getAccountRuntime, hasAccountRuntime, registerAccountRuntime, rekeyRuntime, sendToWindow, setCurrentAccount, unregisterRuntime } from '../shared'; import { logPath } from '../utils/log-path'; -import { listRegistryAccounts } from './accounts-registry'; +import { isRegisteredAccountId, listRegistryAccounts } from './accounts-registry'; import { deleteAccountAttachments, rekeyAccountAttachments } from './attachment-cache'; import { getMeta, setMeta } from './core-db'; import { getDbEncryptionKey } from './db-key-store'; @@ -227,8 +227,26 @@ export function releaseAccountMaintenance(accountId: string): void { * Returns null (never a wrong/empty DB) when the primary hasn't been * established yet, because the primary's file can't be resolved until then. * Does NOT connect IMAP — storage/engine only; safe to call for background reads. + * + * REGISTRY-CHECKED: a runtime that is not open yet is opened only for an id + * the account registry lists. Opening creates the file when it is missing, so + * without this a removed account's id arriving late (a background request + * queued before the delete, a stale unified-inbox id) recreated a blank, + * migrated mailbox under the dead id, which then joined every all-accounts + * loop. An unknown id answers null like the other refusals; a registry that + * cannot be read THROWS — "could not find out" is not "not configured". + * + * `registryChecked` is for ONE caller: `accounts:setActive`, which has already + * decided — from its own registry read, or, while an account is being added, + * from main's proof that the account just signed in (account-add-proof). The + * add flow points main at the new account BEFORE its first connect, and the + * renderer writes the registry row only once that connect succeeds, so at that + * moment the id is legitimately not listed yet. Nothing else may pass it. */ -export async function ensureAccountRuntime(accountId: string): Promise { +export async function ensureAccountRuntime( + accountId: string, + { registryChecked = false }: { registryChecked?: boolean } = {}, +): Promise { const existing = getAccountRuntime(accountId); if (existing?.storage) return existing; @@ -239,6 +257,11 @@ export async function ensureAccountRuntime(accountId: string): Promise { + if (!isRegisteredAccountId(activeId)) { + logger.info('[Accounts] persisted active account is not configured — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + + // Mirror accounts:setActive's legacy-adopt rule: the FIRST account to + // activate claims the existing sarvinbox.db (only when it already exists); + // fresh installs never create it and use per-id DBs. + if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(activeId); + + // Only activate when the account's DB can be resolved — the recorded primary + // (legacy sarvinbox.db) or an existing per-id DB. + const isPrimary = loadPrimaryAccountId() === activeId && legacyDbExists(); + if (!isPrimary && !accountDbExists(activeId)) { + logger.info('[Accounts] persisted active account has no DB yet — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + + // Open first, point second: a runtime that cannot be opened (held for + // maintenance) must not leave the active pointer on an empty slot. + if (!hasAccountRuntime(activeId) && !(await ensureAccountRuntime(activeId))) { + logger.info('[Accounts] persisted active account could not be opened — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + setCurrentAccount(activeId); + return true; +} + /** True once `ensureAccountRuntime` can resolve DB files (primary established). */ export function canResolveAccountRuntimes(): boolean { return !!loadPrimaryAccountId(); diff --git a/apps/desktop/electron/services/agent-decision-values.ts b/apps/desktop/electron/services/agent-decision-values.ts new file mode 100644 index 00000000..1bf12b0b --- /dev/null +++ b/apps/desktop/electron/services/agent-decision-values.ts @@ -0,0 +1,77 @@ +/** + * The values a renderer may write into an agent decision row when it resolves + * one (`agent:resolveDecision`, `agent:resolveProposal`). + * + * Both handlers used to cast whatever arrived (`as any`) straight into the + * parameterized UPDATE. The SQL was safe, but any string became the row's + * status or action, and the learning code reads those back as its enums — an + * unknown status is a decision no query counts, and a bogus action a user + * correction nothing understands. Each set below is the full enum, checked by + * the compiler (a `Record` over the union fails to build when the core type + * gains or loses a member), so a renderer value outside it is refused. + */ +import type { AgentDecisionStatus, UserActionType } from '@sarvinbox/core'; + +/** + * The statuses a decision can be RESOLVED to. `pending` is the unresolved + * state: writing it from a resolve call would stamp `resolved_at` on a row that + * then reads as still waiting. + */ +const RESOLVED_STATUSES: Readonly, true>> = { + approved: true, + rejected: true, + auto: true, + expired: true, + overridden: true, +}; + +/** + * What the user actually did instead, recorded with the resolution: any + * {@link UserActionType}, plus `dismissed` — what the composer and the agent + * dashboard (and the pipeline's own housekeeping) record when a proposal is + * thrown away without another action. It is not a mail action, so it is not + * in the core union, but it is in the data. + */ +const ACTUAL_ACTIONS: Readonly> = { + read: true, + unread: true, + star: true, + unstar: true, + archive: true, + delete: true, + spam: true, + move: true, + label_add: true, + label_remove: true, + snooze: true, + unsnooze: true, + reply: true, + reply_all: true, + forward: true, + important: true, + unimportant: true, + mute: true, + open: true, + ignore: true, + dismissed: true, +}; + +function isOwnKey(table: T, value: unknown): value is keyof T { + return typeof value === 'string' && Object.prototype.hasOwnProperty.call(table, value); +} + +/** `value` as a resolved decision status, or null when it is not one. */ +export function resolvedDecisionStatus(value: unknown): Exclude | null { + return isOwnKey(RESOLVED_STATUSES, value) ? value : null; +} + +/** + * `value` as a recorded actual action. `undefined` / `null` mean "none given" + * (the row keeps what it had); anything else must be a known action. + */ +export function decisionActualAction( + value: unknown, +): { ok: true; action: UserActionType | 'dismissed' | null } | { ok: false } { + if (value === undefined || value === null) return { ok: true, action: null }; + return isOwnKey(ACTUAL_ACTIONS, value) ? { ok: true, action: value } : { ok: false }; +} diff --git a/apps/desktop/electron/services/attachment-cache.ts b/apps/desktop/electron/services/attachment-cache.ts index 5e809bfe..3f7884c8 100644 --- a/apps/desktop/electron/services/attachment-cache.ts +++ b/apps/desktop/electron/services/attachment-cache.ts @@ -17,7 +17,7 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; -import { resolveAccountTarget } from './account-target'; +import { resolveNamedOrActiveAccountTarget } from './account-target'; import { getDbEncryptionKey } from './db-key-store'; const logger = createLogger('attachment-cache'); @@ -624,7 +624,7 @@ export async function resolveAttachmentFile( throw new AttachmentError('Invalid attachment request', 400); } - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) throw new AttachmentError('Email not found', 404); diff --git a/apps/desktop/electron/services/db-compact.ts b/apps/desktop/electron/services/db-compact.ts index da7bf6dd..f8158617 100644 --- a/apps/desktop/electron/services/db-compact.ts +++ b/apps/desktop/electron/services/db-compact.ts @@ -28,6 +28,7 @@ import { Worker } from 'node:worker_threads'; import { accountLogLabel, + errorDiagnostic, compactionEstimate, formatBytes, hasCompactionHeadroom, @@ -38,7 +39,7 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; -import { getAccountRuntime } from '../shared'; +import { getAccountRuntime, getCurrentAccountId, setCurrentAccount } from '../shared'; import type { CompactWorkerResult } from '../workers/db-compact.worker'; import { @@ -50,6 +51,7 @@ import { releaseAccountMaintenance, } from './accounts-runtime'; import { getDbEncryptionKey } from './db-key-store'; +import { rebindOutboxStorage } from './outbox-service'; @@ -209,6 +211,9 @@ export async function compactAccountDatabase(accountId: string): Promise { + let reopened = false; + for (let attempt = 0; ; attempt++) { + try { + reopened = !!(await ensureAccountRuntime(accountId)); + break; + } catch (error) { + const delay = REOPEN_RETRY_DELAYS_MS[attempt]; + logger.error( + `[Compact] FAILED to reopen ${accountLogLabel(accountId)} after compaction ` + + `(attempt ${attempt + 1} of ${REOPEN_RETRY_DELAYS_MS.length + 1})`, + errorDiagnostic(error), + ); + if (delay === undefined) return; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + if (reopened && wasActive && getCurrentAccountId() === null) { + setCurrentAccount(accountId); try { - await ensureAccountRuntime(accountId); + rebindOutboxStorage(); } catch (error) { - logger.error(`[Compact] FAILED to reopen ${accountLogLabel(accountId)} after compaction`, error); + logger.warn(`[Compact] rebinding the outbox of ${accountLogLabel(accountId)} failed`, errorDiagnostic(error)); } + logger.info(`[Compact] ${accountLogLabel(accountId)} is active again`); } } diff --git a/apps/desktop/electron/shared.ts b/apps/desktop/electron/shared.ts index 2faafaf6..c14c647c 100644 --- a/apps/desktop/electron/shared.ts +++ b/apps/desktop/electron/shared.ts @@ -187,9 +187,12 @@ export function rekeyRuntime(oldId: string, newId: string): void { * Does NOT decide DB ownership — the caller (accounts handler) claims the * default sarvinbox.db slot only for the persisted PRIMARY account, so a * secondary account active on restart never grabs the primary's database. + * + * `null` points back at the pre-account default slot — what an activation that + * failed halfway restores when no account was active before it. */ -export function setCurrentAccount(accountId: string): AccountRuntime { - currentAccountId = accountId; +export function setCurrentAccount(accountId: string | null): AccountRuntime { + currentAccountId = accountId ?? DEFAULT_SLOT; return currentRuntime(); } diff --git a/apps/desktop/src/components/ThreadSummary.tsx b/apps/desktop/src/components/ThreadSummary.tsx index 8c1d3d88..ab2479da 100644 --- a/apps/desktop/src/components/ThreadSummary.tsx +++ b/apps/desktop/src/components/ThreadSummary.tsx @@ -13,9 +13,17 @@ const CAPABILITY_THREAD_SUMMARIZE = 'thread.summarize'; interface ThreadSummaryProps { threadId: string; emails: EmailRecord[]; + /** + * The account that owns the thread (All Inboxes shows other accounts' + * threads). The cache is keyed by thread id, which repeats across accounts, + * so it is read from and written to this account only. Omitted: the active + * account. + */ + accountId?: string | null; } -export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { +export function ThreadSummary({ threadId, emails, accountId }: ThreadSummaryProps) { + const ownerAccountId = accountId ?? undefined; const [summary, setSummary] = useState(null); const [loading, setLoading] = useState(false); const [expanded, setExpanded] = useState(false); @@ -30,7 +38,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { const loadCachedSummary = async () => { try { - const result = await window.electronAPI.ai.getThreadSummary(threadId); + const result = await window.electronAPI.ai.getThreadSummary(threadId, ownerAccountId); if (result.success && result.data) { // Check if summary is still valid (email count matches) if (result.data.emailCount === emails.length) { @@ -56,7 +64,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { }; loadCachedSummary(); - }, [threadId, emails.length]); + }, [threadId, emails.length, ownerAccountId]); const generateSummary = async () => { if (loading || emails.length < 2) return; @@ -146,7 +154,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { emailCount: emails.length, processedAt: Math.floor(Date.now() / 1000), modelUsed: getDefaultProvider()?.model || 'unknown', - }); + }, ownerAccountId); } else { setError('Failed to generate summary'); } diff --git a/apps/desktop/src/components/email-detail/EmailDetail.tsx b/apps/desktop/src/components/email-detail/EmailDetail.tsx index ddde1ead..13d74c96 100644 --- a/apps/desktop/src/components/email-detail/EmailDetail.tsx +++ b/apps/desktop/src/components/email-detail/EmailDetail.tsx @@ -178,6 +178,7 @@ export function EmailDetail(options: EmailReaderOptions = {}) { )} diff --git a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx index bc339c56..a3e2a88b 100644 --- a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx +++ b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx @@ -100,6 +100,8 @@ function savedForm(connection: ConnectedEmail): FormValues { } const EMAIL_CHOICES = ['sarv', 'gmail', 'outlook', 'yahoo', 'other']; +/** A switch to the connected account that the app refused (main stayed on another mailbox). */ +const SWITCH_REFUSED = 'This mailbox could not be opened right now. Try again in a moment.'; const inputClass = 'w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-60'; const primaryClass = 'inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50'; const textButtonClass = 'rounded-md px-2 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50'; @@ -401,6 +403,7 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp try { if (useEmailStore.getState().activeAccountId !== connected.result.accountId) { await useEmailStore.getState().selectAccount(connected.result.accountId); + if (useEmailStore.getState().activeAccountId !== connected.result.accountId) throw new Error(SWITCH_REFUSED); } if (isCurrent(id)) complete({ ...connected, smtp: { ...connected.smtp, password: '' } }); } catch (failure) { if (isCurrent(id)) setError(errorMessage(failure)); } @@ -414,7 +417,12 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp try { const account = useEmailStore.getState().accounts.find((item) => item.id === connected.result.accountId); if (!account) throw new Error('This saved account is unavailable. Choose your provider and connect again.'); - if (useEmailStore.getState().activeAccountId !== account.id) await useEmailStore.getState().selectAccount(account.id); + // A refused switch leaves another mailbox active: connecting now would + // run this account's sign-in on that mailbox's connection. + if (useEmailStore.getState().activeAccountId !== account.id) { + await useEmailStore.getState().selectAccount(account.id); + if (useEmailStore.getState().activeAccountId !== account.id) throw new Error(SWITCH_REFUSED); + } if (!isCurrent(id)) return; // Reconnect uses the saved native vault credentials and starts background // sync. It does not add, delete or replace the existing account. diff --git a/apps/desktop/src/store/helpers.ts b/apps/desktop/src/store/helpers.ts index 0808b4e9..b13148ec 100644 --- a/apps/desktop/src/store/helpers.ts +++ b/apps/desktop/src/store/helpers.ts @@ -924,6 +924,21 @@ const withoutSecrets = (a: StoredAccount): StoredAccount => ({ smtpConfig: stripSecrets(a.smtpConfig as any), }); +/** + * Accounts being removed right now. Their registry row is already gone in main + * while the removal waits (up to the OAuth revocation bound), but the row stays + * in the list here until it returns — and a snapshot mirrored in that window + * would write the row straight back. Main tombstones removed ids as well; this + * keeps them out of the snapshot in the first place. + */ +const notMirrored = new Set(); + +/** Keep `accountId` out of (or let it back into) the registry mirror. */ +export const setAccountMirrored = (accountId: string, mirrored: boolean): void => { + if (mirrored) notMirrored.delete(accountId); + else notMirrored.add(accountId); +}; + export const saveAccounts = (accounts: StoredAccount[]) => { try { // Persist only non-secret metadata — each account's IMAP/SMTP secrets are @@ -934,7 +949,9 @@ export const saveAccounts = (accounts: StoredAccount[]) => { // of truth that survives a localStorage wipe. Fire-and-forget: the DB does // an UPSERT-only merge (never wipes on an empty/partial snapshot), so this // can only ever ADD durability. Phase 1 keeps localStorage as the fallback. - try { (window as any)?.electronAPI?.accounts?.save?.(safe); } catch { /* ignore */ } + // Never an account being removed (see notMirrored). + const mirror = notMirrored.size ? safe.filter((a) => !notMirrored.has(a.id)) : safe; + try { (window as any)?.electronAPI?.accounts?.save?.(mirror); } catch { /* ignore */ } } catch { /* ignore */ } }; diff --git a/apps/desktop/src/store/slices/connection-slice.ts b/apps/desktop/src/store/slices/connection-slice.ts index a7dfce23..6950b48d 100644 --- a/apps/desktop/src/store/slices/connection-slice.ts +++ b/apps/desktop/src/store/slices/connection-slice.ts @@ -9,7 +9,7 @@ import { isAIAssistEnabled } from '../../services/agent-settings'; import { getDefaultProvider, removeOAuthProvidersForAccount, reportAIUnhealthy, syncAIProviderToMain } from '../../services/ai-service'; import { isOnboardingPending } from '../../services/onboarding-progress'; import { forgetImageTrustAccount, setImageTrustAccount } from '../../utils/remote-images'; -import { connectAccountId, loadSavedCredentials, loadSavedSmtpCredentials, saveCredentials, clearCredentials, saveSmtpCredentials, clearSmtpCredentials, deriveSmtpFromImap, forgetLegacySecretsFor, loadSmtpConfigured, saveSmtpConfigured, migrateAccounts, upsertAccount, removeAccount, saveAccounts, saveActiveAccountId, accountIdFor, normalizeAccount, vaultEntryFor, vaultHasPassword, effectiveSmtpConfig, loadQuotaCache, saveQuotaCache } from '../helpers'; +import { connectAccountId, loadSavedCredentials, loadSavedSmtpCredentials, saveCredentials, clearCredentials, saveSmtpCredentials, clearSmtpCredentials, deriveSmtpFromImap, forgetLegacySecretsFor, loadSmtpConfigured, saveSmtpConfigured, migrateAccounts, upsertAccount, removeAccount, saveAccounts, saveActiveAccountId, setAccountMirrored, accountIdFor, normalizeAccount, vaultEntryFor, vaultHasPassword, effectiveSmtpConfig, loadQuotaCache, saveQuotaCache } from '../helpers'; import type { ConnectionSlice, EmailStore, SecurityRefusalCode, SliceCreator, StoredAccount } from '../types'; // Concurrent connects to the SAME account join one run. @@ -609,13 +609,24 @@ const connectionSlice = ( selectAccount: async (accountId) => { const { accounts, activeAccountId } = get(); - if (accountId === activeAccountId) return; + if (accountId === activeAccountId) return true; const acct = accounts.find((a) => a.id === accountId); - if (!acct) return; + if (!acct) return false; // Point the main process at this account (creates its runtime if needed). + // A REFUSAL (`success: false`) means main is exactly where it was — + // accounts:setActive is transactional: it does not list the account, could + // not read its registry, or could not open or switch to it and put the + // previous account back. So the switch stops here: going on would show, and + // act on, the current account's mailbox under the selected account's name. + // (A call that failed outright still repoints the renderer, as before: main + // may or may not have moved.) try { - await window.electronAPI.accounts.setActive(accountId); + const activation = await window.electronAPI.accounts.setActive(accountId); + if (activation?.success === false) { + connectionLogger.warn(`Account switch refused by main for ${accountLogLabel(accountId)} — staying on the current account`); + return false; + } } catch (e) { console.error('[Store] setActive failed:', e); } @@ -685,7 +696,7 @@ const connectionSlice = ( get().startIdle('INBOX').catch(() => {}); // Light freshness pull — no teardown/reconnect. get().syncSingleFolder('INBOX').catch(() => {}); - return; + return true; } } catch { /* fall through to a real connect */ } @@ -693,6 +704,7 @@ const connectionSlice = ( get().connect(acct.imapConfig).catch((e) => { console.error('[Store] selectAccount background connect failed:', e); }); + return true; }, addAccount: async (imapConfig, opts) => { @@ -742,11 +754,21 @@ const connectionSlice = ( // Ask main to spin up a fresh runtime (its own DB) and point to it BEFORE // connecting, so the new account's data lands in its own database. + // `adding`: this account is not in main's registry until the connect below + // succeeds, and main opens a database for an unlisted id only on this call. + // A REFUSAL means main is still on the previous account; connecting now + // would sync the new account's mail into THAT database. Nothing durable has + // changed yet, so stop here with nothing to roll back. + let activation: { success?: boolean; error?: string } | undefined; try { - await window.electronAPI.accounts.setActive(id); + activation = await window.electronAPI.accounts.setActive(id, { adding: true }); } catch (e) { console.error('[Store] setActive (add) failed:', e); } + if (activation?.success === false) { + connectionLogger.warn(`Adding ${accountLogLabel(id)} refused by main — nothing was changed`); + throw new Error(activation.error || 'Could not prepare the new account. Try again.'); + } saveActiveAccountId(id); saveCredentials(imapConfig); saveSmtpConfigured(false); @@ -772,9 +794,17 @@ const connectionSlice = ( // Put the previous account back — both the durable pointers and the view // state — so a failed add leaves the app exactly as it found it. console.error('[Store] addAccount: connect failed after a passing probe — rolling back'); + // Main must move back too, and say so. If it REFUSES (its registry cannot + // be read, or the previous account cannot be reopened), it is still on + // the half-added account — showing the previous account's name over it + // would send that account's actions into the wrong database. Then no + // account is shown as active: the previous one stays saved as the active + // account (the next launch, or a click in the switcher, reopens it). + let mainRestored = true; if (prev.activeAccountId) { try { - await window.electronAPI.accounts.setActive(prev.activeAccountId); + const restored = await window.electronAPI.accounts.setActive(prev.activeAccountId); + mainRestored = restored?.success !== false; } catch (e) { console.error('[Store] setActive (rollback) failed:', e); } @@ -783,7 +813,12 @@ const connectionSlice = ( if (prev.imapConfig) saveCredentials(prev.imapConfig); else clearCredentials(); saveSmtpConfigured(prev.smtpConfigured); - set(prev); + if (mainRestored) { + set(prev); + } else { + connectionLogger.warn(`Rolling back the add: main refused to return to ${accountLogLabel(prev.activeAccountId)} — no account is active`); + set({ ...prev, activeAccountId: null, connected: false, connectionStatus: 'disconnected', folders: [], emails: [], selectedFolderId: null, selectedEmailId: null, sectionData: {} }); + } throw error; } @@ -932,6 +967,9 @@ const connectionSlice = ( // Clear any stale failure from a previous attempt at this account. accountActionError: get().accountActionError?.id === accountId ? null : get().accountActionError, }); + // Main drops its registry row before the removal returns; a snapshot + // mirrored meanwhile must not write it back (see setAccountMirrored). + setAccountMirrored(accountId, false); const removedAccount = accounts.find((a) => a.id === accountId); try { @@ -1012,14 +1050,19 @@ const connectionSlice = ( // Only now that the durable wipe succeeded do we drop the row and move the // active account away, never onto another account being removed. if (accountId === get().activeAccountId) { - const next = remaining.find((a) => !get().deletingAccountIds.includes(a.id)); set({ accounts: remaining }); - if (next) { - // Force a switch: activeAccountId still points at the removed one, so - // selectAccount won't early-return. (selectAccount restores the next - // account's own saved SMTP creds.) - await get().selectAccount(next.id); - } else { + // Force a switch: activeAccountId still points at the removed one, so + // selectAccount won't early-return. (selectAccount restores the next + // account's own saved SMTP creds.) A switch main REFUSES must not leave + // the deleted account active with its mail on screen: try the next one, + // and with none left that opens, show no account (main is already on + // its pre-account slot — the removal closed this account's runtime). + let switched = false; + for (const next of remaining) { + if (get().deletingAccountIds.includes(next.id)) continue; + if (await get().selectAccount(next.id)) { switched = true; break; } + } + if (!switched) { saveActiveAccountId(null); // The saved IMAP/SMTP creds went with forgetLegacySecretsFor above. saveSmtpConfigured(false); @@ -1053,6 +1096,9 @@ const connectionSlice = ( throw err; } finally { set({ deletingAccountIds: get().deletingAccountIds.filter((id) => id !== accountId) }); + // Removed: it is in no list any more. Kept (a failed removal): its row + // must be mirrored again like any other account's. + setAccountMirrored(accountId, true); } }, }); diff --git a/apps/desktop/src/store/types.ts b/apps/desktop/src/store/types.ts index 9084a3ff..d25f2512 100644 --- a/apps/desktop/src/store/types.ts +++ b/apps/desktop/src/store/types.ts @@ -184,8 +184,10 @@ export interface ConnectionSlice { * outgoing mail queues in the Outbox until SMTP is set up again. */ removeSmtp: () => Promise; /** Switch the active account: point the main process at it, then reconnect + - * reload that account's mailbox. No-op if it's already active. */ - selectAccount: (accountId: string) => Promise; + * reload that account's mailbox. No-op if it's already active. Resolves + * `true` when that account is the active one afterwards, `false` when it is + * unknown or main refused the switch (the previous account stays active). */ + selectAccount: (accountId: string) => Promise; /** Connect a brand-new account (its own DB) and make it active. SMTP setup is * then prompted by the usual overlay. */ /** Verifies the credentials before persisting anything. Pass diff --git a/apps/desktop/test/unit/electron/ipc/accounts-remove-attachments.test.ts b/apps/desktop/test/unit/electron/ipc/accounts-remove-attachments.test.ts index cd72b182..fba9592f 100644 --- a/apps/desktop/test/unit/electron/ipc/accounts-remove-attachments.test.ts +++ b/apps/desktop/test/unit/electron/ipc/accounts-remove-attachments.test.ts @@ -47,6 +47,8 @@ vi.mock('../../../../electron/services/accounts-registry', () => ({ h.calls.push(`registry-remove:${id}`); h.registry = h.registry.filter((a) => a.id !== id); }, + // The removal's tombstone (tested in accounts-remove-signout): not this suite's subject. + markAccountRemoved: () => {}, upsertRegistryAccounts: () => {}, getRegistryActiveAccountId: () => null, setRegistryActiveAccountId: () => {}, diff --git a/apps/desktop/test/unit/electron/ipc/accounts-remove-signout.test.ts b/apps/desktop/test/unit/electron/ipc/accounts-remove-signout.test.ts index b64859d4..231c4273 100644 --- a/apps/desktop/test/unit/electron/ipc/accounts-remove-signout.test.ts +++ b/apps/desktop/test/unit/electron/ipc/accounts-remove-signout.test.ts @@ -11,6 +11,8 @@ const h = vi.hoisted(() => ({ registry: [] as Array<{ id: string; imapConfig: Record | null }>, registryThrows: false, calls: [] as string[], + /** Each tombstone written, and whether the registry row was still there then. */ + tombstones: [] as Array<{ id: string; rowStillThere: boolean }>, signOut: vi.fn(), clearWarning: vi.fn(), session: { @@ -46,6 +48,9 @@ vi.mock('../../../../electron/services/accounts-registry', async () => { h.calls.push(`registry-remove:${id}`); h.registry = h.registry.filter((a) => a.id !== id); }, + markAccountRemoved: (id: string) => { + h.tombstones.push({ id, rowStillThere: h.registry.some((a) => a.id === id) }); + }, upsertRegistryAccounts: () => {}, getRegistryActiveAccountId: () => null, setRegistryActiveAccountId: () => {}, @@ -93,6 +98,7 @@ beforeEach(() => { h.registry = []; h.registryThrows = false; h.calls.length = 0; + h.tombstones.length = 0; h.signOut.mockReset().mockResolvedValue({ revocation: Promise.resolve('revoked') }); h.clearWarning.mockReset(); h.session.clearStorageData.mockReset().mockResolvedValue(undefined); @@ -101,6 +107,29 @@ beforeEach(() => { registerAccountsHandlers(); }); +// The window keeps a removed account in its list until accounts:remove returns +// (it waits for the provider's sign-out answer), and a snapshot it mirrors in +// that time used to write the registry row straight back — the next launch then +// treated the removed account as configured again. +describe('accounts:remove — the removed account cannot come back', () => { + // Breaks: the row is dropped with no tombstone, or the tombstone lands only + // after the row is gone (a snapshot mirrored in between re-adds the row). + it('tombstones the id BEFORE its registry row is dropped', async () => { + h.registry = [oauth('a1', 'gmail', 'me@gmail.com'), oauth('a2', 'microsoft', 'me@outlook.com')]; + await expect(remove('a1')).resolves.toMatchObject({ success: true }); + expect(h.tombstones).toEqual([{ id: 'a1', rowStillThere: true }]); + expect(h.calls).toContain('registry-remove:a1'); + }); + + // Breaks: a removal that failed before anything was deleted still tombstones + // the account — it stays in the switcher but can never be saved again. + it('writes no tombstone when the removal fails before deleting anything', async () => { + h.clearWarning.mockImplementation(() => { throw new Error('warning store unreadable'); }); + await expect(remove('a1')).resolves.toMatchObject({ success: false }); + expect(h.tombstones).toEqual([]); + }); +}); + describe('accounts:remove — OAuth sign-out', () => { // Breaks: removing/re-adding a mailbox inherits an old warning-suppression choice or clears another mailbox's choice. it('clears only the removed account warning preference before deleting its data', async () => { diff --git a/apps/desktop/test/unit/electron/ipc/accounts-set-active.test.ts b/apps/desktop/test/unit/electron/ipc/accounts-set-active.test.ts new file mode 100644 index 00000000..74da651c --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/accounts-set-active.test.ts @@ -0,0 +1,352 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: which mailbox database becomes the active +// one, and whether main and the window agree about it. +// +// `accounts:setActive` opens (and, when missing, CREATES) the named account's +// database and points every active-account handler at it. It used to do that +// for ANY id — a removed account's id that the window still remembered +// re-created a blank mailbox and made it the active one. Now: +// - only a configured account can be activated — except one being ADDED, and +// only with main's own proof that it just signed in (one use, short-lived); +// - it is TRANSACTIONAL: `success: false` means main is exactly where it was. +// The window trusts that and keeps showing the previous account; a failure +// that left main pointing elsewhere sent the previous account's actions into +// another account's database (or into an empty slot: "Storage not +// initialized", and a click on the previous account was then a no-op); +// - an account being added never adopts a legacy install's sarvinbox.db; +// - an add that is abandoned does not leave its database open. + +const h = vi.hoisted(() => ({ + handlers: new Map any>(), + registry: [] as Array<{ id: string }>, + registryThrows: false, + /** Reads that succeed before the registry starts throwing (Infinity: never). */ + registryReadsBeforeFailure: Number.POSITIVE_INFINITY, + registryReads: 0, + current: null as string | null, + persisted: null as string | null, + open: new Set(), + calls: [] as string[], + ensure: vi.fn(), + rebind: vi.fn(), + persist: vi.fn(), + quiesce: vi.fn(), + proof: vi.fn(), + clearRemoved: vi.fn(), + primary: null as string | null, + legacy: false, +})); + +vi.mock('electron', () => ({ + ipcMain: { handle: (name: string, fn: (...a: any[]) => any) => h.handlers.set(name, fn), on: () => {} }, + session: { defaultSession: {} }, +})); +vi.mock('@sarvinbox/core', async (orig) => ({ + ...(await orig()), + createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }), +})); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => { + h.registryReads += 1; + if (h.registryThrows || h.registryReads > h.registryReadsBeforeFailure) throw new Error('addon failed to load'); + return [...h.registry]; + }; + return { + oauthIdentityOf: () => null, + listRegistryAccounts: () => [...h.registry], + readRegistryAccounts, + isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id), + removeRegistryAccount: () => {}, + markAccountRemoved: () => {}, + clearAccountRemoved: h.clearRemoved, + upsertRegistryAccounts: () => {}, + getRegistryActiveAccountId: () => h.persisted, + setRegistryActiveAccountId: h.persist, + getAllAppSettings: () => ({}), + setAppSetting: () => {}, + deleteAppSetting: () => {}, + }; +}); +vi.mock('../../../../electron/services/account-add-proof', () => ({ takeVerifiedAccount: h.proof })); +vi.mock('../../../../electron/services/accounts-runtime', () => ({ + deleteAccountData: async () => {}, + cleanupOrphanedAccountDbs: () => [], + ensureAccountRuntime: h.ensure, + quiesceAccountRuntime: h.quiesce, + loadPrimaryAccountId: () => h.primary, + savePrimaryAccountId: (id: string) => { h.primary = id; h.calls.push(`primary:${id}`); }, + clearPrimaryAccountId: () => { h.primary = null; h.calls.push('primary:cleared'); }, + accountInboxUnread: async () => 0, + rekeyAccount: async () => {}, + legacyDbExists: () => h.legacy, +})); +vi.mock('../../../../electron/services/oauth-refresh-scheduler', () => ({ signOutOAuthAccount: vi.fn() })); +vi.mock('../../../../electron/services/outbox-service', () => ({ rebindOutboxStorage: h.rebind })); +vi.mock('../../../../electron/services/attachment-warning-preferences', () => ({ clearUnscannedWarningPreference: vi.fn() })); +vi.mock('../../../../electron/services/reputation-service', () => ({ noteAppSettingChanged: () => {} })); +vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ disablePipelineAIIfProviderRemoved: async () => {} })); +vi.mock('../../../../electron/shared', () => ({ + setCurrentAccount: (id: string | null) => { h.current = id; h.calls.push(`current:${id}`); }, + hasAccountRuntime: (id: string) => h.open.has(id), + getCurrentAccountId: () => h.current, +})); + +const setActive = (id: unknown, options?: unknown) => h.handlers.get('accounts:setActive')!(null, id, options); + +/** Main as the window last saw it: acct-a active and persisted, acct-a open. */ +const expectStillOnA = () => { + expect(h.current).toBe('acct-a'); + expect(h.persisted).toBe('acct-a'); +}; + +beforeEach(async () => { + // A fresh handler module per test: it remembers an unfinished add between + // calls, and one test's add must not be "abandoned" by the next test. + vi.resetModules(); + h.handlers.clear(); + (await import('../../../../electron/ipc/accounts-handlers')).registerAccountsHandlers(); + h.registry = [{ id: 'acct-a' }, { id: 'acct-b' }]; + h.registryThrows = false; + h.registryReadsBeforeFailure = Number.POSITIVE_INFINITY; + h.registryReads = 0; + h.current = 'acct-a'; + h.persisted = 'acct-a'; + h.open = new Set(['acct-a']); + h.calls.length = 0; + h.primary = null; + h.legacy = false; + h.ensure.mockReset().mockImplementation(async (id: string) => { + h.open.add(id); + h.calls.push(`open:${id}`); + return { storage: {}, syncEngine: null, smtpClient: null }; + }); + h.persist.mockReset().mockImplementation((id: string | null) => { h.persisted = id; h.calls.push(`pointer:${id}`); }); + h.rebind.mockReset().mockImplementation(() => { h.calls.push(`rebind:${h.current}`); }); + h.quiesce.mockReset().mockImplementation(async (id: string) => { h.open.delete(id); h.calls.push(`close:${id}`); }); + h.proof.mockReset().mockReturnValue(false); + h.clearRemoved.mockReset(); +}); + +describe('accounts:setActive — only configured accounts', () => { + // Breaks: switching to another configured account (the account switcher). + // Open FIRST, point second, and read the registry once. + it('opens a configured account, then points at it, persists the pointer and rebinds the outbox', async () => { + await expect(setActive('acct-b')).resolves.toEqual({ success: true }); + expect(h.ensure).toHaveBeenCalledExactlyOnceWith('acct-b', { registryChecked: true }); + expect(h.calls).toEqual(['open:acct-b', 'current:acct-b', 'pointer:acct-b', 'rebind:acct-b']); + expect(h.registryReads).toBe(1); + }); + + // Breaks: THE resurrection bug — a stale id (a removed account the renderer + // still remembers) re-created a blank mailbox and made it the active one. + it('refuses an unconfigured id without moving the pointer, opening anything or persisting it', async () => { + const res = await setActive('acct-gone'); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/not configured/) }); + expect(h.ensure).not.toHaveBeenCalled(); + expect(h.calls).toEqual([]); + expectStillOnA(); + }); + + // Breaks: every click on the already-active account pays a registry read + // (or fails while the registry is unreadable, though nothing would change). + it('answers the already-active, open account without reading the registry', async () => { + h.registryThrows = true; + await expect(setActive('acct-a')).resolves.toEqual({ success: true }); + expect(h.registryReads).toBe(0); + expect(h.calls).toEqual([]); + }); + + // Breaks: a switch to an account that is already open (a background one) + // re-opens it, or skips the pointer and persistence. + it('switches to an already-open account without reopening it', async () => { + h.open.add('acct-b'); + await expect(setActive('acct-b')).resolves.toEqual({ success: true }); + expect(h.ensure).not.toHaveBeenCalled(); + expect(h.calls).toEqual(['current:acct-b', 'pointer:acct-b', 'rebind:acct-b']); + }); + + // Breaks: a missing or non-string id reaches the registry or the runtime. + it.each([[''], [undefined], [42]])('refuses a missing id %j', async (id) => { + await expect(setActive(id)).resolves.toEqual({ success: false, error: 'No accountId provided' }); + expect(h.ensure).not.toHaveBeenCalled(); + }); +}); + +describe('accounts:setActive — transactional: a failure leaves main where it was', () => { + // Breaks (fail securely): an unreadable registry read as "configured" (open + // anything) or as "not configured" with the pointer already moved. + it('refuses when the registry cannot be read', async () => { + h.registryThrows = true; + await expect(setActive('acct-b')).resolves.toEqual({ success: false, error: 'addon failed to load' }); + expect(h.ensure).not.toHaveBeenCalled(); + expect(h.calls).toEqual([]); + expectStillOnA(); + }); + + // Breaks: a runtime that cannot be opened (held for a compaction) answered + // success and left main on an EMPTY active slot — "Storage not initialized" + // for every following call while the window believed the switch worked. + it('treats a runtime that cannot be opened as a failure, before the pointer moves', async () => { + h.ensure.mockResolvedValueOnce(null); + const res = await setActive('acct-b'); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/could not be opened/) }); + expect(h.calls).toEqual([]); + expectStillOnA(); + }); + + // Breaks: an open that THROWS after the pointer had moved returned + // `success: false` with main already on acct-b — the window stayed on acct-a + // and its actions went into acct-b's database. + it('leaves the pointer alone when opening throws', async () => { + h.ensure.mockRejectedValueOnce(new Error('SQLITE_CANTOPEN')); + await expect(setActive('acct-b')).resolves.toEqual({ success: false, error: 'SQLITE_CANTOPEN' }); + expect(h.calls).toEqual([]); + expectStillOnA(); + }); + + // Breaks: a failed persist left main pointing at acct-b while the window, + // told "failed", stayed on acct-a. + it('puts the pointer and the outbox back when persisting the pointer throws', async () => { + h.persist.mockImplementationOnce(() => { throw new Error('core DB is read-only'); }); + await expect(setActive('acct-b')).resolves.toEqual({ success: false, error: 'core DB is read-only' }); + expectStillOnA(); + expect(h.calls).toEqual(['open:acct-b', 'current:acct-b', 'current:acct-a', 'rebind:acct-a', 'pointer:acct-a']); + }); + + // Breaks: a failed outbox rebind left main (and its persisted pointer) on + // acct-b, and the outbox draining the wrong account's queue. + it('puts the pointer, the persisted pointer and the outbox back when the rebind throws', async () => { + h.rebind.mockImplementationOnce(() => { h.calls.push(`rebind:${h.current}`); throw new Error('outbox wiring failed'); }); + await expect(setActive('acct-b')).resolves.toEqual({ success: false, error: 'outbox wiring failed' }); + expectStillOnA(); + expect(h.calls).toEqual(['open:acct-b', 'current:acct-b', 'pointer:acct-b', 'rebind:acct-b', 'current:acct-a', 'rebind:acct-a', 'pointer:acct-a']); + }); + + // Breaks: with no account active before (startup), a failure leaves main on + // the half-activated account instead of the pre-account slot. + it('restores the pre-account slot when no account was active before', async () => { + h.current = null; + h.persisted = null; + h.persist.mockImplementationOnce(() => { throw new Error('core DB is read-only'); }); + await expect(setActive('acct-b')).resolves.toMatchObject({ success: false }); + expect(h.current).toBeNull(); + expect(h.persisted).toBeNull(); + }); + + // Breaks: the legacy adopt of a switch that then failed to open stays + // recorded — sarvinbox.db silently assigned to an account that never opened. + it('undoes a legacy adopt whose runtime never opened', async () => { + h.legacy = true; + h.ensure.mockResolvedValueOnce(null); + await expect(setActive('acct-b')).resolves.toMatchObject({ success: false }); + expect(h.primary).toBeNull(); + expect(h.calls).toEqual(['primary:acct-b', 'primary:cleared']); + }); +}); + +describe('accounts:setActive — adding an account', () => { + // Breaks: adding an account. The add flow points main at the new account + // BEFORE its first connect, and the window writes its registry row only once + // that connect succeeds — so its first activation names an unlisted id. + it('opens an unlisted id that main saw sign in, and lets its registry row back', async () => { + h.proof.mockReturnValueOnce(true); + await expect(setActive('acct-new', { adding: true })).resolves.toEqual({ success: true }); + expect(h.proof).toHaveBeenCalledExactlyOnceWith('acct-new'); + expect(h.ensure).toHaveBeenCalledExactlyOnceWith('acct-new', { registryChecked: true }); + expect(h.calls).toEqual(['open:acct-new', 'current:acct-new', 'pointer:acct-new', 'rebind:acct-new']); + // A removed account being added again: its tombstone goes (see accounts:remove). + expect(h.clearRemoved).toHaveBeenCalledExactlyOnceWith('acct-new'); + }); + + // Breaks (item 4): `{ adding: true }` alone let the window activate any id, + // any number of times — each one a new database and an open engine. + it('refuses an add main has no sign-in proof for', async () => { + const res = await setActive('acct-new', { adding: true }); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/not signed in/) }); + expect(h.ensure).not.toHaveBeenCalled(); + expect(h.calls).toEqual([]); + expect(h.clearRemoved).not.toHaveBeenCalled(); + }); + + // Breaks: anything but a literal `adding: true` (a truthy string, a stray + // object) opens the exception, or spends a proof. + it.each([[{ adding: 'yes' }], [{ adding: 1 }], [{}], [null], ['adding']])('refuses an unlisted id for options %j', async (options) => { + h.proof.mockReturnValue(true); + await expect(setActive('acct-new', options)).resolves.toMatchObject({ success: false }); + expect(h.proof).not.toHaveBeenCalled(); + expect(h.ensure).not.toHaveBeenCalled(); + }); + + // Breaks: re-adding an account that IS configured spends (or needs) a proof. + it('keeps the ordinary path for a configured account even when adding', async () => { + await expect(setActive('acct-b', { adding: true })).resolves.toEqual({ success: true }); + expect(h.proof).not.toHaveBeenCalled(); + expect(h.clearRemoved).not.toHaveBeenCalled(); + }); + + // Breaks: a new account takes over a legacy install's sarvinbox.db (its + // mail) because it happened to be the first account to activate. + it('never adopts the legacy database for an account being added', async () => { + h.legacy = true; + h.proof.mockReturnValueOnce(true); + await setActive('acct-new', { adding: true }); + expect(h.primary).toBeNull(); + expect(h.calls).not.toContain('primary:acct-new'); + // A configured account still adopts it, as before. + await setActive('acct-b'); + expect(h.primary).toBe('acct-b'); + }); + + // Breaks: a failed add left its freshly opened database (and engine) open, + // and main pointing at it. + it('closes the runtime a failed add opened and puts the previous account back', async () => { + h.proof.mockReturnValueOnce(true); + h.persist.mockImplementationOnce(() => { throw new Error('core DB is read-only'); }); + await expect(setActive('acct-new', { adding: true })).resolves.toMatchObject({ success: false }); + expectStillOnA(); + expect(h.quiesce).toHaveBeenCalledExactlyOnceWith('acct-new', 'failed add'); + expect(h.clearRemoved).not.toHaveBeenCalled(); + }); + + // Breaks: an add whose connect failed and was rolled back (the window + // switches back to the previous account) left the new account's database and + // engine open for the rest of the session. + it('closes the runtime of an abandoned add when the window switches away', async () => { + h.proof.mockReturnValueOnce(true); + await setActive('acct-new', { adding: true }); + await expect(setActive('acct-a')).resolves.toEqual({ success: true }); + expect(h.quiesce).toHaveBeenCalledExactlyOnceWith('acct-new', 'abandoned add'); + expect(h.current).toBe('acct-a'); + }); + + // Breaks: a second add (a corrected address) left the first one's runtime open. + it('closes the previous unfinished add when a different add arrives', async () => { + h.proof.mockReturnValue(true); + await setActive('acct-new', { adding: true }); + await setActive('acct-other', { adding: true }); + expect(h.quiesce).toHaveBeenCalledExactlyOnceWith('acct-new', 'abandoned add'); + expect(h.current).toBe('acct-other'); + }); + + // Breaks: a SUCCESSFUL add (its registry row landed) was closed as abandoned + // the first time the user switched to another account. + it('leaves a completed add open', async () => { + h.proof.mockReturnValueOnce(true); + await setActive('acct-new', { adding: true }); + h.registry.push({ id: 'acct-new' }); + await setActive('acct-a'); + expect(h.quiesce).not.toHaveBeenCalled(); + }); + + // Breaks: an unreadable registry after an add made main close it on a guess. + it('never closes an add it cannot check', async () => { + h.proof.mockReturnValueOnce(true); + await setActive('acct-new', { adding: true }); + h.open.add('acct-b'); + // The switch's own registry read succeeds; the abandoned-add check's fails. + h.registryReadsBeforeFailure = h.registryReads + 1; + await expect(setActive('acct-b')).resolves.toEqual({ success: true }); + expect(h.quiesce).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/agent-draft-reply-context.test.ts b/apps/desktop/test/unit/electron/ipc/agent-draft-reply-context.test.ts index 8db2beee..437ce8b2 100644 --- a/apps/desktop/test/unit/electron/ipc/agent-draft-reply-context.test.ts +++ b/apps/desktop/test/unit/electron/ipc/agent-draft-reply-context.test.ts @@ -47,10 +47,15 @@ vi.mock('../../../../electron/services/accounts-runtime', () => ({ return { storage, syncEngine: null }; }), })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ - resolveAccountIdentity: () => ({ email: 'me@me.test', name: 'Me', aliases: ['me@me.test'] }), - readRegistryAccounts: () => [{ id: 'acct-a' }, { id: 'acct-b' }], -})); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => [{ id: 'acct-a' }, { id: 'acct-b' }]; + return { + resolveAccountIdentity: () => ({ email: 'me@me.test', name: 'Me', aliases: ['me@me.test'] }), + readRegistryAccounts, + // The shared membership check, read through this mock's registry. + isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id), + }; +}); vi.mock('../../../../electron/services/agent-config-store', () => ({ saveAgentConfig: vi.fn(), loadAgentConfig: vi.fn() })); vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ getIntelligence: vi.fn(() => null), diff --git a/apps/desktop/test/unit/electron/ipc/agent-resolve-decision.test.ts b/apps/desktop/test/unit/electron/ipc/agent-resolve-decision.test.ts new file mode 100644 index 00000000..deb20e64 --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/agent-resolve-decision.test.ts @@ -0,0 +1,138 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: the agent's learning data. Resolving a +// decision writes a status and an "actual action" the learning code reads back +// as its enums. Both handlers used to cast whatever the renderer sent (`as +// any`) straight into the row — an unknown status is a decision no accuracy +// query counts, an unknown action a correction nothing understands. Now only +// the enums' own values are written; anything else is refused and the row is +// left as it was. Real account database, real repository. + +const h = vi.hoisted(() => ({ + handlers: new Map Promise>(), + storage: null as unknown, +})); +vi.mock('electron', () => ({ ipcMain: { handle: (name: string, fn: (...args: unknown[]) => Promise) => h.handlers.set(name, fn) } })); +vi.mock('../../../../electron/shared', () => ({ requireStorage: () => h.storage, getSyncEngine: () => null })); +vi.mock('../../../../electron/services/account-target', () => ({ + openAccountStorages: () => [], requireNamedOrActiveStorage: vi.fn(), requireTargetAccountId: vi.fn(), +})); +vi.mock('../../../../electron/services/accounts-registry', () => ({ resolveAccountIdentity: vi.fn() })); +vi.mock('../../../../electron/services/agent-config-store', () => ({ saveAgentConfig: vi.fn(), loadAgentConfig: vi.fn() })); +vi.mock('../../../../electron/services/contact-classification-service', () => ({ refreshContactClassifications: vi.fn() })); +vi.mock('../../../../electron/services/thread-context', () => ({ buildThreadMessages: vi.fn() })); +vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ + getIntelligence: vi.fn(), getUnifiedPipeline: vi.fn(), setPipelineUserProfile: vi.fn(), getPipelineAIConfig: vi.fn(), +})); + +import { registerAgentHandlers } from '../../../../electron/ipc/agent-handlers'; +import { decisionActualAction, resolvedDecisionStatus } from '../../../../electron/services/agent-decision-values'; +import { openTestAccount, type TestAccount } from '../../../helpers/account-storage'; + +registerAgentHandlers(); + +const call = async (channel: string, ...args: unknown[]) => + (await h.handlers.get(channel)!({} as never, ...args)) as { success: boolean; error?: string }; + +let dir = ''; +let account: TestAccount; + +const row = () => (account.storage as unknown as { db: { prepare: (sql: string) => { get: (...p: unknown[]) => unknown } } }).db + .prepare('SELECT status, actual_action AS actualAction, user_feedback AS feedback, resolved_at AS resolvedAt FROM agent_decisions WHERE id = ?') + .get('d1') as { status: string; actualAction: string | null; feedback: string | null; resolvedAt: number | null }; + +beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), 'agent-resolve-decision-')); + account = await openTestAccount(dir, 'a'); + await account.add('t1', { id: 'e1' }); + await (account.storage.getRepositories() as any).agent.saveDecision({ + id: 'd1', emailId: 'e1', threadId: 't1', senderAddress: 's@x.test', proposedAction: 'reply', proposedValue: null, + confidence: 0.9, reasoning: 'r', status: 'pending', actualAction: null, userFeedback: null, proposedAt: 1, resolvedAt: null, createdAt: 1, + }); + h.storage = account.storage; +}); + +afterEach(async () => { + await account.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe('the allow-lists (agent-decision-values)', () => { + // Breaks: a resolution writes a status the learning queries never count. + it('accepts exactly the resolved statuses', () => { + for (const status of ['approved', 'rejected', 'auto', 'expired', 'overridden']) expect(resolvedDecisionStatus(status)).toBe(status); + // `pending` is the UNresolved state: writing it would stamp resolved_at on a row that reads as waiting. + for (const bad of ['pending', 'APPROVED', 'dismissed', '', 'constructor', '__proto__', 'toString', null, undefined, 1, {}]) { + expect(resolvedDecisionStatus(bad)).toBeNull(); + } + }); + + // Breaks: the Dismiss button (composer, agent dashboard) stops recording — + // `dismissed` is not a mail action, but it is what they and the pipeline write. + it('accepts every user action plus dismissed, and "none given"', () => { + for (const action of ['read', 'archive', 'reply', 'reply_all', 'label_add', 'ignore', 'dismissed']) { + expect(decisionActualAction(action)).toEqual({ ok: true, action }); + } + expect(decisionActualAction(undefined)).toEqual({ ok: true, action: null }); + expect(decisionActualAction(null)).toEqual({ ok: true, action: null }); + }); + + // Breaks: an inherited key or any other string becomes the recorded action. + it('refuses anything else, inherited keys included', () => { + for (const bad of ['delete_all', 'Reply', '', 'constructor', '__proto__', 'hasOwnProperty', 7, {}, ['reply']]) { + expect(decisionActualAction(bad)).toEqual({ ok: false }); + } + }); +}); + +describe('agent:resolveDecision', () => { + // Breaks: resolving a decision with real values stops working. + it('writes a known status and action', async () => { + expect(await call('agent:resolveDecision', 'd1', 'overridden', 'archive', 'did this instead')).toEqual({ success: true }); + expect(row()).toMatchObject({ status: 'overridden', actualAction: 'archive', feedback: 'did this instead' }); + expect(row().resolvedAt).toBeGreaterThan(0); + }); + + // Breaks (F6): an arbitrary renderer string became the row's status. + it.each(['hacked', 'pending', '', 'constructor', null, 42])('refuses status %j and leaves the row untouched', async (status) => { + expect(await call('agent:resolveDecision', 'd1', status, 'archive')).toEqual({ success: false, error: 'Unknown decision status' }); + expect(row()).toMatchObject({ status: 'pending', actualAction: null, resolvedAt: null }); + }); + + // Breaks (F6): an arbitrary renderer string became the recorded action. + it('refuses an unknown action and leaves the row untouched', async () => { + expect(await call('agent:resolveDecision', 'd1', 'rejected', 'format_disk')).toEqual({ success: false, error: 'Unknown action' }); + expect(row()).toMatchObject({ status: 'pending', actualAction: null, resolvedAt: null }); + }); +}); + +describe('agent:resolveProposal', () => { + // Breaks: approving a proposal from the composer stops recording the reply. + it('records an approval with its action', async () => { + expect(await call('agent:resolveProposal', 'd1', true, 'reply')).toEqual({ success: true }); + expect(row()).toMatchObject({ status: 'approved', actualAction: 'reply' }); + }); + + // Breaks: the Dismiss buttons (InlineReply, AgentDashboard) send + // `dismissed`, which is not a mail action — refusing it would break them. + it('records a dismissal', async () => { + expect(await call('agent:resolveProposal', 'd1', false, 'dismissed')).toEqual({ success: true }); + expect(row()).toMatchObject({ status: 'rejected', actualAction: 'dismissed' }); + }); + + // Breaks: a resolution with no action given wipes or refuses. + it('keeps the stored action when none is given', async () => { + expect(await call('agent:resolveProposal', 'd1', false)).toEqual({ success: true }); + expect(row()).toMatchObject({ status: 'rejected', actualAction: null }); + }); + + // Breaks (F6): an arbitrary renderer string became the recorded action. + it.each(['nuke', '__proto__', 5])('refuses action %j and leaves the row untouched', async (action) => { + expect(await call('agent:resolveProposal', 'd1', true, action)).toEqual({ success: false, error: 'Unknown action' }); + expect(row()).toMatchObject({ status: 'pending', actualAction: null, resolvedAt: null }); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/ai-handlers-first-split.test.ts b/apps/desktop/test/unit/electron/ipc/ai-handlers-first-split.test.ts index e32b0a1e..04340942 100644 --- a/apps/desktop/test/unit/electron/ipc/ai-handlers-first-split.test.ts +++ b/apps/desktop/test/unit/electron/ipc/ai-handlers-first-split.test.ts @@ -58,12 +58,14 @@ vi.mock('../../../../electron/services/accounts-runtime', () => ({ return { storage, syncEngine: null }; }), })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ - readRegistryAccounts: () => { +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => { if (h.registryError) throw h.registryError; return h.registry.map((id) => ({ id, email: `${id}@x.test` })); - }, -})); + }; + // The shared membership check, read through this mock's (throwing) registry. + return { readRegistryAccounts, isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id) }; +}); vi.mock('../../../../electron/services/ai-backlog-cap', () => ({ getAutoBacklogCap: vi.fn(), setAutoBacklogCap: vi.fn() })); vi.mock('../../../../electron/services/ai-secret-store', () => ({ listAiSecretIds: vi.fn(async () => ['p1']), setAiSecret: vi.fn(), deleteAiSecret: vi.fn(), isSecureStorageAvailable: vi.fn(() => true), @@ -440,3 +442,71 @@ describe('AI key IPC surface', () => { expect(h.handlers.has('ai:providerFetchAbort')).toBe(true); }); }); + +// The thread-summary cache shares the first-split cache's hazard: it is keyed +// by thread id, which BOTH accounts hold. It used to take no account at all and +// always use the active account's database. +describe('ai:getThreadSummary / ai:saveThreadSummary — routed by the owning account (F7)', () => { + const summaryOf = (text: string) => ({ + threadId: THREAD, summary: text, keyPoints: JSON.stringify(['k']), participants: JSON.stringify(['p']), + lastEmailDate: T0, emailCount: 2, processedAt: T0, modelUsed: 'm', + }); + const getSummary = (accountId?: string) => call<{ summary: string } | null>('ai:getThreadSummary', THREAD, accountId); + const saveSummary = (text: string, accountId?: string) => call('ai:saveThreadSummary', summaryOf(text), accountId); + + // Breaks: a summary made for account B's thread in All Inboxes was cached in + // the ACTIVE account's database under the thread id both share — and then + // shown on account A's own copy of the conversation. + it("caches a non-active account's summary in that account only", async () => { + expect(await saveSummary('summary for B', 'acct-b')).toEqual({ success: true }); + expect((await getSummary('acct-b')).data).toMatchObject({ summary: 'summary for B' }); + expect((await getSummary('acct-a')).data).toBeNull(); + expect(await a.getThreadSummary(THREAD)).toBeNull(); + }); + + // Breaks: two accounts' summaries of the same thread id overwrite each other. + it("keeps each account's summary of the same thread id apart", async () => { + await saveSummary('A says', 'acct-a'); + await saveSummary('B says', 'acct-b'); + expect((await getSummary('acct-a')).data).toMatchObject({ summary: 'A says' }); + expect((await getSummary('acct-b')).data).toMatchObject({ summary: 'B says' }); + }); + + // Breaks: the single-account path (no account named) stops reaching the + // active account's cache. + it('uses the active account when no account is named', async () => { + await saveSummary('active summary'); + expect((await a.getThreadSummary(THREAD))?.summary).toBe('active summary'); + expect((await getSummary()).data).toMatchObject({ summary: 'active summary' }); + expect(await b.getThreadSummary(THREAD)).toBeNull(); + }); + + // Breaks (fail securely): a removed account's late request wrote its summary + // into the active account, or created a blank database for the dead id. + it('refuses a removed account without touching the active account or creating a database', async () => { + h.registry = ['acct-a']; + h.byId.delete('acct-b'); + expect(await saveSummary('late', 'acct-b')).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(await getSummary('acct-b')).toMatchObject({ success: false }); + expect(await a.getThreadSummary(THREAD)).toBeNull(); + expect(h.created).toEqual([]); + }); + + // Breaks: a configured account that cannot be opened right now (held for a + // compaction) falls back to the active account's cache instead of failing. + it('refuses a configured account that cannot be opened, leaving the active cache alone', async () => { + h.byId.delete('acct-b'); + vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); + expect(await saveSummary('held', 'acct-b')).toMatchObject({ success: false }); + expect(await a.getThreadSummary(THREAD)).toBeNull(); + }); + + // Breaks: an unreadable registry read as "not configured" or "configured". + it('surfaces an unreadable registry as an error, writing nothing', async () => { + h.byId.delete('acct-b'); + h.registryError = new Error('core DB unreadable'); + expect(await saveSummary('x', 'acct-b')).toMatchObject({ success: false, error: 'core DB unreadable' }); + expect(await a.getThreadSummary(THREAD)).toBeNull(); + expect(h.created).toEqual([]); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/attachment-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/attachment-handlers.test.ts index 1b139694..06f5bb19 100644 --- a/apps/desktop/test/unit/electron/ipc/attachment-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/attachment-handlers.test.ts @@ -90,9 +90,11 @@ vi.mock('../../../../electron/services/body-prefetch-scheduler', () => ({ deferBodyPrefetch: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ - readRegistryAccounts: () => [{ id: 'acct-1' }, { id: 'acct-2' }], -})); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => [{ id: 'acct-1' }, { id: 'acct-2' }]; + // The shared membership check, read through this mock's registry. + return { readRegistryAccounts, isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id) }; +}); vi.mock('../../../../electron/services/antivirus-scan-service', () => ({ getAntivirusScanService: () => ({ getAttachmentSetupRequirement: async (extensionId: string, accountId: string) => { diff --git a/apps/desktop/test/unit/electron/ipc/draft-attachments.test.ts b/apps/desktop/test/unit/electron/ipc/draft-attachments.test.ts index 197e203e..47f4df41 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-attachments.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-attachments.test.ts @@ -28,7 +28,7 @@ vi.mock('../../../../electron/shared', () => ({ sendToWindow: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); // The attachment cache seals with a key derived from the DB key (CASA M-7); // the real store would reach for the OS keychain. vi.mock('../../../../electron/services/db-key-store', () => ({ getDbEncryptionKey: vi.fn(() => 'k'.repeat(64)) })); @@ -41,7 +41,7 @@ import { draftMimeAttachments, } from '../../../../electron/ipc/draft-attachments'; import { registerDraftHandlers, saveDraftToIMAP, writeLocalDraftRow } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; import { accountAttachmentDir, getOrCacheAttachment, @@ -150,7 +150,7 @@ describe('saveDraftToIMAP with attachments', () => { // device, and gone here once the sync replaces the local row. it('puts the files in the appended MIME message', async () => { const appendMessage = vi.fn(async () => 11); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(draftsDb()), syncEngine: { isConnected: () => true, getClient: () => ({ appendMessage }) }, } as any); @@ -166,7 +166,7 @@ describe('saveDraftToIMAP with attachments', () => { // names to load — the draft reopens without its files. it('records the files on the local draft row', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -184,7 +184,7 @@ describe('saveDraftToIMAP with attachments', () => { // instead of as a plaintext file under the row id; and it must be sealed at rest. it('seeds the files into the cache under the local row id', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, accountId: 'acct-1', } as any); @@ -203,7 +203,7 @@ describe('saveDraftToIMAP with attachments', () => { // account leaves them behind. it("seeds a non-active account's draft into that account's store only", async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, accountId: 'acct-2', } as any); @@ -211,7 +211,7 @@ describe('saveDraftToIMAP with attachments', () => { accountId: 'acct-2', to: 'a@x.com', htmlBody: '

x

', accountEmail: 'me2@x.com', attachments: [invoice], }); - expect(resolveAccountTarget).toHaveBeenCalledWith('acct-2'); + expect(resolveNamedOrActiveAccountTarget).toHaveBeenCalledWith('acct-2'); const { id } = attachmentColumnsOf(db, res.messageId!); expect((await reopenedFile('acct-2', id, 'invoice.pdf')).content.equals(PDF)).toBe(true); await expect(reopenedFile('acct-1', id, 'invoice.pdf')).rejects.toMatchObject({ status: 404 }); @@ -222,7 +222,7 @@ describe('saveDraftToIMAP with attachments', () => { // save, losing the draft text along with the files it could not cache. it('still saves the draft when its files cannot be cached', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, accountId: 'acct-1', } as any); vi.mocked(getDbEncryptionKey).mockImplementationOnce(() => { @@ -243,7 +243,7 @@ describe('saveDraftToIMAP with attachments', () => { // now, so "no folder" is checked at the owning account's folder. it('writes nothing to the cache for a draft without files', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, accountId: 'acct-1', } as any); @@ -279,7 +279,7 @@ describe('drafts:find-for-thread', () => { // reopens without the attachments it was saved with. it('returns the draft\'s attachment names and sizes', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: null } as any); + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: null } as any); await writeLocalDraftRow(storageOver(db) as any, { messageId: '', folderPath: DRAFTS, to: 'a@x.com', cc: '', bcc: '', subject: 'Re: s', bodyText: 'x', bodyHtml: '

x

', inReplyTo: '', fromAddress: 'me@x.com', rawMessage: '', diff --git a/apps/desktop/test/unit/electron/ipc/draft-badge-refresh.test.ts b/apps/desktop/test/unit/electron/ipc/draft-badge-refresh.test.ts index 09d177b9..cef96ae6 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-badge-refresh.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-badge-refresh.test.ts @@ -44,10 +44,10 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { registerDraftHandlers, deleteDraftsForThread } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; /** A storage whose raw handle answers the draft queries, and which records the * read-model catch-up the badge depends on. */ @@ -88,7 +88,7 @@ describe('discarding a draft refreshes the folder badge', () => { // 5-second safety pump gets to it. it('asks for the read-model catch-up after the local delete', async () => { const storage = makeStorage([{ message_id: '', uid: 7 }]); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: onlineEngine({ selectFolder: async () => {}, deleteAndExpunge: vi.fn(async () => {}) }), } as never); @@ -103,7 +103,7 @@ describe('discarding a draft refreshes the folder badge', () => { // when the IMAP half fails — offline, or on a connection that just died. it('asks for it even when the server copy cannot be removed', async () => { const storage = makeStorage([{ message_id: '', uid: 7 }]); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: { isConnected: () => true, @@ -123,7 +123,7 @@ describe('discarding a draft refreshes the folder badge', () => { // same raw delete, same stale badge, with nobody around to blame it on. it('asks for it when the send path clears a thread\'s drafts', async () => { const storage = makeStorage([{ message_id: '', uid: 7 }]); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: onlineEngine({ selectFolder: async () => {}, deleteAndExpunge: vi.fn(async () => {}) }), } as never); @@ -138,7 +138,7 @@ describe('discarding a draft refreshes the folder badge', () => { it('still completes the discard when the storage cannot drain', async () => { const storage = makeStorage([{ message_id: '', uid: 7 }]) as Partial>; delete storage.scheduleReadModelDrain; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: onlineEngine({ selectFolder: async () => {}, deleteAndExpunge: vi.fn(async () => {}) }), } as never); diff --git a/apps/desktop/test/unit/electron/ipc/draft-calendar-metadata.test.ts b/apps/desktop/test/unit/electron/ipc/draft-calendar-metadata.test.ts index 4a9d5bf7..0f2c995d 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-calendar-metadata.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-calendar-metadata.test.ts @@ -18,8 +18,14 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/account-target', () => ({ requireTargetAccountId: (id = 'account-a') => { if (!h.accounts.has(id)) throw new Error('Account unavailable'); return id; }, requireAccountStorage: async (id: string) => { if (!h.accounts.has(id)) throw new Error('Account unavailable'); return h.accounts.get(id); }, - resolveNamedOrActiveAccountTarget: async (id: string) => { if (!h.accounts.has(id)) throw new Error('Account unavailable'); return { storage: h.accounts.get(id), syncEngine: { isConnected: () => h.connected, getClient: () => ({ appendMessage: h.append }) } }; }, - resolveAccountTarget: async (id = 'account-a') => ({ storage: h.accounts.get(id), accountId: id, syncEngine: { isConnected: () => h.connected, getClient: () => ({ appendMessage: h.append }) } }), + // Changed deliberately: the lenient resolver is gone, so this models the one + // strict resolver — no id is the active account ('account-a'), and an + // unknown named account throws instead of falling back. + resolveNamedOrActiveAccountTarget: async (id?: string) => { + const owner = id || 'account-a'; + if (!h.accounts.has(owner)) throw new Error('Account unavailable'); + return { storage: h.accounts.get(owner), accountId: owner, syncEngine: { isConnected: () => h.connected, getClient: () => ({ appendMessage: h.append }) } }; + }, })); vi.mock('../../../../electron/services/attachment-cache', () => ({ seedAttachmentCache: vi.fn() })); vi.mock('../../../../electron/services/read-model-poke', () => ({ pokeReadModel: vi.fn() })); diff --git a/apps/desktop/test/unit/electron/ipc/draft-caller-message-id.test.ts b/apps/desktop/test/unit/electron/ipc/draft-caller-message-id.test.ts index 13b6fc06..289ef188 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-caller-message-id.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-caller-message-id.test.ts @@ -45,12 +45,12 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); // eslint-disable-next-line import/order -- see local-mirror-content-hash.test.ts import { newMigratedDb } from '../../../../../../packages/storage-node/src/test-support/test-db'; import { newDraftMessageId, registerDraftHandlers, saveDraftToIMAP } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; const DRAFTS = 'Drafts'; @@ -92,7 +92,7 @@ describe("saveDraftToIMAP — the caller's own Message-ID", () => { // the draft row carries — its own draft then reads as the user's. it('stamps the id a main-process caller passes in options, on the row and in the result', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -109,7 +109,7 @@ describe("saveDraftToIMAP — the caller's own Message-ID", () => { // Breaks: without a caller id every save still gets a fresh one. it('mints one when the caller passes none', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -124,7 +124,7 @@ describe("saveDraftToIMAP — the caller's own Message-ID", () => { // — naming an existing message's id would have the mirror write replace it. it('ignores a messageId smuggled into the drafts:save IPC payload', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); diff --git a/apps/desktop/test/unit/electron/ipc/draft-change-events.test.ts b/apps/desktop/test/unit/electron/ipc/draft-change-events.test.ts index 6ae43066..c892475e 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-change-events.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-change-events.test.ts @@ -43,12 +43,12 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); // eslint-disable-next-line import/order -- see local-mirror-content-hash.test.ts import { newMigratedDb } from '../../../../../../packages/storage-node/src/test-support/test-db'; import { registerDraftHandlers, saveDraftToIMAP } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; import { sendToWindow } from '../../../../electron/shared'; const DRAFTS = 'Drafts'; @@ -77,7 +77,7 @@ describe('saveDraftToIMAP — drafts:saved', () => { // Breaks: THE regression — the list only learned of a new draft on the next sync. it('announces the draft as soon as the local row is written', async () => { const db = draftsDb(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -91,7 +91,7 @@ describe('saveDraftToIMAP — drafts:saved', () => { // Breaks: an event for a row that was never written makes the list reload // into a state that still lacks the draft — or, worse, signals success. it('does not announce when the local write fails', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver({ prepare: () => { throw new Error('disk I/O error'); } }), syncEngine: { isConnected: () => false }, } as any); @@ -123,7 +123,7 @@ describe('drafts:delete — drafts:removed', () => { // Breaks: the autosave's replace-in-place deletes the superseded draft by // message-id; without this event it stays on screen as a duplicate. it('tells the renderer which draft rows it removed', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: { isConnected: () => false, deleteEmail: vi.fn(async () => ({ success: true })) }, } as any); @@ -136,7 +136,7 @@ describe('drafts:delete — drafts:removed', () => { // Breaks: a delete that matched nothing still fires, making every open view // reload for no change. it('stays quiet when nothing matched', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: { ...storage, db: { prepare: () => ({ all: () => [], get: () => undefined, run: () => ({ changes: 0 }) }) } }, syncEngine: { isConnected: () => false }, } as any); diff --git a/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts b/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts index 78f71741..7017144a 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-encryption.test.ts @@ -28,7 +28,7 @@ vi.mock('../../../../electron/shared', () => ({ sendToWindow: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); vi.mock('../../../../electron/services/attachment-cache', () => ({ seedAttachmentCache: vi.fn() })); vi.mock('../../../../electron/services/pgp-service', () => ({ getPgpKeyring: () => h.keyring })); @@ -37,7 +37,7 @@ import { captureLogs } from '../../../../../../packages/core/src/test-support/lo import { newMigratedDb } from '../../../../../../packages/storage-node/src/test-support/test-db'; import { registerDraftHandlers, saveDraftToIMAP, writeLocalDraftRow } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; import { seedAttachmentCache } from '../../../../electron/services/attachment-cache'; import { encryptDraftMime } from '../../../../electron/services/pgp-outgoing'; @@ -67,7 +67,7 @@ const storageOver = (db: unknown) => ({ }); const target = (db: unknown, appendMessage = vi.fn(async () => 7), connected = true) => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => connected, getClient: () => ({ appendMessage }) }, } as any); @@ -252,7 +252,7 @@ describe('drafts:find-for-thread', () => { bodyText: 'Encrypted message', bodyHtml: '', inReplyTo: '', fromAddress: ME, rawMessage: 'CIPHERTEXT', pgpStatus: 'encrypted', }); - vi.mocked(resolveAccountTarget).mockResolvedValue({ storage: storageOver(db) } as any); + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db) } as any); registerDraftHandlers(); const result = await h.handlers.get('drafts:find-for-thread')!(null, ['']); expect(result.data).toMatchObject({ messageId: '', pgpStatus: 'encrypted' }); diff --git a/apps/desktop/test/unit/electron/ipc/draft-handlers-logging.test.ts b/apps/desktop/test/unit/electron/ipc/draft-handlers-logging.test.ts index 693b8914..fc90560b 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-handlers-logging.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-handlers-logging.test.ts @@ -47,11 +47,11 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { captureLogs, type CapturedLogs } from '../../../../../../packages/core/src/test-support/log-capture'; import { deleteDraftsForThread, registerDraftHandlers, rendererDraftDebugFields } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; /** Text the user typed, an OS user name and an account id: none may reach a log line. */ const SUBJECT = 'SENTINEL-subject Payslip for Jane'; @@ -111,7 +111,7 @@ describe('drafts:delete — what reaches the log', () => { it('logs the subject-only cleanup as booleans and counts, and still deletes', async () => { const search = vi.fn(async () => [5]); const deleteAndExpunge = vi.fn(async () => {}); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db')), syncEngine: { isConnected: () => true, deleteEmail: vi.fn(), getClient: () => ({ selectFolder: async () => {}, search, deleteAndExpunge }) }, accountId: ACCOUNT, @@ -134,7 +134,7 @@ describe('drafts:delete — what reaches the log', () => { // Breaks (IMAP error): the subject search fails and the error line logs the // ImapFlow error whole, whose executedCommand names the subject. it('logs a failed subject search by error class and code, and queues nothing it cannot', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db')), syncEngine: { isConnected: () => true, @@ -157,7 +157,7 @@ describe('drafts:delete — what reaches the log', () => { // the UIDs or the options while it hands the removal to the durable queue. it('logs an offline delete as counts while it queues the server removal', async () => { const deleteEmail = vi.fn(async () => ({ success: true })); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db'), [{ message_id: '', uid: 41 }]), syncEngine: { isConnected: () => false, deleteEmail }, accountId: ACCOUNT, @@ -174,7 +174,7 @@ describe('drafts:delete — what reaches the log', () => { // Breaks (multi-account): a delete for a draft of ANOTHER account writes // either account's id; what it may say is whether it named the active one. it('says whether the named account is the active one, without naming either', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-9f9f.db'), [{ message_id: '', uid: 0 }]), syncEngine: { isConnected: () => false, deleteEmail: vi.fn() }, accountId: OTHER_ACCOUNT, @@ -190,7 +190,7 @@ describe('drafts:delete — what reaches the log', () => { // Breaks (idempotent re-run): the second discard of the same draft (nothing // left to delete) logs something the first did not — e.g. the options. it('logs nothing new and nothing secret when the same delete runs twice', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db')), syncEngine: { isConnected: () => false, deleteEmail: vi.fn() }, accountId: ACCOUNT, @@ -210,7 +210,7 @@ describe('drafts:delete — what reaches the log', () => { it('writes no draft diagnostic line at the release log level', async () => { logs.stop(); logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }, { level: 'info' }); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db'), [{ message_id: '', uid: 41 }]), syncEngine: { isConnected: () => false, deleteEmail: vi.fn(async () => ({ success: true })) }, accountId: ACCOUNT, @@ -235,7 +235,7 @@ describe('drafts:save — what reaches the log', () => { if (sql.startsWith('UPDATE emails SET uid')) throw Object.assign(new Error('database is locked'), { code: 'SQLITE_BUSY' }); return prepare(sql); }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage, syncEngine: { isConnected: () => true, getClient: () => ({ appendMessage }) }, accountId: ACCOUNT, @@ -265,14 +265,14 @@ describe('draft error paths — what reaches the log', () => { // diagnostics log an error's message (exact lines: class and code only), or // the request's subject and recipient on the way. it('logs every failed step by error class and code, and still answers', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: failingStorage(), syncEngine: { isConnected: () => false, deleteEmail: vi.fn() }, accountId: ACCOUNT, } as any); const failedCollect = await call('drafts:delete', { threadId: 't-1', subject: SUBJECT, to: TO }); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db'), [{ message_id: '', uid: 41 }]), syncEngine: { isConnected: () => false, deleteEmail: vi.fn(async () => { throw new Error('pending_operations write failed'); }) }, accountId: ACCOUNT, @@ -289,13 +289,13 @@ describe('draft error paths — what reaches the log', () => { // Breaks: the send-time cleanup of a thread's drafts logs the thread id, or // its failure logs the error's message. it('logs the send-time cleanup as a count, and its failure by class', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValueOnce({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValueOnce({ storage: makeStorage(dbPath('sarvinbox-1a2b.db'), [{ message_id: '', uid: 41 }]), syncEngine: null, accountId: ACCOUNT, } as any); await deleteDraftsForThread(ACCOUNT, 'SENTINEL-thread'); - vi.mocked(resolveAccountTarget).mockResolvedValueOnce({ storage: failingStorage(), syncEngine: null, accountId: ACCOUNT } as any); + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValueOnce({ storage: failingStorage(), syncEngine: null, accountId: ACCOUNT } as any); await deleteDraftsForThread(ACCOUNT, 'SENTINEL-thread'); expectNoSecrets(logs); @@ -308,7 +308,7 @@ describe('drafts:cleanup — what reaches the log', () => { // Breaks (multi-account): the per-account sweep line names each account id // and its database's full path; the result handed back keeps the id. it('logs each account by its database file name only', async () => { - vi.mocked(resolveAccountTarget).mockImplementation(async (accountId?: string) => ({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockImplementation(async (accountId?: string | null) => ({ storage: makeStorage(dbPath(accountId === ACCOUNT ? 'sarvinbox-aaaa.db' : 'sarvinbox-bbbb.db'), [{ message_id: '', uid: 0 }]), syncEngine: null, accountId, @@ -329,7 +329,7 @@ describe('drafts:cleanup — what reaches the log', () => { const search = vi.fn(async () => { throw Object.assign(new Error(`Command timed out for ${ACCOUNT}`), { code: 'ETIMEDOUT' }); }); const deleteAndExpunge = vi.fn(async () => {}); const conn = { selectFolder: vi.fn(async () => {}), search, deleteAndExpunge }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(dbPath('sarvinbox-1a2b.db')), syncEngine: { isConnected: () => true, connectionPool: { withConnection: (fn: (c: unknown) => unknown) => fn(conn) } }, accountId: ACCOUNT, @@ -351,7 +351,7 @@ describe('drafts:cleanup — what reaches the log', () => { const unnamed = makeStorage(''); const throwing = makeStorage(dbPath('sarvinbox-1a2b.db')); Object.defineProperty(throwing.db, 'name', { get: () => { throw new Error(`closed: ${dbPath('sarvinbox-1a2b.db')}`); } }); - vi.mocked(resolveAccountTarget).mockImplementation(async (accountId?: string) => ({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockImplementation(async (accountId?: string | null) => ({ storage: accountId === ACCOUNT ? unnamed : throwing, syncEngine: null, accountId, @@ -367,7 +367,7 @@ describe('drafts:cleanup — what reaches the log', () => { // Breaks: a failed sweep logs the error's message (or the account id). it('logs a failed sweep by error class', async () => { - vi.mocked(resolveAccountTarget).mockRejectedValue(Object.assign(new Error(`no storage for ${ACCOUNT}`), { code: 'ENOENT' })); + vi.mocked(resolveNamedOrActiveAccountTarget).mockRejectedValue(Object.assign(new Error(`no storage for ${ACCOUNT}`), { code: 'ENOENT' })); const res = await call('drafts:cleanup', { accountId: ACCOUNT }); diff --git a/apps/desktop/test/unit/electron/ipc/draft-msgid-window.test.ts b/apps/desktop/test/unit/electron/ipc/draft-msgid-window.test.ts index 0db6ede7..24344db6 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-msgid-window.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-msgid-window.test.ts @@ -47,10 +47,10 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { registerDraftHandlers, resolveDraftServerUids } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; /** * A connection whose Message-ID scan answers from `windowed` when a window was @@ -225,7 +225,7 @@ describe('drafts:delete — the scan it puts on the wire', () => { // the connection recycle that kills the EXPUNGE — is exactly as it was. it('bounds the scan it runs for the delete', async () => { const conn = { selectFolder: async () => {}, deleteAndExpunge: vi.fn(async () => {}), ...scannerOver([['d1@x', 88]]) }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, deleteEmail: vi.fn(), getClient: () => conn }, } as any); @@ -241,7 +241,7 @@ describe('drafts:delete — the scan it puts on the wire', () => { // change that was supposed to make the removal reliable. it('still deletes a draft that only the widened scan can find', async () => { const conn = { selectFolder: async () => {}, deleteAndExpunge: vi.fn(async () => {}), ...scannerOver([], [['d1@x', 12]]) }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, deleteEmail: vi.fn(), getClient: () => conn }, } as any); @@ -258,7 +258,7 @@ describe('drafts:delete — the scan it puts on the wire', () => { it('queues a durable removal when the scan times out', async () => { const deleteEmail = vi.fn(async () => ({ success: true })); rows[0] = { message_id: '', uid: 41 }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, diff --git a/apps/desktop/test/unit/electron/ipc/draft-sent-copy-kept.test.ts b/apps/desktop/test/unit/electron/ipc/draft-sent-copy-kept.test.ts index 8d9706db..8b7e567c 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-sent-copy-kept.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-sent-copy-kept.test.ts @@ -46,12 +46,12 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); // eslint-disable-next-line import/order -- see local-mirror-content-hash.test.ts import { newMigratedDb } from '../../../../../../packages/storage-node/src/test-support/test-db'; import { deleteDraftsForThread, registerDraftHandlers } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; import { sendToWindow } from '../../../../electron/shared'; // A provider whose Drafts folder is NOT one of the standard names, so only the @@ -122,7 +122,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { it('drafts:delete by thread removes only drafts, locally and on the server', async () => { const db = threadWithSentCopies(); const deleteEmail = vi.fn(async () => ({ success: true })); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false, deleteEmail }, } as any); @@ -138,7 +138,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { // markers, deleting the very Sent copy the send had just stored. it('the post-send cleanup removes only drafts', async () => { const db = threadWithSentCopies(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -154,7 +154,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { const db = mailbox(); addRow(db, { id: 'draft', tags: '|draft|', uid: 0 }); addRow(db, { id: 'sent', tags: `|${SENT}|draft|`, uid: 900 }); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -166,7 +166,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { // Breaks: the junk-draft sweep took stale-tagged Sent copies in its window. it('drafts:cleanup sweeps only drafts', async () => { const db = threadWithSentCopies(); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false }, } as any); @@ -183,7 +183,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { addRow(db, { id: 'draft', tags: '|draft|', uid: 0 }); addRow(db, { id: 'sent', tags: `|${SENT}|draft|`, uid: 900 }); db.prepare('UPDATE emails SET date = date + 60 WHERE id = ?').run('sent'); - vi.mocked(resolveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: {} } as any); + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: {} } as any); const res = await call('drafts:find-for-thread', [''], 'acct-1'); @@ -202,7 +202,7 @@ describe('draft deletes keep the reader\'s Sent copies', () => { }, }; const deleteEmail = vi.fn(async () => ({ success: true })); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: storageOver(db), syncEngine: { isConnected: () => false, deleteEmail }, } as any); diff --git a/apps/desktop/test/unit/electron/ipc/draft-server-delete.test.ts b/apps/desktop/test/unit/electron/ipc/draft-server-delete.test.ts index 6f5824ea..f1f43721 100644 --- a/apps/desktop/test/unit/electron/ipc/draft-server-delete.test.ts +++ b/apps/desktop/test/unit/electron/ipc/draft-server-delete.test.ts @@ -45,10 +45,10 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { registerDraftHandlers, serverDeletableUids } from '../../../../electron/ipc/draft-handlers'; -import { resolveAccountTarget } from '../../../../electron/services/account-target'; +import { resolveNamedOrActiveAccountTarget } from '../../../../electron/services/account-target'; describe('serverDeletableUids', () => { // Breaks: rows whose draft really is on the server are skipped, so nothing is @@ -107,7 +107,7 @@ describe('drafts:delete — durability of the server removal', () => { // fresh draft the moment connectivity returned. it('queues a durable server delete when IMAP is offline', async () => { const deleteEmail = vi.fn(async () => ({ success: true })); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => false, deleteEmail }, } as any); @@ -123,7 +123,7 @@ describe('drafts:delete — durability of the server removal', () => { // server copy survives with nothing scheduled to remove it. it('queues a durable server delete when the in-line IMAP delete throws', async () => { const deleteEmail = vi.fn(async () => ({ success: true })); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, @@ -146,7 +146,7 @@ describe('drafts:delete — durability of the server removal', () => { it('does not queue anything when the in-line delete removes the message', async () => { const deleteEmail = vi.fn(async () => ({ success: true })); const deleteAndExpunge = vi.fn(async () => {}); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, @@ -167,7 +167,7 @@ describe('drafts:delete — durability of the server removal', () => { // Message-ID→UID, so nobody can tell a real removal from a no-op. it('reports that a UID-less row could not be resolved on the server', async () => { rows[0] = { message_id: '', uid: 0 }; - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, @@ -188,7 +188,7 @@ describe('drafts:delete — durability of the server removal', () => { it('deletes a UID-less row located by the Message-ID scan', async () => { rows[0] = { message_id: '', uid: 0 }; const deleteAndExpunge = vi.fn(async () => {}); - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: { isConnected: () => true, @@ -211,7 +211,7 @@ describe('drafts:delete — durability of the server removal', () => { // Breaks: an account with no engine at all (still initialising, removed // mid-flight) throws out of the handler and the local cleanup is lost too. it('still succeeds locally when there is no sync engine to queue against', async () => { - vi.mocked(resolveAccountTarget).mockResolvedValue({ + vi.mocked(resolveNamedOrActiveAccountTarget).mockResolvedValue({ storage: makeStorage(), syncEngine: null, } as any); diff --git a/apps/desktop/test/unit/electron/ipc/email-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/email-handlers.test.ts index e231d6a8..6b89b30d 100644 --- a/apps/desktop/test/unit/electron/ipc/email-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/email-handlers.test.ts @@ -67,7 +67,10 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/body-prefetch-scheduler', () => ({ deferBodyPrefetch: vi.fn() })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); vi.mock('../../../../electron/ipc/agent-handlers', () => ({ logUserAction: h.logUserAction })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ readRegistryAccounts: () => [{ id: 'active-account' }, { id: 'other-account' }] })); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => [{ id: 'active-account' }, { id: 'other-account' }]; + return { readRegistryAccounts, isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id) }; +}); import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; import { @@ -76,6 +79,7 @@ import { registerEmailHandlers, restoreEmailsFromTrash, } from '../../../../electron/ipc/email-handlers'; +import { ensureAccountRuntime } from '../../../../electron/services/accounts-runtime'; import { isRetryableBodyFetchError, looksGoneFromServer } from '../../../../src/store/body-fetch-failures'; const fetchBodiesBatch = () => h.handlers.get('emails:fetchBodiesBatch')!; @@ -1165,3 +1169,62 @@ describe('emails:search — what reaches the log', () => { } }); }); + +// These handlers used the LENIENT resolver: a named account that could not be +// resolved (removed, or held for a compaction) silently became the ACTIVE +// account. For an email id that only turned into "Email not found", but +// account:getQuota showed the active mailbox's usage under the other +// account's name, and emails:searchServer ran the user's search on the active +// account's server and filed the results in its database. What breaks if +// this fails: one of them falls back to the active account again. +describe('row actions on a named account that cannot be resolved — an error, never the active account', () => { + beforeEach(() => { + registerEmailHandlers(); + h.namedStorage = null; // no open runtime for the named account + vi.mocked(ensureAccountRuntime).mockReset().mockResolvedValue(null); // and it cannot be opened (held) + }); + + // Breaks: the storage bar shows the active account's quota for another account. + it("account:getQuota does not answer with the active account's quota", async () => { + const getQuota = vi.fn(async () => ({ used: 1, limit: 2 })); + (h.syncEngine as unknown as { getQuota: typeof getQuota }).getQuota = getQuota; + const res = await h.handlers.get('account:getQuota')!({}, 'other-account'); + expect(res).toEqual({ success: false, error: 'Account other-account is not available' }); + expect(getQuota).not.toHaveBeenCalled(); + // The single-account path still works. + expect(await h.handlers.get('account:getQuota')!({}, undefined)).toEqual({ success: true, data: { used: 1, limit: 2 } }); + }); + + // Breaks: a server search meant for account B runs on the active account's + // server and lands in its database. + it("emails:searchServer does not run on the active account's engine", async () => { + const serverSearch = vi.fn(async () => []); + (h.syncEngine as unknown as { serverSearch: typeof serverSearch }).serverSearch = serverSearch; + const res = await h.handlers.get('emails:searchServer')!({}, { query: { text: 'x' }, accountId: 'other-account' }); + expect(res).toMatchObject({ success: false, error: 'Account other-account is not available' }); + expect(serverSearch).not.toHaveBeenCalled(); + }); + + // Breaks: a mark-read for another account's row reads the active database. + it.each([ + ['emails:markRead', ['e1', true]], + ['emails:markStarred', ['e1', true]], + ['emails:moveToTrash', ['e1']], + ['emails:archive', ['e1']], + ['emails:delete', ['e1']], + ['emails:setCalendarAdded', ['e1', true]], + ])('%s refuses instead of looking in the active account', async (channel, args) => { + const res = await h.handlers.get(channel)!({}, ...args, 'other-account'); + expect(res).toMatchObject({ success: false, error: 'Account other-account is not available' }); + expect(h.storage.getEmail).not.toHaveBeenCalled(); + expect(h.storage.updateEmail).not.toHaveBeenCalled(); + }); + + // Breaks: an account that is not configured at all gets a runtime opened + // (production would create a blank database for it). + it('never tries to open an account the registry does not list', async () => { + const res = await h.handlers.get('emails:markRead')!({}, 'e1', true, 'gone-account'); + expect(res).toMatchObject({ success: false, error: 'Account gone-account is not available' }); + expect(ensureAccountRuntime).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/email-thread-ownership.test.ts b/apps/desktop/test/unit/electron/ipc/email-thread-ownership.test.ts index 2eed9d7a..44dc61b7 100644 --- a/apps/desktop/test/unit/electron/ipc/email-thread-ownership.test.ts +++ b/apps/desktop/test/unit/electron/ipc/email-thread-ownership.test.ts @@ -7,7 +7,6 @@ const h = vi.hoisted(() => ({ registered: true, changed: false, strict: vi.fn(), - lenient: vi.fn(), })); vi.mock('electron', () => ({ ipcMain: { handle: (name: string, handler: (...args: unknown[]) => Promise) => h.handlers.set(name, handler) }, dialog: {}, shell: {}, app: { getPath: () => '/tmp' } })); vi.mock('../../../../electron/shared', () => ({ @@ -17,8 +16,10 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/body-prefetch-scheduler', () => ({ deferBodyPrefetch: vi.fn() })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); vi.mock('../../../../electron/ipc/agent-handlers', () => ({ logUserAction: vi.fn() })); +// Changed deliberately: the lenient resolver no longer exists (every caller +// resolves strictly), so there is no fallback resolver left to mock or to +// assert unused — the module cannot reach one. vi.mock('../../../../electron/services/account-target', () => ({ - resolveAccountTarget: h.lenient, resolveNamedOrActiveAccountTarget: h.strict, requireTargetAccountId: (id: string) => { if (id !== 'cited' || !h.registered) throw new Error('Source account unavailable'); return id; }, })); @@ -31,7 +32,6 @@ beforeEach(() => { h.active.getEmailsByThread.mockResolvedValue([{ id: 'same-id', account: 'wrong-active-account' }]); h.cited.getEmailsByThread.mockResolvedValue([{ id: 'same-id', account: 'cited-account' }]); h.active.getEmail.mockResolvedValue(null); h.cited.getEmail.mockResolvedValue(null); - h.lenient.mockResolvedValue({ storage: h.active, syncEngine: null }); h.strict.mockImplementation(async (id?: string) => ({ storage: id === undefined || h.changed ? h.active : h.cited, syncEngine: null })); registerEmailHandlers(); }); @@ -43,7 +43,6 @@ describe('source thread mailbox ownership', () => { expect(await load('cited')).toEqual({ success: true, data: [{ id: 'same-id', account: 'cited-account' }] }); expect(h.cited.getEmailsByThread).toHaveBeenCalledExactlyOnceWith('same-thread'); expect(h.active.getEmailsByThread).not.toHaveBeenCalled(); - expect(h.lenient).not.toHaveBeenCalled(); }); it('preserves the unnamed active-mailbox path', async () => { diff --git a/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts b/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts index e9e3b8ab..da230dad 100644 --- a/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts +++ b/apps/desktop/test/unit/electron/ipc/imap-connect-security.test.ts @@ -25,6 +25,10 @@ const h = vi.hoisted(() => { forgetImapAccountFor: vi.fn(async (_account: Record) => true), /** The engine on screen, when it is not `engine`: makes `engine` a background account. */ active: null as object | null, + /** No active runtime yet (the renderer booted without its pointer): drives self-activation. */ + noActiveEngine: false, + /** Whether the named account's database file is on disk. */ + dbExists: false, engine: { isConnected: vi.fn(() => false), connect: vi.fn(async (_cfg: Record) => {}), @@ -81,7 +85,7 @@ vi.mock('../../../../electron/shared', () => ({ getStorage: () => null, requireStorage: () => ({}), getStorageFor: () => null, - getSyncEngine: () => h.active ?? h.engine, + getSyncEngine: () => (h.noActiveEngine ? null : h.active ?? h.engine), getSyncEngineFor: () => h.engine, requireSyncEngine: () => h.engine, getMainWindow: () => ({ isDestroyed: () => false, webContents: { send: (channel: string, payload?: unknown, code?: unknown) => h.sent.push(code === undefined ? [channel, payload] : [channel, payload, code]) } }), @@ -94,7 +98,7 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(async () => ({ storage: { getFolders: async () => [] }, syncEngine: h.engine })), accountInboxUnread: vi.fn(() => 0), - accountDbExists: () => false, + accountDbExists: () => h.dbExists, })); vi.mock('../../../../electron/services/oauth-service', () => ({ getValidAccessToken: vi.fn(), attachImapBearer: (c: unknown) => c })); vi.mock('../../../../electron/services/body-prefetch-scheduler', () => ({ kickBodyPrefetchScheduler: vi.fn() })); @@ -114,7 +118,9 @@ vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ import { registerSyncHandlers } from '../../../../electron/ipc/sync-handlers'; import { resetFakeCoreDb } from '../../../../electron/services/__testing__/fake-core-db'; +import { ensureAccountRuntime } from '../../../../electron/services/accounts-runtime'; import { setAccountSecrets } from '../../../../electron/services/secure-credential-store'; +import { setCurrentAccount } from '../../../../electron/shared'; const NONE_ACCOUNT = { host: 'mail.example.org', port: 143, secure: false, security: 'none', allowInsecureTLS: true, @@ -131,6 +137,10 @@ beforeEach(() => { h.clearImapAccount.mockClear(); h.forgetImapAccountFor.mockClear(); h.active = null; + h.noActiveEngine = false; + h.dbExists = false; + vi.mocked(setCurrentAccount).mockClear(); + vi.mocked(ensureAccountRuntime).mockClear(); h.engine.connect.mockReset().mockResolvedValue(undefined); h.engine.forceReconnect.mockReset().mockResolvedValue(undefined); // Connected with a config = connect() or forceReconnect() dialled that very object. @@ -257,3 +267,39 @@ describe('imap:connect — a rejected sign-in, with several accounts', () => { expect(h.forgetImapAccountFor).toHaveBeenLastCalledWith(expect.objectContaining({ username: 'renamed@x.com' })); }); }); + +// imap:connect adopts the named account's existing database when the renderer +// booted without its active-account pointer (no active engine yet). What breaks +// if this fails: an id the registry does not list (refused inside +// ensureAccountRuntime) still moved main's active pointer — onto an empty slot, +// so every following call failed "Storage not initialized" — or a configured +// account was no longer adopted at all. +describe('imap:connect — self-activation of an existing account database', () => { + // Breaks: a renderer that lost its pointer can no longer bring its own + // (configured) account up — the app stays "Storage not initialized". + it('adopts a configured account whose database is on disk, then points at it', async () => { + h.noActiveEngine = true; + h.dbExists = true; + await connect(NONE_ACCOUNT); + expect(ensureAccountRuntime).toHaveBeenCalledWith('acct-a'); + expect(setCurrentAccount).toHaveBeenCalledExactlyOnceWith('acct-a'); + }); + + // Breaks (CASA 3.1.3): the refusal was ignored and the pointer moved anyway. + it('leaves the active pointer alone when the account cannot be opened', async () => { + h.noActiveEngine = true; + h.dbExists = true; + vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); + await connect(NONE_ACCOUNT); + expect(ensureAccountRuntime).toHaveBeenCalledWith('acct-a'); + expect(setCurrentAccount).not.toHaveBeenCalled(); + }); + + // Breaks: a blank mailbox is spun up for an id whose data is not on disk. + it('never opens anything when the database is not on disk', async () => { + h.noActiveEngine = true; + await connect(NONE_ACCOUNT); + expect(ensureAccountRuntime).not.toHaveBeenCalled(); + expect(setCurrentAccount).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts b/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts index 7f0a5104..5386ac4a 100644 --- a/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts +++ b/apps/desktop/test/unit/electron/ipc/imap-oauth-host-binding.test.ts @@ -1,3 +1,4 @@ +import { accountIdFor } from '@sarvinbox/core'; import { beforeEach, describe, expect, it, vi } from 'vitest'; // What breaks if this file fails: an IMAP connect path mints the user's OAuth @@ -92,6 +93,7 @@ vi.mock('../../../../electron/services/unified-pipeline-service', () => ({ })); import { registerSyncHandlers } from '../../../../electron/ipc/sync-handlers'; +import { clearVerifiedAccounts, takeVerifiedAccount } from '../../../../electron/services/account-add-proof'; const SAVED_APP_PW = { password: 'app-pw', host: 'mail.example.org', allowInsecureTLS: false, allowPlaintext: false }; @@ -112,6 +114,7 @@ beforeEach(() => { h.probeConnect.mockReset().mockResolvedValue(undefined); h.engine.isConnected.mockReset().mockReturnValue(false); h.engine.connect.mockReset().mockResolvedValue(undefined); + clearVerifiedAccounts(); registerSyncHandlers(); }); @@ -130,6 +133,25 @@ describe('imap:probeCredentials', () => { expect(res.success).toBe(false); expect(h.probeConnect).not.toHaveBeenCalled(); }); + + // Breaks (item 4): adding an account. accounts:setActive opens a database for + // an account not yet in the registry ONLY on main's own proof that it signed + // in — the successful probe every add path makes first. + it('records a sign-in proof for exactly the probed address and host when the probe succeeds', async () => { + expect(await h.handlers.get('imap:probeCredentials')!({}, GMAIL)).toEqual({ success: true }); + expect(takeVerifiedAccount(accountIdFor('me@gmail.com', 'imap.evil.example'))).toBe(false); + expect(takeVerifiedAccount(accountIdFor('me@gmail.com', 'imap.gmail.com'))).toBe(true); + }); + + // Breaks: a probe that FAILED (bad password, refused token destination) + // still let the window activate an unlisted account. + it('records no proof when the probe fails or is refused', async () => { + h.probeConnect.mockRejectedValueOnce(new Error('AUTHENTICATIONFAILED')); + expect((await h.handlers.get('imap:probeCredentials')!({}, GMAIL)).success).toBe(false); + expect((await h.handlers.get('imap:probeCredentials')!({}, EVIL)).success).toBe(false); + expect(takeVerifiedAccount(accountIdFor('me@gmail.com', 'imap.gmail.com'))).toBe(false); + expect(takeVerifiedAccount(accountIdFor('me@gmail.com', 'imap.evil.example'))).toBe(false); + }); }); describe('imap:connect', () => { diff --git a/apps/desktop/test/unit/electron/ipc/inbox-assistant-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/inbox-assistant-handlers.test.ts index c02bcd52..a506832e 100644 --- a/apps/desktop/test/unit/electron/ipc/inbox-assistant-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/inbox-assistant-handlers.test.ts @@ -42,10 +42,15 @@ vi.mock('../../../../electron/shared', () => ({ getAllAccountRuntimes: () => [], })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: h.ensureRuntime })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ - readRegistryAccounts: () => { if (h.registryError) throw new Error('Account registry unavailable.'); return h.registered; }, - resolveAccountIdentity: () => ({ aliases: [] }), -})); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => { if (h.registryError) throw new Error('Account registry unavailable.'); return h.registered; }; + return { + readRegistryAccounts, + // The shared membership check, read through this mock's (throwing) registry. + isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a: { id: string }) => a.id === id), + resolveAccountIdentity: () => ({ aliases: [] }), + }; +}); vi.mock('../../../../electron/services/assistant-attachment-reader', () => ({ readAssistantAttachment: vi.fn() })); vi.mock('../../../../electron/services/assistant-mailbox-download', () => ({ fetchAssistantMessageBody: vi.fn() })); vi.mock('../../../../electron/services/inbox-assistant-history', () => ({ inboxAssistantHistory: { read: vi.fn(), write: vi.fn() } })); diff --git a/apps/desktop/test/unit/electron/ipc/local-mirror-content-hash.test.ts b/apps/desktop/test/unit/electron/ipc/local-mirror-content-hash.test.ts index f327a219..fafbdb69 100644 --- a/apps/desktop/test/unit/electron/ipc/local-mirror-content-hash.test.ts +++ b/apps/desktop/test/unit/electron/ipc/local-mirror-content-hash.test.ts @@ -67,7 +67,7 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { writeLocalDraftRow } from '../../../../electron/ipc/draft-handlers'; import { writeLocalSentRow } from '../../../../electron/ipc/smtp-handlers'; diff --git a/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts b/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts index 7c739d2c..0bbdd99e 100644 --- a/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts +++ b/apps/desktop/test/unit/electron/ipc/pgp-handlers.test.ts @@ -11,7 +11,7 @@ vi.mock('electron', () => ({ safeStorage: {}, })); vi.mock('fs/promises', () => ({ writeFile: h.writeFile })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: h.resolve, requireTargetAccountId: h.requireTarget })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: h.resolve, requireTargetAccountId: h.requireTarget })); vi.mock('../../../../electron/services/pgp-service', () => ({ getPgpKeyring: () => h.keyring, readPgpPrefsFromSettings: () => h.prefs(), diff --git a/apps/desktop/test/unit/electron/ipc/send-pgp-wiring.test.ts b/apps/desktop/test/unit/electron/ipc/send-pgp-wiring.test.ts index 5c267d72..159da7b0 100644 --- a/apps/desktop/test/unit/electron/ipc/send-pgp-wiring.test.ts +++ b/apps/desktop/test/unit/electron/ipc/send-pgp-wiring.test.ts @@ -38,7 +38,7 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); vi.mock('../../../../electron/services/pgp-service', () => ({ sendTransformFor: h.sendTransformFor })); vi.mock('../../../../electron/ipc/follow-up-handlers', () => ({ recordFollowUpForSend: vi.fn() })); vi.mock('../../../../electron/services/local-calendar-invitations', () => ({ diff --git a/apps/desktop/test/unit/electron/ipc/sent-append.test.ts b/apps/desktop/test/unit/electron/ipc/sent-append.test.ts index 7e960eee..7ff15aad 100644 --- a/apps/desktop/test/unit/electron/ipc/sent-append.test.ts +++ b/apps/desktop/test/unit/electron/ipc/sent-append.test.ts @@ -47,7 +47,7 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ notifyOutboxChanged: vi.fn(), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); import { appendSentCopy } from '../../../../electron/ipc/smtp-handlers'; import { getStorage, getSyncEngine } from '../../../../electron/shared'; diff --git a/apps/desktop/test/unit/electron/ipc/sent-attachments.test.ts b/apps/desktop/test/unit/electron/ipc/sent-attachments.test.ts index 0e19ec32..5344dbaa 100644 --- a/apps/desktop/test/unit/electron/ipc/sent-attachments.test.ts +++ b/apps/desktop/test/unit/electron/ipc/sent-attachments.test.ts @@ -20,7 +20,7 @@ vi.mock('../../../../electron/shared', () => ({ getAccountIdForStorage: vi.fn((storage: object | null) => storage ? h.storageAccounts.get(storage) ?? null : null), })); vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn() })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); // The real encrypted attachment store derives its own keys from the database // key; these tests use a deterministic fixture instead of the OS keychain. vi.mock('../../../../electron/services/db-key-store', () => ({ getDbEncryptionKey: vi.fn(() => 'k'.repeat(64)) })); diff --git a/apps/desktop/test/unit/electron/ipc/smtp-oauth-host-binding.test.ts b/apps/desktop/test/unit/electron/ipc/smtp-oauth-host-binding.test.ts index ca77efad..77f5cc7f 100644 --- a/apps/desktop/test/unit/electron/ipc/smtp-oauth-host-binding.test.ts +++ b/apps/desktop/test/unit/electron/ipc/smtp-oauth-host-binding.test.ts @@ -58,7 +58,12 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ drainOutboxForAccount: vi.fn(async () => {}), notifyOutboxChanged: vi.fn(), })); -vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(async () => {}) })); +// Changed deliberately: smtp:connectFor now refuses when the account's runtime +// cannot be opened (an account the registry does not list), so the stand-in +// answers with an open runtime the way a configured account's would. +vi.mock('../../../../electron/services/accounts-runtime', () => ({ + ensureAccountRuntime: vi.fn(async () => ({ storage: {}, syncEngine: null, smtpClient: null })), +})); vi.mock('../../../../electron/services/pgp-service', () => ({ sendTransformFor: vi.fn() })); vi.mock('../../../../electron/ipc/follow-up-handlers', () => ({ recordFollowUpForSend: vi.fn() })); diff --git a/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts b/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts index c606bb75..02d1b13a 100644 --- a/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts +++ b/apps/desktop/test/unit/electron/ipc/smtp-vault-password.test.ts @@ -57,12 +57,18 @@ vi.mock('../../../../electron/services/outbox-service', () => ({ drainOutboxForAccount: vi.fn(async () => {}), notifyOutboxChanged: vi.fn(), })); -vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(async () => {}) })); +// Changed deliberately: smtp:connectFor now refuses when the account's runtime +// cannot be opened (an account the registry does not list), so the stand-in +// answers with an open runtime the way a configured account's would. +vi.mock('../../../../electron/services/accounts-runtime', () => ({ + ensureAccountRuntime: vi.fn(async () => ({ storage: {}, syncEngine: null, smtpClient: null })), +})); vi.mock('../../../../electron/services/pgp-service', () => ({ sendTransformFor: vi.fn() })); vi.mock('../../../../electron/ipc/follow-up-handlers', () => ({ recordFollowUpForSend: vi.fn() })); import { registerSmtpHandlers } from '../../../../electron/ipc/smtp-handlers'; import { resetFakeCoreDb, state as dbState } from '../../../../electron/services/__testing__/fake-core-db'; +import { ensureAccountRuntime } from '../../../../electron/services/accounts-runtime'; import { getAccountSecrets, setAccountSecrets } from '../../../../electron/services/secure-credential-store'; import { captureRegistryForLegacyBinding } from '../../../../electron/services/vault-credentials'; @@ -149,6 +155,18 @@ describe('smtp:connectFor (multi-account send-as)', () => { expect(res.success).toBe(false); expect(h.connect).not.toHaveBeenCalled(); }); + + // Breaks (CASA 3.1.4): send-as for an account the registry does not list + // (a removed account the renderer still names) went ahead — the runtime + // slot was "ensured" without looking at the answer, the vault was read and + // the server dialled for an account that no longer exists here. + it('refuses an account whose runtime cannot be opened, before reading the vault or dialling', async () => { + vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); + const res = await h.handlers.get('smtp:connectFor')!({}, 'acct-gone', SAVED); + expect(res).toEqual({ success: false, error: 'Account acct-gone is not available' }); + expect(ensureAccountRuntime).toHaveBeenCalledWith('acct-gone'); + expect(h.connect).not.toHaveBeenCalled(); + }); }); // How the saved password is sent is the user's choice saved WITH it, not the diff --git a/apps/desktop/test/unit/electron/ipc/strict-account-targets.test.ts b/apps/desktop/test/unit/electron/ipc/strict-account-targets.test.ts new file mode 100644 index 00000000..50c42b4c --- /dev/null +++ b/apps/desktop/test/unit/electron/ipc/strict-account-targets.test.ts @@ -0,0 +1,373 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: data keyed by something EVERY mailbox holds +// lands in the wrong one. A sender address, a thread id, a Message-ID and a +// label name all exist in both of these accounts' databases (thread ids come +// from headers). These handlers used to resolve a named account LENIENTLY: when +// it could not be resolved (removed, held for maintenance) they quietly used +// the ACTIVE account instead — trusting a sender there (its mail then bypasses +// the spam filter), deleting the active account's drafts of the same +// conversation, reopening its draft in another account's composer, or creating +// a label in it. Now a named account that cannot be resolved is an error the +// caller sees, and the active account's database is untouched. +// +// Real account databases (the built storage facade over temp files) and the +// REAL account-target resolver; only the runtime registry, the account +// registry and the handlers' unrelated edges are stand-ins. + +const h = vi.hoisted(() => ({ + handlers: new Map unknown>(), + current: 'acct-a' as string | null, + /** Open runtimes: account id → storage. */ + byId: new Map(), + engines: new Map(), + /** The account registry's ids. */ + registry: ['acct-a', 'acct-b'] as string[], + registryError: null as Error | null, + /** Every id ensureAccountRuntime was asked to OPEN (create) a database for. */ + created: [] as string[], +})); + +vi.mock('electron', () => ({ + ipcMain: { handle: (name: string, fn: (...a: unknown[]) => unknown) => h.handlers.set(name, fn) }, +})); +vi.mock('../../../../electron/shared', () => ({ + getCurrentAccountId: () => h.current, + requireStorage: () => { + const active = h.current ? h.byId.get(h.current) : null; + if (!active) throw new Error('Storage not initialized'); + return active; + }, + getSyncEngine: () => (h.current ? h.engines.get(h.current) ?? null : null), + getStorageFor: (id: string) => h.byId.get(id) ?? null, + getSyncEngineFor: (id: string) => h.engines.get(id) ?? null, + getAllAccountIds: () => [...h.byId.keys()], + getAllAccountRuntimes: () => [...h.byId.entries()].map(([id, storage]) => [id, { storage, syncEngine: h.engines.get(id) ?? null, smtpClient: null }]), + getMainWindow: () => null, + sendToWindow: vi.fn(), +})); +// Deliberately PERMISSIVE (production's also checks the registry): an open +// runtime is handed back as production does, and ANY other id gets a blank +// database — so these tests prove the handlers never get that far for an +// account the registry does not list. +const openOrCreate = vi.hoisted(() => async (id: string) => { + if (h.byId.has(id)) return { storage: h.byId.get(id), syncEngine: h.engines.get(id) ?? null, smtpClient: null }; + h.created.push(id); + return { storage: { blankDatabaseFor: id }, syncEngine: null, smtpClient: null }; +}); +vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(openOrCreate) })); +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = () => { + if (h.registryError) throw h.registryError; + return h.registry.map((id) => ({ id, email: `${id}@x.test` })); + }; + return { readRegistryAccounts, isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id) }; +}); +vi.mock('../../../../electron/services/reputation-service', () => ({ reportSenderVerdict: vi.fn() })); +vi.mock('../../../../electron/services/spam-reputation-service', () => ({ getSpamReputationState: vi.fn(), kickSpamReputation: vi.fn() })); +vi.mock('../../../../electron/services/attachment-cache', () => ({ seedAttachmentCache: vi.fn() })); +vi.mock('../../../../electron/services/read-model-poke', () => ({ pokeReadModel: vi.fn() })); +vi.mock('../../../../electron/services/pgp-outgoing', () => ({ encryptDraftMime: vi.fn() })); +vi.mock('../../../../electron/services/pgp-service', () => ({ getPgpKeyring: vi.fn() })); + +import { captureLogs } from '../../../../../../packages/core/src/test-support/log-capture'; +import { deleteDraftsForThread, registerDraftHandlers } from '../../../../electron/ipc/draft-handlers'; +import { registerLabelHandlers } from '../../../../electron/ipc/label-handlers'; +import { registerSpamHandlers } from '../../../../electron/ipc/spam-handlers'; +import { ensureAccountRuntime } from '../../../../electron/services/accounts-runtime'; +import { openTestAccount, type TestAccount } from '../../../helpers/account-storage'; + +registerSpamHandlers(); +registerLabelHandlers(); +registerDraftHandlers(); + +type Envelope = { success: boolean; data?: any; error?: string; results?: any[] }; +const call = async (channel: string, ...args: unknown[]): Promise => + (await h.handlers.get(channel)!({} as never, ...args)) as Envelope; + +const SENDER = 'newsletter@shared.example'; +const THREAD = 'thread-shared'; +const PARENT = ''; + +let dir = ''; +let accountA: TestAccount; +let accountB: TestAccount; +let a: TestAccount['storage']; +let b: TestAccount['storage']; + +/** Account B as the registry and runtimes see it after it was removed. */ +const removeB = () => { h.registry = ['acct-a']; h.byId.delete('acct-b'); h.engines.delete('acct-b'); }; +/** Account B configured, but its runtime closed and unopenable (a compaction hold). */ +const holdB = () => { + h.byId.delete('acct-b'); + h.engines.delete('acct-b'); + vi.mocked(ensureAccountRuntime).mockResolvedValue(null); +}; + +const draftRows = (account: TestAccount['storage']) => + ((account as unknown as { db: { prepare: (sql: string) => { all: (...p: unknown[]) => unknown[] } } }).db + .prepare("SELECT message_id AS messageId, subject FROM emails WHERE instr(tags, '|draft|') > 0 ORDER BY subject").all()) as Array<{ messageId: string; subject: string }>; +const saveDraft = (subject: string, accountId?: string) => + call('drafts:save', { subject, to: 'them@shared.example', body: subject, threadId: THREAD, inReplyTo: PARENT, accountEmail: 'me@x.test', accountId }); + +beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), 'strict-account-targets-')); + accountA = await openTestAccount(dir, 'a'); + accountB = await openTestAccount(dir, 'b'); + // The SAME conversation in both mailboxes, as header-derived ids give it. + await accountA.add(THREAD, { id: 'a1', messageId: PARENT, fromAddress: SENDER }); + await accountB.add(THREAD, { id: 'b1', messageId: PARENT, fromAddress: SENDER }); + a = accountA.storage; + b = accountB.storage; + h.current = 'acct-a'; + h.byId = new Map([['acct-a', a], ['acct-b', b]]); + // Offline engines: a draft is written to the local mirror only. + h.engines = new Map([['acct-a', { isConnected: () => false }], ['acct-b', { isConnected: () => false }]]); + h.registry = ['acct-a', 'acct-b']; + h.registryError = null; + h.created = []; + vi.mocked(ensureAccountRuntime).mockReset(); + vi.mocked(ensureAccountRuntime).mockImplementation(openOrCreate as never); +}); + +afterEach(async () => { + await accountA.close(); + await accountB.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe('spam:trustSender / untrustSender / listTrustedSenders — the named account only (F2)', () => { + // Breaks: "Trust this sender" on account B's message lands in another + // mailbox, so B's filter still catches the sender (and A's stops). + it("trusts the sender in the named account's database only", async () => { + expect(await call('spam:trustSender', SENDER, 'acct-b')).toEqual({ success: true }); + expect((await b.getTrustedSenders()).map((t) => t.email)).toEqual([SENDER]); + expect(await a.getTrustedSenders()).toEqual([]); + expect((await call('spam:listTrustedSenders', 'acct-b')).data.map((t: { email: string }) => t.email)).toEqual([SENDER]); + expect((await call('spam:listTrustedSenders', 'acct-a')).data).toEqual([]); + }); + + // Breaks: THE finding — with account B unavailable the trust was written + // into the ACTIVE account, where that sender's authenticated mail then + // bypassed the spam filter. + it('refuses a removed account instead of trusting the sender in the active one', async () => { + removeB(); + const res = await call('spam:trustSender', SENDER, 'acct-b'); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(await a.getTrustedSenders()).toEqual([]); + expect(h.created).toEqual([]); + }); + + // Breaks: a held (compacting) account falls back to the active one. + it('refuses a configured account that cannot be opened, leaving the active one alone', async () => { + holdB(); + expect(await call('spam:trustSender', SENDER, 'acct-b')).toMatchObject({ success: false }); + expect(await a.getTrustedSenders()).toEqual([]); + }); + + // Breaks: removing a trust on account B's Security page lifts the active + // account's trust of the same sender instead (and B's stays). + it('untrusts only in the named account, and refuses an unavailable one', async () => { + await a.trustSender(SENDER); + await b.trustSender(SENDER); + expect(await call('spam:untrustSender', SENDER, 'acct-b')).toEqual({ success: true }); + expect(await b.getTrustedSenders()).toEqual([]); + expect((await a.getTrustedSenders()).map((t) => t.email)).toEqual([SENDER]); + + await b.trustSender(SENDER); + removeB(); + expect(await call('spam:untrustSender', SENDER, 'acct-b')).toMatchObject({ success: false }); + expect(await call('spam:listTrustedSenders', 'acct-b')).toMatchObject({ success: false }); + expect((await a.getTrustedSenders()).map((t) => t.email)).toEqual([SENDER]); + // Refused before any runtime was opened — no blank database for the dead id. + expect(h.created).toEqual([]); + }); + + // Breaks: the single-account path (no account named) stops working. + it('uses the active account when no account is named', async () => { + expect(await call('spam:trustSender', SENDER)).toEqual({ success: true }); + expect((await a.getTrustedSenders()).map((t) => t.email)).toEqual([SENDER]); + expect(await b.getTrustedSenders()).toEqual([]); + }); + + // Breaks: an unreadable registry read as "not configured" or "configured". + it('surfaces an unreadable registry as an error, writing nothing', async () => { + h.byId.delete('acct-b'); + h.registryError = new Error('core DB unreadable'); + expect(await call('spam:trustSender', SENDER, 'acct-b')).toMatchObject({ success: false, error: 'core DB unreadable' }); + expect(await a.getTrustedSenders()).toEqual([]); + expect(h.created).toEqual([]); + }); +}); + +describe('what a refused or failed trust writes to app.log', () => { + // Breaks (log privacy): the failure line logged the whole error, whose + // message names the account id (an address) and can quote what the storage + // was given. Only the account's label and the error's class may appear. + it('logs the account by its label and the error by its class, never the id or the message', async () => { + const SENTINEL = 'sentinel-sender-7f3a@private.example'; + vi.spyOn(b, 'trustSender').mockRejectedValueOnce(new Error(`constraint failed for ${SENTINEL}`)); + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + expect(await call('spam:trustSender', SENDER, 'acct-b')).toMatchObject({ success: false }); + removeB(); + expect(await call('spam:trustSender', SENDER, 'acct-b')).toMatchObject({ success: false }); + expect(await call('spam:setUserVerdict', 'b1', 'spam', 'acct-b')).toMatchObject({ success: false }); + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.containing('acct-b')).toEqual([]); + expect(logs.containing('spam:trustSender failed')).toHaveLength(2); + expect(logs.containing('spam:setUserVerdict failed')).toHaveLength(1); + } finally { + logs.stop(); + } + }); +}); + +describe('spam:listJudged / setUserVerdict — strict too', () => { + // Breaks: the Spam tab of an unavailable account shows the ACTIVE + // account's judged mail under its name. + it('refuses an unavailable named account rather than listing the active one', async () => { + removeB(); + expect(await call('spam:listJudged', 50, 'acct-b')).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(await call('spam:setUserVerdict', 'b1', 'spam', 'acct-b')).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(h.created).toEqual([]); + }); +}); + +describe('labels:list / labels:create / emails:setLabel — the named account only (F4)', () => { + // Breaks: a label created for account B's message (All Inboxes) is created + // in the active account, and B has no such label. + it('creates and lists a label in the named account only', async () => { + expect(await call('labels:create', { name: 'Clients' }, 'acct-b')).toMatchObject({ success: true }); + expect((await b.getLabels()).map((l) => l.name)).toEqual(['Clients']); + expect(await a.getLabels()).toEqual([]); + expect((await call('labels:list', 'acct-b')).data.map((l: { name: string }) => l.name)).toEqual(['Clients']); + expect((await call('labels:list', 'acct-a')).data).toEqual([]); + }); + + // Breaks: with account B unavailable, its label went into the ACTIVE + // account (a name both can hold), and its list showed the active account's. + it('refuses a removed or held account instead of using the active one', async () => { + removeB(); + expect(await call('labels:create', { name: 'Clients' }, 'acct-b')).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(await call('labels:list', 'acct-b')).toMatchObject({ success: false }); + expect(await a.getLabels()).toEqual([]); + expect(h.created).toEqual([]); + + h.registry = ['acct-a', 'acct-b']; + holdB(); + expect(await call('labels:create', { name: 'Held' }, 'acct-b')).toMatchObject({ success: false }); + expect(await a.getLabels()).toEqual([]); + }); + + // Breaks: tagging account B's message writes into the active account's DB + // (or, unavailable, silently does nothing there instead of failing). + it('tags the email in the named account, and refuses an unavailable one', async () => { + expect(await call('emails:setLabel', 'b1', 'Clients', true, 'acct-b')).toEqual({ success: true }); + expect((await b.getEmail('b1'))?.tags).toContain('Clients'); + + removeB(); + expect(await call('emails:setLabel', 'b1', 'Clients', true, 'acct-b')).toMatchObject({ success: false, error: expect.stringMatching(/not available/) }); + expect((await a.getEmail('a1'))?.tags ?? '').not.toContain('Clients'); + }); + + // Breaks: the single-account path (no account named) stops working. + it('uses the active account when no account is named', async () => { + expect(await call('labels:create', { name: 'Mine' })).toMatchObject({ success: true }); + expect((await a.getLabels()).map((l) => l.name)).toEqual(['Mine']); + expect(await b.getLabels()).toEqual([]); + }); +}); + +describe('drafts — thread id and Message-ID keys, the named account only (F3)', () => { + // Breaks: a draft saved for account B's conversation is written into the + // ACTIVE account's copy of the same thread when B is unavailable. + it('drafts:save refuses an unavailable named account and writes nothing to the active one', async () => { + removeB(); + const res = await saveDraft('reply from B', 'acct-b'); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(draftRows(a)).toEqual([]); + expect(h.created).toEqual([]); + }); + + // Breaks: the composer of account B's conversation reopens ANOTHER + // mailbox's draft (the In-Reply-To is in both). + it("drafts:find-for-thread finds only the named account's draft, and refuses an unavailable one", async () => { + expect(await saveDraft('reply from A')).toMatchObject({ success: true }); + expect(await saveDraft('reply from B', 'acct-b')).toMatchObject({ success: true }); + expect((await call('drafts:find-for-thread', [PARENT], 'acct-b')).data).toMatchObject({ subject: 'reply from B' }); + expect((await call('drafts:find-for-thread', [PARENT], 'acct-a')).data).toMatchObject({ subject: 'reply from A' }); + + removeB(); + const res = await call('drafts:find-for-thread', [PARENT], 'acct-b'); + expect(res).toMatchObject({ success: false }); + expect(res.data).toBeUndefined(); + }); + + // Breaks: discarding account B's draft deletes the ACTIVE account's draft of + // the same thread — the user's own unsent reply in the other mailbox. + it("drafts:delete by thread removes only the named account's draft, and refuses an unavailable one", async () => { + await saveDraft('reply from A'); + await saveDraft('reply from B', 'acct-b'); + expect(await call('drafts:delete', { threadId: THREAD, accountId: 'acct-b' })).toMatchObject({ success: true }); + expect(draftRows(b)).toEqual([]); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + + await saveDraft('another from B', 'acct-b'); + removeB(); + const res = await call('drafts:delete', { threadId: THREAD, accountId: 'acct-b' }); + expect(res).toMatchObject({ success: false, error: expect.stringMatching(/acct-b is not available/) }); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + }); + + // Breaks: drafts:delete used to resolve OUTSIDE its try, so a refusal would + // reject the invoke instead of answering — the renderer saw an exception. + it('drafts:delete answers a held account with a refusal, not a rejected promise', async () => { + await saveDraft('reply from A'); + holdB(); + await expect(call('drafts:delete', { threadId: THREAD, accountId: 'acct-b' })).resolves.toMatchObject({ success: false }); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + }); + + // Breaks: a sweep for account B wipes the ACTIVE account's drafts instead. + it("drafts:cleanup for an unavailable account reports it and leaves the active account's drafts", async () => { + await saveDraft('reply from A'); + removeB(); + const res = await call('drafts:cleanup', { accountId: 'acct-b' }); + expect(res.success).toBe(true); + expect(res.results).toEqual([{ accountId: 'acct-b', error: expect.stringMatching(/acct-b is not available/) }]); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + }); + + // Breaks: after a reply sent from account B, the send path's cleanup + // deletes the ACTIVE account's drafts of that thread when B is unavailable. + it('deleteDraftsForThread (send path) refuses an unavailable account, deleting nothing', async () => { + await saveDraft('reply from A'); + removeB(); + await expect(deleteDraftsForThread('acct-b', THREAD)).rejects.toThrow(/acct-b is not available/); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + + // And with the account available, only its own drafts go. + h.registry = ['acct-a', 'acct-b']; + h.byId.set('acct-b', b); + await saveDraft('reply from B', 'acct-b'); + await deleteDraftsForThread('acct-b', THREAD); + expect(draftRows(b)).toEqual([]); + expect(draftRows(a).map((r) => r.subject)).toEqual(['reply from A']); + }); + + // Breaks: the single-account path (no account named) stops reaching the + // active account's drafts. + it('uses the active account when no account is named', async () => { + await saveDraft('reply from A'); + await saveDraft('reply from B', 'acct-b'); + expect(await call('drafts:delete', { threadId: THREAD })).toMatchObject({ success: true }); + expect(draftRows(a)).toEqual([]); + expect(draftRows(b).map((r) => r.subject)).toEqual(['reply from B']); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/account-add-proof.test.ts b/apps/desktop/test/unit/electron/services/account-add-proof.test.ts new file mode 100644 index 00000000..cdc92faf --- /dev/null +++ b/apps/desktop/test/unit/electron/services/account-add-proof.test.ts @@ -0,0 +1,77 @@ +import { accountIdFor } from '@sarvinbox/core'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { + ADD_PROOF_TTL_MS, + clearVerifiedAccounts, + noteVerifiedAccount, + takeVerifiedAccount, +} from '../../../../electron/services/account-add-proof'; + +// What breaks if this file fails: the one exception to "only configured +// accounts get a mailbox database". An account being ADDED is activated before +// its registry row exists; main allows that only on its own proof that the +// account just signed in. A proof that is reusable, never expires, or names the +// wrong account lets the window create databases for ids nobody added. + +const T0 = 1_780_000_000_000; +const ID = accountIdFor('new@example.com', 'imap.example.com'); + +beforeEach(() => clearVerifiedAccounts()); + +describe('account add proofs', () => { + // Breaks: adding an account — the id the add flow mints must match the one + // the probe recorded (same address and host, any spelling the id ignores). + it('names the account the add flow mints for that address and host', () => { + noteVerifiedAccount('New@Example.com', 'IMAP.example.com', T0); + expect(takeVerifiedAccount(ID, T0 + 1)).toBe(true); + }); + + // Breaks: one sign-in admitting any number of activations (each a new DB). + it('admits ONE activation', () => { + noteVerifiedAccount('new@example.com', 'imap.example.com', T0); + expect(takeVerifiedAccount(ID, T0)).toBe(true); + expect(takeVerifiedAccount(ID, T0)).toBe(false); + }); + + // Breaks: a sign-in from long ago still opening a database today. + it('expires', () => { + noteVerifiedAccount('new@example.com', 'imap.example.com', T0); + expect(takeVerifiedAccount(ID, T0 + ADD_PROOF_TTL_MS + 1)).toBe(false); + // …and an expired proof is gone, not waiting for a clock that runs back. + expect(takeVerifiedAccount(ID, T0)).toBe(false); + noteVerifiedAccount('new@example.com', 'imap.example.com', T0); + expect(takeVerifiedAccount(ID, T0 + ADD_PROOF_TTL_MS)).toBe(true); + }); + + // Breaks: a proof from a clock that ran backwards (or a forged timestamp) is honoured. + it('refuses a proof dated in the future', () => { + noteVerifiedAccount('new@example.com', 'imap.example.com', T0 + 60_000); + expect(takeVerifiedAccount(ID, T0)).toBe(false); + }); + + // Breaks (multi-account): a sign-in to one server admits the same address on another. + it('is bound to the host as well as the address', () => { + noteVerifiedAccount('new@example.com', 'imap.example.com', T0); + expect(takeVerifiedAccount(accountIdFor('new@example.com', 'imap.other.example'), T0)).toBe(false); + expect(takeVerifiedAccount(accountIdFor('other@example.com', 'imap.example.com'), T0)).toBe(false); + expect(takeVerifiedAccount(ID, T0)).toBe(true); + }); + + // Breaks: a malformed probe config records a proof for a junk id. + it.each([[undefined, 'imap.example.com'], ['new@example.com', undefined], ['', 'imap.example.com'], ['new@example.com', ' '], [7, 'h']])( + 'records nothing for username %j and host %j', + (username, host) => { + noteVerifiedAccount(username, host, T0); + expect(takeVerifiedAccount(accountIdFor('default', ''), T0)).toBe(false); + expect(takeVerifiedAccount(accountIdFor('new@example.com', ''), T0)).toBe(false); + }, + ); + + // Breaks: an unbounded map of proofs grows with every probe. + it('keeps a bounded number of proofs, dropping the oldest', () => { + for (let i = 0; i < 20; i++) noteVerifiedAccount(`u${i}@example.com`, 'imap.example.com', T0); + expect(takeVerifiedAccount(accountIdFor('u0@example.com', 'imap.example.com'), T0)).toBe(false); + expect(takeVerifiedAccount(accountIdFor('u19@example.com', 'imap.example.com'), T0)).toBe(true); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/account-target.test.ts b/apps/desktop/test/unit/electron/services/account-target.test.ts index 19990772..d42ffaa3 100644 --- a/apps/desktop/test/unit/electron/services/account-target.test.ts +++ b/apps/desktop/test/unit/electron/services/account-target.test.ts @@ -6,8 +6,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; // strict resolver must never quietly hand back the ACTIVE account's storage for // another account — that is a silent read of the wrong cache, or a write of // account B's split into account A's database — nor CREATE a database for an id -// that is not a configured account. The lenient resolver keeps its documented -// fallback for row actions. +// that is not a configured account. There is no lenient resolver any more: a +// named account that cannot be resolved is an error for every caller. const h = vi.hoisted(() => ({ current: 'acct-a' as string | null, @@ -32,8 +32,10 @@ vi.mock('../../../../electron/shared', () => ({ getSyncEngineFor: (id: string) => h.engines.get(id) ?? null, getAllAccountRuntimes: () => h.runtimes, })); -// As in production: ensureAccountRuntime OPENS (creates, migrates, registers) -// a database for ANY id it is handed — it has no notion of "unknown account". +// Deliberately PERMISSIVE: this ensureAccountRuntime opens (creates, migrates, +// registers) a database for ANY id it is handed. Production's checks the +// registry too, but these tests prove account-target's OWN check — its promise +// must not rest on a check two modules away. vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: vi.fn(async (id: string) => { h.created.push(id); @@ -43,19 +45,20 @@ vi.mock('../../../../electron/services/accounts-runtime', () => ({ return rt; }), })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ - readRegistryAccounts: vi.fn(() => { +vi.mock('../../../../electron/services/accounts-registry', () => { + const readRegistryAccounts = vi.fn(() => { if (h.registryError) throw h.registryError; return h.registry.map((id) => ({ id, email: `${id}@x.test` })); - }), -})); + }); + // As in production: the membership check reads through the THROWING reader. + return { readRegistryAccounts, isRegisteredAccountId: (id: string) => readRegistryAccounts().some((a) => a.id === id) }; +}); import { openAccountStorages, requireAccountStorage, requireNamedOrActiveStorage, requireTargetAccountId, - resolveAccountTarget, resolveNamedOrActiveAccountTarget, } from '../../../../electron/services/account-target'; import { readRegistryAccounts } from '../../../../electron/services/accounts-registry'; @@ -176,92 +179,79 @@ describe('requireNamedOrActiveStorage — strict when named, active when not', ( }); }); -describe('resolveAccountTarget — lenient, unchanged', () => { - // Breaks: a row action on another account's message (unified view) hits the - // active account's database — the mark-read "Email not found" loop. - // Changed deliberately (CASA M-7): the result also names the account whose - // storage it is, which the per-account attachment store keys by. - it("returns the named account's storage and engine, opening its runtime when needed", async () => { - await expect(resolveAccountTarget('acct-b')).resolves.toEqual({ - storage: B, syncEngine: { name: 'engine-b' }, accountId: 'acct-b', - }); - await expect(resolveAccountTarget('acct-c')).resolves.toEqual({ - storage: { name: 'storage-acct-c' }, syncEngine: { name: 'engine-acct-c' }, accountId: 'acct-c', - }); - expect(readRegistryAccounts).not.toHaveBeenCalled(); - }); - - // Pinned as the documented contract of the LENIENT resolver (row actions), - // which is why the cache handlers must not use it. - // Changed deliberately (CASA M-7): the result also names its account. After a - // fallback that is the ACTIVE account, never the id that was asked for — - // otherwise an attachment read from the active account's mail would be filed - // under (and removed with) an account it does not belong to. - it('falls back to the active account for no id, the active id, or an unresolvable one', async () => { +describe('resolveNamedOrActiveAccountTarget — the one resolver, strict when named', () => { + // Breaks: the single-account path (a renderer call that names no account, + // or names the active one) stops reaching the active account, or pays a + // registry read on every call. + it('uses the active storage and engine for no id or the active id, naming the active account', async () => { const active = { storage: h.active, syncEngine: h.activeEngine, accountId: 'acct-a' }; - vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); - await expect(resolveAccountTarget()).resolves.toEqual(active); - await expect(resolveAccountTarget('acct-a')).resolves.toEqual(active); - await expect(resolveAccountTarget('acct-gone')).resolves.toEqual(active); - }); - - // Breaks: on the pre-account default slot (no active id yet) the fallback - // invents an owner — the requested id, or the literal "undefined" — for - // storage that belongs to no account. - it('names no account for the default slot before an account is active', async () => { - h.current = null; - vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); - await expect(resolveAccountTarget()).resolves.toEqual({ - storage: h.active, syncEngine: h.activeEngine, accountId: null, - }); - await expect(resolveAccountTarget('acct-gone')).resolves.toMatchObject({ storage: h.active, accountId: null }); - // A named account that resolves keeps its own id even then. - await expect(resolveAccountTarget('acct-b')).resolves.toMatchObject({ storage: B, accountId: 'acct-b' }); - }); -}); - -describe('resolveNamedOrActiveAccountTarget — mutations use the named account', () => { - it('uses active storage and engine for no id or the active id', async () => { - const active = { storage: h.active, syncEngine: h.activeEngine }; await expect(resolveNamedOrActiveAccountTarget()).resolves.toEqual(active); + await expect(resolveNamedOrActiveAccountTarget(null)).resolves.toEqual(active); await expect(resolveNamedOrActiveAccountTarget('acct-a')).resolves.toEqual(active); expect(ensureAccountRuntime).not.toHaveBeenCalled(); expect(readRegistryAccounts).not.toHaveBeenCalled(); }); - it('returns the other account storage and engine together', async () => { + // Breaks: a row action on another account's message (unified view) hits the + // active account's database — the mark-read "Email not found" loop. The + // result names the account whose storage it is (the attachment store and + // draft meeting metadata key by it). + it("returns a non-active account's own storage and engine together, with its id", async () => { await expect(resolveNamedOrActiveAccountTarget('acct-b')).resolves.toEqual({ - storage: B, syncEngine: { name: 'engine-b' }, + storage: B, syncEngine: { name: 'engine-b' }, accountId: 'acct-b', }); expect(ensureAccountRuntime).not.toHaveBeenCalled(); }); + // Breaks: an account whose runtime is not open yet (never viewed this + // session) cannot be served at all. it('opens only a configured account whose runtime is not open', async () => { await expect(resolveNamedOrActiveAccountTarget('acct-c')).resolves.toEqual({ - storage: { name: 'storage-acct-c' }, syncEngine: { name: 'engine-acct-c' }, + storage: { name: 'storage-acct-c' }, syncEngine: { name: 'engine-acct-c' }, accountId: 'acct-c', }); expect(ensureAccountRuntime).toHaveBeenCalledWith('acct-c'); }); + // Breaks: a removed account's late request recreates a blank database, or + // writes into the ACTIVE account's — the lenient resolver's old fallback. it('rejects a removed account without creating it or using the active account', async () => { await expect(resolveNamedOrActiveAccountTarget('acct-gone')).rejects.toThrow(/acct-gone is not available/); expect(ensureAccountRuntime).not.toHaveBeenCalled(); expect(h.created).toEqual([]); }); - it('rejects an unavailable configured account instead of falling back', async () => { + // Changed deliberately (CASA 3.1.3 / 3.1.4): this USED to be the lenient + // resolver's pinned contract — an unresolvable named account fell back to + // the active one. A thread id, Message-ID, sender address or label name is + // in every account's database, so that fallback trusted senders, deleted + // drafts and created labels in the wrong mailbox. It is an error now. + it('rejects an unavailable configured account (held for maintenance) instead of falling back', async () => { vi.mocked(ensureAccountRuntime).mockResolvedValueOnce(null); await expect(resolveNamedOrActiveAccountTarget('acct-c')).rejects.toThrow(/acct-c is not available/); }); - it('surfaces registry failures and resolves named accounts before an active account exists', async () => { + // Breaks: on the pre-account default slot (no active id yet) the result + // invents an owner for storage that belongs to no account, or a named + // account is matched to "active" and not resolved at all. + it('names no account for the default slot, and still resolves named accounts strictly there', async () => { h.current = null; + await expect(resolveNamedOrActiveAccountTarget()).resolves.toEqual({ + storage: h.active, syncEngine: h.activeEngine, accountId: null, + }); await expect(resolveNamedOrActiveAccountTarget('acct-b')).resolves.toEqual({ - storage: B, syncEngine: { name: 'engine-b' }, + storage: B, syncEngine: { name: 'engine-b' }, accountId: 'acct-b', }); + await expect(resolveNamedOrActiveAccountTarget('acct-gone')).rejects.toThrow(/not available/); + }); + + // Breaks: an unreadable registry read as "not configured" (or as + // "configured") — it must be an error the caller sees, opening nothing. An + // account already open needs no registry read. + it('surfaces registry failures, opening nothing', async () => { h.registryError = new Error('core DB unreadable'); await expect(resolveNamedOrActiveAccountTarget('acct-c')).rejects.toThrow(/core DB unreadable/); expect(ensureAccountRuntime).not.toHaveBeenCalled(); + await expect(resolveNamedOrActiveAccountTarget('acct-b')).resolves.toMatchObject({ storage: B, accountId: 'acct-b' }); }); }); diff --git a/apps/desktop/test/unit/electron/services/accounts-registry.test.ts b/apps/desktop/test/unit/electron/services/accounts-registry.test.ts index 71248420..cefe8a32 100644 --- a/apps/desktop/test/unit/electron/services/accounts-registry.test.ts +++ b/apps/desktop/test/unit/electron/services/accounts-registry.test.ts @@ -71,6 +71,10 @@ import { resetFakeCoreDb, state as dbState } from '../../../../electron/services import { accountRegistryExists, cleanupMigratedLegacyFiles, + clearAccountRemoved, + isAccountRemoved, + isRegisteredAccountId, + markAccountRemoved, getRegistryActiveAccountId, listRegistryAccounts, readRegistryAccounts, @@ -237,6 +241,109 @@ describe('listRegistryAccounts', () => { }); }); +// The ONE membership check every path that opens a mailbox database or +// resolves a named account relies on (ensureAccountRuntime, the strict +// resolvers, accounts:setActive). Every other suite replaces it with a mock, so +// this is the only place its real behaviour is pinned. +describe('isRegisteredAccountId — the real check', () => { + // Breaks: a configured account is refused (its mailbox can no longer be + // opened), or an unknown one is admitted (a blank database is created for it). + it('is true for exactly the listed ids', () => { + upsertRegistryAccount(account({ id: 'acct-a', email: 'a@x.com' })); + upsertRegistryAccount(account({ id: 'acct-b', email: 'b@x.com' })); + expect(isRegisteredAccountId('acct-a')).toBe(true); + expect(isRegisteredAccountId('acct-b')).toBe(true); + expect(isRegisteredAccountId('acct-c')).toBe(false); + expect(isRegisteredAccountId('acct-')).toBe(false); // a prefix is not a member + }); + + // Breaks: the empty-registry case (fresh install) admits something. + it('is false for anything when the registry is empty, and for an empty or non-string id', () => { + expect(isRegisteredAccountId('acct-a')).toBe(false); + upsertRegistryAccount(account({ id: 'acct-a', email: 'a@x.com' })); + expect(isRegisteredAccountId('')).toBe(false); + expect(isRegisteredAccountId(undefined as unknown as string)).toBe(false); + expect(isRegisteredAccountId(7 as unknown as string)).toBe(false); + }); + + // Breaks (fail securely): an unreadable registry answered "not configured" + // (a quiet refusal the caller cannot tell from a removed account) or, worse, + // "configured". "Could not find out" must THROW. + it('THROWS when the registry cannot be read — never false', () => { + upsertRegistryAccount(account({ id: 'acct-a', email: 'a@x.com' })); + dbState.fail.add('select'); + expect(() => isRegisteredAccountId('acct-a')).toThrow(); + expect(() => isRegisteredAccountId('acct-unknown')).toThrow(); + dbState.fail.delete('select'); + expect(isRegisteredAccountId('acct-a')).toBe(true); + }); +}); + +// accounts:remove drops the registry row, but the window keeps the account in +// its list until the removal returns (it waits for the OAuth sign-out), and any +// snapshot it mirrors meanwhile used to write the row straight back — on the +// next launch the removed account was "configured" again. A token left on disk +// did the same through seeding. +describe('removed-account tombstones', () => { + // Breaks: THE resurrection — a snapshot mirrored during the removal (or any + // time after) re-adds the removed account. + it('keeps a removed account out of every snapshot, without dropping the others', () => { + upsertRegistryAccount(account({ id: 'acct-a', email: 'a@x.com' })); + markAccountRemoved('acct-gone'); + upsertRegistryAccounts([ + account({ id: 'acct-gone', email: 'gone@x.com' }), + account({ id: 'acct-a', email: 'a2@x.com' }), + ]); + expect(listRegistryAccounts().map((a) => [a.id, a.email])).toEqual([['acct-a', 'a2@x.com']]); + expect(isRegisteredAccountId('acct-gone')).toBe(false); + }); + + // Breaks: a single-row write (seeding from a token left on disk) re-adds it. + it('keeps a removed account out of single upserts and of seeding', async () => { + markAccountRemoved(accountIdFor('gone@example.com', 'imap.example.com')); + upsertRegistryAccount(account({ id: accountIdFor('gone@example.com', 'imap.example.com'), email: 'gone@example.com' })); + h.imapAccount = { host: 'imap.example.com', port: 993, username: 'gone@example.com' }; + await seedAccountRegistryFromDurableStores(); + expect(listRegistryAccounts()).toEqual([]); + }); + + // Breaks: adding the account again (the add flow clears its tombstone) still + // cannot write its row — the re-added account vanishes on the next launch. + it('lets the account back once its tombstone is cleared, and only that one', () => { + markAccountRemoved('acct-gone'); + markAccountRemoved('acct-other'); + clearAccountRemoved('acct-gone'); + expect(isAccountRemoved('acct-gone')).toBe(false); + expect(isAccountRemoved('acct-other')).toBe(true); + upsertRegistryAccounts([account({ id: 'acct-gone', email: 'gone@x.com' }), account({ id: 'acct-other', email: 'o@x.com' })]); + expect(listRegistryAccounts().map((a) => a.id)).toEqual(['acct-gone']); + }); + + // Breaks: tombstones lost across a restart (memory only) — the next + // launch's mirror re-adds the account the user removed. + it('is durable (kept in the core DB), idempotent and bounded', () => { + markAccountRemoved('acct-gone'); + markAccountRemoved('acct-gone'); + expect(JSON.parse(dbState.meta.get('removed_account_ids')!)).toEqual(['acct-gone']); + for (let i = 0; i < 205; i++) markAccountRemoved(`acct-${i}`); + const kept = JSON.parse(dbState.meta.get('removed_account_ids')!) as string[]; + expect(kept).toHaveLength(200); + expect(kept.at(-1)).toBe('acct-204'); + expect(isAccountRemoved('acct-gone')).toBe(false); // the oldest went first + }); + + // Breaks: a corrupt tombstone record blocks every write, or throws at the IPC boundary. + it('reads a corrupt tombstone record as none', () => { + dbState.meta.set('removed_account_ids', '{not json'); + expect(isAccountRemoved('acct-a')).toBe(false); + upsertRegistryAccounts([account({ id: 'acct-a', email: 'a@x.com' })]); + expect(listRegistryAccounts().map((a) => a.id)).toEqual(['acct-a']); + clearAccountRemoved('acct-a'); // nothing to clear: no throw + markAccountRemoved(''); + expect(isAccountRemoved('')).toBe(false); + }); +}); + describe('upsertRegistryAccounts (snapshot mirror)', () => { it('NEVER deletes rows the snapshot omits', () => { upsertRegistryAccount(account({ id: 'kept', email: 'kept@x.com' })); diff --git a/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts b/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts index 4f4d5309..3a32b5df 100644 --- a/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts +++ b/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts @@ -38,9 +38,23 @@ const h = vi.hoisted(() => ({ secretsDeleted: [] as string[], secretsRekeyed: [] as Array<[string, string]>, secretsDeleteThrows: false, + /** The registry read fails (the throwing reader's "could not find out"). */ + registryThrows: false, + /** Every account id `isRegisteredAccountId` was asked about. */ + registryAsked: [] as string[], + /** The active-account pointer, as `setCurrentAccount` left it. */ + current: null as string | null, })); -vi.mock('../../../../electron/services/accounts-registry', () => ({ listRegistryAccounts: () => h.registry })); +vi.mock('../../../../electron/services/accounts-registry', () => ({ + listRegistryAccounts: () => h.registry, + // The throwing membership check ensureAccountRuntime gates on. + isRegisteredAccountId: (id: string) => { + h.registryAsked.push(id); + if (h.registryThrows) throw new Error('core DB unreadable'); + return h.registry.some((account) => account.id === id); + }, +})); vi.mock('electron', () => ({ app: { getPath: () => h.userData, getName: () => 'Sarv Inbox Test', isPackaged: false }, @@ -150,6 +164,7 @@ vi.mock('../../../../electron/shared', () => ({ return null; }, sendToWindow: (channel: string, payload: unknown) => { h.sent.push([channel, payload]); }, + setCurrentAccount: (accountId: string) => { h.current = accountId; }, unregisterRuntime: (accountId: string) => { h.unregistered.push(accountId); h.runtimes.delete(accountId); }, })); @@ -159,6 +174,7 @@ import { PRIMARY_DB_FILE, accountDbExists, accountInboxUnread, + activatePersistedAccount, canResolveAccountRuntimes, cleanupOrphanedAccountDbs, cleanupStaleUserDataArtifacts, @@ -195,8 +211,16 @@ beforeAll(() => { h.userData = mkdtempSync(join(tmpdir(), 'sarvinbox-runtime-')); }); +/** Make `ids` configured accounts (the registry rows ensureAccountRuntime checks). */ +const configure = (...ids: string[]): void => { + h.registry = ids.map((id) => ({ id, imapConfig: null })); +}; + beforeEach(() => { h.registry = []; + h.registryThrows = false; + h.registryAsked.length = 0; + h.current = null; resetFakeCoreDb(); h.storages.length = 0; h.engines.length = 0; @@ -371,6 +395,10 @@ describe('legacyDbExists / accountDbExists', () => { }); describe('ensureAccountRuntime', () => { + // Changed deliberately: ensureAccountRuntime opens only CONFIGURED accounts + // now, so every account these tests open is configured first. + beforeEach(() => configure('acct-a', 'acct-first', 'acct-second', 'acct-primary', 'acct-fresh')); + it('returns an already-open runtime without touching the disk', async () => { const existing = { storage: { tag: 'open' }, syncEngine: {}, smtpClient: null }; h.runtimes.set('acct-a', existing); @@ -451,6 +479,166 @@ describe('ensureAccountRuntime', () => { }); }); +/** + * The registry gate (CASA 3.1.3 / 3.1.4). Opening a runtime CREATES its + * database file when it is missing, so an id the registry does not list — a + * removed account's late background request, a stale unified-inbox id — used + * to bring a blank, migrated mailbox back from the dead, which then joined + * every all-accounts loop. + */ +describe('ensureAccountRuntime — only configured accounts', () => { + // Breaks: THE resurrection bug — an unknown id gets a new empty database, + // a sync engine and a registered runtime. + it('refuses an id the registry does not list, creating no database, file or runtime', async () => { + configure('acct-a'); + await expect(ensureAccountRuntime('acct-gone')).resolves.toBeNull(); + expect(h.storages).toHaveLength(0); + expect(h.engines).toHaveLength(0); + expect(h.runtimes.has('acct-gone')).toBe(false); + expect(existsSync(join(h.userData, dbFileForAccount('acct-gone')))).toBe(false); + expect(logLines.some((line) => line.includes('not a configured account'))).toBe(true); + }); + + // Breaks: an unreadable registry read as "not configured" (a quiet null the + // caller cannot tell from a removed account) or as "configured" (open it + // anyway). "Could not find out" must be an error, and open nothing. + it('throws when the registry cannot be read, opening nothing', async () => { + h.registryThrows = true; + await expect(ensureAccountRuntime('acct-a')).rejects.toThrow(/core DB unreadable/); + expect(h.storages).toHaveLength(0); + expect(h.runtimes.has('acct-a')).toBe(false); + }); + + // Breaks: an account already open is cut off (or pays a registry read on + // every call) the moment the registry cannot be read. + it('serves an already-open runtime without asking the registry', async () => { + h.registryThrows = true; + const existing = { storage: { tag: 'open' }, syncEngine: {}, smtpClient: null }; + h.runtimes.set('acct-a', existing); + await expect(ensureAccountRuntime('acct-a')).resolves.toBe(existing); + expect(h.registryAsked).toEqual([]); + }); + + // Breaks: adding an account — the add flow points main at the new account + // BEFORE its first connect, and its registry row is written only once that + // connect succeeds, so its first open must be allowed while it is unlisted. + // (accounts:setActive decides that, from main's own sign-in proof, and says + // so with `registryChecked`; the registry is then not read a second time.) + it('opens an unlisted id only when the caller has already decided, without reading the registry again', async () => { + await expect(ensureAccountRuntime('acct-new', { registryChecked: true })).resolves.not.toBeNull(); + expect(h.storages[0].opts.dbPath).toBe(join(h.userData, dbFileForAccount('acct-new'))); + expect(h.runtimes.has('acct-new')).toBe(true); + expect(h.registryAsked).toEqual([]); + // Being added never skips the maintenance hold. + await quiesceAccountRuntime('acct-new', 'compact', { hold: true }); + try { + await expect(ensureAccountRuntime('acct-new', { registryChecked: true })).resolves.toBeNull(); + } finally { + releaseAccountMaintenance('acct-new'); + } + }); + + // Breaks: an account being ADDED on a legacy install whose primary was never + // recorded opens (and so owns) the existing sarvinbox.db — a new account + // taking over the old mailbox. It refuses to guess instead, as for anyone. + it('never opens the legacy sarvinbox.db for an account being added', async () => { + touch(PRIMARY_DB_FILE); + await expect(ensureAccountRuntime('acct-new', { registryChecked: true })).resolves.toBeNull(); + expect(h.storages).toHaveLength(0); + expect(h.claimed).toEqual([]); + expect(loadPrimaryAccountId()).toBeNull(); + }); + + // Breaks (multi-account): one account's registry row admits another id. + it('checks the exact id, not a prefix or a sibling account', async () => { + configure('acct-a', 'acct-b'); + await expect(ensureAccountRuntime('acct-a')).resolves.not.toBeNull(); + await expect(ensureAccountRuntime('acct-a-old')).resolves.toBeNull(); + await expect(ensureAccountRuntime('')).resolves.toBeNull(); + expect(h.storages).toHaveLength(1); + }); +}); + +/** + * Startup auto-activation of the registry's persisted active account (moved out + * of main.ts so it can be tested). It used to move the active pointer FIRST and + * open second, with no registry check at all. + */ +describe('activatePersistedAccount', () => { + // Breaks: a normal launch no longer opens the last-used account before the + // window asks for it (first paint waits on the renderer's own activation). + it('opens a configured account whose DB is on disk, then points at it', async () => { + configure('acct-a'); + touch(dbFileForAccount('acct-a')); + await expect(activatePersistedAccount('acct-a')).resolves.toBe(true); + expect(h.current).toBe('acct-a'); + expect(h.runtimes.has('acct-a')).toBe(true); + }); + + // Breaks: an add that crashed before its registry row was written leaves + // its id as the persisted pointer; the next launch made that ghost the + // active account — and, on a legacy install, the owner of sarvinbox.db. + it('refuses an unconfigured id before the legacy adopt, leaving the pointer alone', async () => { + configure('acct-a'); + touch(PRIMARY_DB_FILE); + touch(dbFileForAccount('acct-ghost')); + await expect(activatePersistedAccount('acct-ghost')).resolves.toBe(false); + expect(loadPrimaryAccountId()).toBeNull(); + expect(h.current).toBeNull(); + expect(h.storages).toHaveLength(0); + }); + + // Breaks: a launch spins up a blank mailbox for an id whose data is not on disk. + it('defers when the account has no DB on disk yet', async () => { + configure('acct-a'); + await expect(activatePersistedAccount('acct-a')).resolves.toBe(false); + expect(h.current).toBeNull(); + expect(h.storages).toHaveLength(0); + }); + + // Breaks: a held account (a compaction that outlived the last session's + // window) left main pointing at an empty slot: every first IPC failed with + // "Storage not initialized". + it('does not move the pointer when the runtime cannot be opened', async () => { + configure('acct-a'); + touch(dbFileForAccount('acct-a')); + await quiesceAccountRuntime('acct-a', 'compact', { hold: true }); + try { + await expect(activatePersistedAccount('acct-a')).resolves.toBe(false); + } finally { + releaseAccountMaintenance('acct-a'); + } + expect(h.current).toBeNull(); + }); + + // Breaks: the legacy install's first account no longer claims sarvinbox.db. + it('lets the first configured account adopt the legacy DB, as accounts:setActive does', async () => { + configure('acct-a'); + touch(PRIMARY_DB_FILE); + await expect(activatePersistedAccount('acct-a')).resolves.toBe(true); + expect(loadPrimaryAccountId()).toBe('acct-a'); + expect(h.claimed).toEqual(['acct-a']); + expect(h.current).toBe('acct-a'); + }); + + // Breaks: an already-open account is re-opened (a second handle) at launch. + it('reuses an already-open runtime', async () => { + configure('acct-a'); + touch(dbFileForAccount('acct-a')); + h.runtimes.set('acct-a', { storage: { tag: 'open' }, syncEngine: {}, smtpClient: null }); + await expect(activatePersistedAccount('acct-a')).resolves.toBe(true); + expect(h.storages).toHaveLength(0); + }); + + // Breaks: an unreadable registry read as "not configured" (a quiet skip that + // hides the failure) — it surfaces to main.ts's catch, which logs it. + it('throws when the registry cannot be read', async () => { + h.registryThrows = true; + await expect(activatePersistedAccount('acct-a')).rejects.toThrow(/core DB unreadable/); + expect(h.current).toBeNull(); + }); +}); + /** * The exclusive-maintenance hold. * @@ -463,6 +651,9 @@ describe('ensureAccountRuntime', () => { * keep it closed; only the hold does. */ describe('exclusive maintenance holds', () => { + // Changed deliberately: only configured accounts are opened (see above). + beforeEach(() => configure('acct-a', 'acct-b')); + // The hold lives in module state, so a test that leaves one set would wedge // every test after it. Clear both ids whatever the test did. afterEach(() => { diff --git a/apps/desktop/test/unit/electron/services/attachment-cache-legacy.test.ts b/apps/desktop/test/unit/electron/services/attachment-cache-legacy.test.ts index 9249303d..e7c007e2 100644 --- a/apps/desktop/test/unit/electron/services/attachment-cache-legacy.test.ts +++ b/apps/desktop/test/unit/electron/services/attachment-cache-legacy.test.ts @@ -38,7 +38,7 @@ vi.mock('../../../../electron/services/db-key-store', () => ({ return 'k'.repeat(64); }, })); -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); vi.mock('../../../../electron/services/accounts-registry', () => ({ readRegistryAccounts: () => { if (h.registryThrows) throw new Error('addon failed to load'); diff --git a/apps/desktop/test/unit/electron/services/attachment-cache-store.test.ts b/apps/desktop/test/unit/electron/services/attachment-cache-store.test.ts index 21bbcf12..5570c2cf 100644 --- a/apps/desktop/test/unit/electron/services/attachment-cache-store.test.ts +++ b/apps/desktop/test/unit/electron/services/attachment-cache-store.test.ts @@ -51,7 +51,7 @@ vi.mock('../../../../electron/services/db-key-store', () => ({ })); // resolveAttachmentFile is not under test here; keep the account runtime (and // with it storage-node) out of this suite. -vi.mock('../../../../electron/services/account-target', () => ({ resolveAccountTarget: vi.fn() })); +vi.mock('../../../../electron/services/account-target', () => ({ resolveNamedOrActiveAccountTarget: vi.fn() })); vi.mock('@sarvinbox/core', async (importOriginal) => ({ ...(await importOriginal()), createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }), diff --git a/apps/desktop/test/unit/electron/services/attachment-protocol.test.ts b/apps/desktop/test/unit/electron/services/attachment-protocol.test.ts index 0d5bb424..70c4a999 100644 --- a/apps/desktop/test/unit/electron/services/attachment-protocol.test.ts +++ b/apps/desktop/test/unit/electron/services/attachment-protocol.test.ts @@ -74,7 +74,7 @@ vi.mock('../../../../electron/services/db-key-store', () => ({ getDbEncryptionKey: () => 'k'.repeat(64), })); vi.mock('../../../../electron/services/account-target', () => ({ - resolveAccountTarget: () => { + resolveNamedOrActiveAccountTarget: () => { throw new Error('the protocol suite resolves through h.resolve only'); }, })); diff --git a/apps/desktop/test/unit/electron/services/db-compact.test.ts b/apps/desktop/test/unit/electron/services/db-compact.test.ts index 86c70a70..513dde82 100644 --- a/apps/desktop/test/unit/electron/services/db-compact.test.ts +++ b/apps/desktop/test/unit/electron/services/db-compact.test.ts @@ -48,6 +48,14 @@ const h = vi.hoisted(() => ({ released: [] as string[], reopened: [] as string[], reopenThrows: false, + /** How many reopen attempts throw before one succeeds (0: none). */ + reopenFailures: 0, + /** What a reopen that does not throw answers (null: refused — removed or held). */ + reopenResult: null as unknown, + /** The active-account pointer (null: the pre-account slot). */ + current: 'other-account' as string | null, + pointedAt: [] as Array, + rebinds: 0, })); vi.mock('electron', () => ({ @@ -96,6 +104,9 @@ vi.mock('../../../../electron/services/accounts-runtime', () => ({ quiesceAccountRuntime: async (accountId: string, reason: string, options: { hold?: boolean } = {}) => { h.quiesced.push({ accountId, reason, hold: options.hold === true }); h.order.push('quiesce'); + // As production: unregistering the ACTIVE account's runtime drops the + // active pointer back to the pre-account slot. + if (h.current === accountId) h.current = null; }, releaseAccountMaintenance: (accountId: string) => { h.released.push(accountId); @@ -104,8 +115,9 @@ vi.mock('../../../../electron/services/accounts-runtime', () => ({ ensureAccountRuntime: async (accountId: string) => { h.order.push('reopen'); if (h.reopenThrows) throw new Error('reopen exploded'); + if (h.reopenFailures > 0) { h.reopenFailures -= 1; throw new Error('core DB is busy'); } h.reopened.push(accountId); - return null; + return h.reopenResult; }, })); @@ -113,7 +125,13 @@ vi.mock('../../../../electron/services/db-key-store', () => ({ getDbEncryptionKey: () => KEY, })); +vi.mock('../../../../electron/services/outbox-service', () => ({ + rebindOutboxStorage: () => { h.rebinds += 1; }, +})); + vi.mock('../../../../electron/shared', () => ({ + getCurrentAccountId: () => h.current, + setCurrentAccount: (accountId: string | null) => { h.current = accountId; h.pointedAt.push(accountId); }, getAccountRuntime: () => h.storageOpen ? { storage: { getPageStats: () => h.pageStats }, syncEngine: { isSyncing: () => h.syncing } } @@ -152,6 +170,11 @@ beforeEach(() => { h.released = []; h.reopened = []; h.reopenThrows = false; + h.reopenFailures = 0; + h.reopenResult = null; + h.current = 'other-account'; + h.pointedAt = []; + h.rebinds = 0; }); afterEach(() => { @@ -358,6 +381,32 @@ describe('compactAccountDatabase', () => { expect(compactionInProgress()).toBeNull(); }); + // Breaks (item 6): the reopen reads the account registry now, and one core-DB + // read error right after a minutes-long VACUUM left the mailbox closed until + // restart. The account was configured when the compaction began, so a THROW + // is retried. + it('retries a reopen that throws, until it succeeds', async () => { + h.reopenFailures = 2; + await compactAccountDatabase('acct-a'); + expect(h.order.filter((step) => step === 'reopen')).toHaveLength(3); + expect(h.reopened).toEqual(['acct-a']); + }); + + // Breaks: a reopen that keeps failing retries forever (Compress hangs). + it('gives up after a bounded number of attempts', async () => { + h.reopenThrows = true; + await compactAccountDatabase('acct-a'); + expect(h.order.filter((step) => step === 'reopen')).toHaveLength(3); + expect(h.reopened).toEqual([]); + }); + + // Breaks: a reopen that ANSWERED null (the account was removed meanwhile, or + // is held again) is hammered as if it were a transient failure. + it('does not retry a reopen that answered (null)', async () => { + await compactAccountDatabase('acct-a'); + expect(h.order.filter((step) => step === 'reopen')).toHaveLength(1); + }); + // Breaks: a worker started before the app's own handle is closed cannot get // the exclusive lock and the rebuild fails outright. it('quiesces the account BEFORE starting the worker', async () => { @@ -481,3 +530,64 @@ describe('compactAccountDatabase database targeting', () => { expect(JSON.stringify(error, Object.getOwnPropertyNames(error))).not.toContain(KEY); }); }); + +// Compacting the ACTIVE account: the quiesce unregisters its runtime, which +// drops main's active pointer to the pre-account slot, and nothing pointed it +// back — every later call failed "Storage not initialized" while the window +// still showed the mailbox, and a legacy primary (sarvinbox.db) never +// recovered (imap:connect only re-adopts a per-id database). +describe('compactAccountDatabase — the active account stays active', () => { + // Breaks: THE pre-existing bug above. + it('points main back at the compacted account once it is reopened, and rebinds its outbox', async () => { + h.current = 'acct-a'; + h.reopenResult = { storage: {} }; + await compactAccountDatabase('acct-a'); + expect(h.current).toBe('acct-a'); + expect(h.pointedAt).toEqual(['acct-a']); + expect(h.rebinds).toBe(1); + }); + + // Breaks: the same, when the reopen needed a retry. + it('restores the pointer after a retried reopen', async () => { + h.current = 'acct-a'; + h.reopenFailures = 1; + h.reopenResult = { storage: {} }; + await compactAccountDatabase('acct-a'); + expect(h.current).toBe('acct-a'); + }); + + // Breaks: a background account's compaction yanks the active account away. + it('leaves the active pointer alone when a background account was compacted', async () => { + h.current = 'other-account'; + h.reopenResult = { storage: {} }; + await compactAccountDatabase('acct-a'); + expect(h.current).toBe('other-account'); + expect(h.pointedAt).toEqual([]); + }); + + // Breaks: the user switched to another account during a long rebuild, and the + // reopen switched them back. + it('does not override a switch the user made meanwhile', async () => { + h.current = 'acct-a'; + h.reopenResult = { storage: {} }; + let release!: () => void; + h.gate = new Promise((resolve) => { release = resolve; }); + const running = compactAccountDatabase('acct-a'); + await new Promise((resolve) => setTimeout(resolve, 0)); + h.current = 'acct-b'; // accounts:setActive('acct-b') while the worker runs + release(); + await running; + expect(h.current).toBe('acct-b'); + expect(h.pointedAt).toEqual([]); + }); + + // Breaks: an account that could not be reopened (removed meanwhile) becomes + // the active pointer — an active slot with no database behind it. + it('does not point at an account that could not be reopened', async () => { + h.current = 'acct-a'; + h.reopenResult = null; + await compactAccountDatabase('acct-a'); + expect(h.current).toBeNull(); + expect(h.pointedAt).toEqual([]); + }); +}); diff --git a/apps/desktop/test/unit/src/components/ThreadSummary.account.test.tsx b/apps/desktop/test/unit/src/components/ThreadSummary.account.test.tsx new file mode 100644 index 00000000..6bd481e6 --- /dev/null +++ b/apps/desktop/test/unit/src/components/ThreadSummary.account.test.tsx @@ -0,0 +1,89 @@ +// @vitest-environment happy-dom +import { act } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// What breaks if this file fails: a thread summary is read from, or cached +// into, the wrong account. The cache is keyed by thread id, which every +// account that received the conversation shares; All Inboxes shows other +// accounts' threads. The component used to send only the thread id, so main +// always used the ACTIVE account — showing its summary on another account's +// thread, and storing another account's summary in it. + +vi.mock('../../../../src/services/ai-service', () => ({ + generateThreadSummary: vi.fn(async () => ({ summary: 'S', keyPoints: ['k'], participants: ['p'], confidence: 0.9 })), + isThreadSummariesEnabled: () => true, + getDefaultProvider: () => ({ model: 'test-model' }), + getCurrentUserEmail: () => '', +})); +vi.mock('../../../../src/components/email-detail/chat-message-adapter', () => ({ + chatMessagesFromThread: () => [], + toEpochSeconds: (value: number) => value, +})); + +import { ThreadSummary } from '../../../../src/components/ThreadSummary'; +import { cleanup, render } from '../../../helpers/render'; + +const getThreadSummary = vi.fn(); +const saveThreadSummary = vi.fn(); +const emails = [ + { id: 'e1', subject: 'S', fromAddress: 'a@x.test', toAddress: 'b@x.test', date: 1, cleanBody: 'one' }, + { id: 'e2', subject: 'S', fromAddress: 'b@x.test', toAddress: 'a@x.test', date: 2, cleanBody: 'two' }, +] as never[]; + +const settle = () => act(async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); }); + +beforeEach(() => { + getThreadSummary.mockReset().mockResolvedValue({ success: true, data: null }); + saveThreadSummary.mockReset().mockResolvedValue({ success: true }); + (window as unknown as { electronAPI: unknown }).electronAPI = { + ai: { getThreadSummary, saveThreadSummary }, + extensions: { invoke: vi.fn(async () => ({ success: true, data: { served: false } })) }, + }; + vi.spyOn(console, 'log').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('ThreadSummary — the owning account', () => { + // Breaks: the cached summary of a non-active account's thread is looked up + // in the active account's cache (the same thread id lives in both). + it("reads the cache from the thread's own account", async () => { + render(); + await settle(); + expect(getThreadSummary).toHaveBeenCalledExactlyOnceWith('t-shared', 'acct-b'); + }); + + // Breaks: a summary generated for account B's thread is stored in the + // active account's cache. + it("caches a generated summary in the thread's own account", async () => { + const view = render(); + await settle(); + const button = [...view.container.querySelectorAll('button')].find((b) => b.textContent?.includes('Summarize')); + await act(async () => { button!.click(); }); + await settle(); + expect(saveThreadSummary).toHaveBeenCalledOnce(); + expect(saveThreadSummary.mock.calls[0][0]).toMatchObject({ threadId: 't-shared', summary: 'S', emailCount: 2 }); + expect(saveThreadSummary.mock.calls[0][1]).toBe('acct-b'); + }); + + // Breaks: switching to the same thread id in ANOTHER account keeps showing + // the first account's cached summary (the effect did not re-run). + it('reloads the cache when the owning account changes', async () => { + const view = render(); + await settle(); + view.rerender(); + await settle(); + expect(getThreadSummary.mock.calls).toEqual([['t-shared', 'acct-a'], ['t-shared', 'acct-b']]); + }); + + // Breaks: the single-account path — no account known means the active one, + // which main resolves when no id is sent. + it('sends no account when none is known', async () => { + render(); + await settle(); + expect(getThreadSummary).toHaveBeenCalledExactlyOnceWith('t-shared', undefined); + }); +}); diff --git a/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx b/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx index eefe8b1f..c95a9ae3 100644 --- a/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx +++ b/apps/desktop/test/unit/src/components/onboarding/EmailSetupStep.test.tsx @@ -511,6 +511,28 @@ describe('connected mailbox safety', () => { expect(state.accounts).toHaveLength(1); }); + // Breaks: "Retry receiving" after a REFUSED switch connected the saved + // account's sign-in while another mailbox was active in main — its mail + // synced into that mailbox's database. + it('never connects a saved account whose switch was refused', async () => { + localStorage.setItem('sarvinbox-onboarding-pending', 'true'); + state.accounts = [{ id: 'saved-mail', email: 'saved@example.com', imapConfig: { + host: 'imap.sarv.com', port: 993, secure: true, authMethod: 'oauth2', oauthProvider: 'sarv', password: '', + }, smtpConfig: null, smtpConfigured: true }]; + state.activeAccountId = 'saved-mail'; state.connected = false; + saveOnboardingEmailProgress('saved-mail', true); + connect.mockRejectedValueOnce(new Error('Network offline')); + const view = render(); + await settle(); + fire(button(view, 'Retry receiving connection'), 'click'); await settle(); + connect.mockClear(); + state.activeAccountId = 'another-account'; + selectAccount.mockImplementationOnce(async () => false); // refused: nothing switched + fire(button(view, 'Retry receiving connection'), 'click'); await settle(); + expect(connect).not.toHaveBeenCalled(); + expect(view.container.textContent).toContain('could not be opened right now'); + }); + // Regression: derived OAuth SMTP configuration must not be treated as a // successful sending verification after an interrupted first-run check. it('resumes sending as pending when no successful sending progress was saved', async () => { @@ -617,6 +639,19 @@ describe('connected mailbox safety', () => { expect(addAccount).toHaveBeenCalledOnce(); }); + // Breaks: main REFUSED the switch (selectAccount resolved without switching), + // and the wizard completed with another mailbox still active — its next + // steps then ran against that mailbox. + it('does not continue when the switch to the saved account was refused', async () => { + const view = render(); await choose(view, 'Yahoo'); enterManual(view); submit(view); await settle(); + state.activeAccountId = 'another-account'; onConnected.mockClear(); + selectAccount.mockImplementationOnce(async () => false); // refused: nothing switched + fire(button(view, 'Continue'), 'click'); await settle(); + expect(view.container.textContent).toContain('could not be opened right now'); + expect(onConnected).not.toHaveBeenCalled(); + expect(state.activeAccountId).toBe('another-account'); + }); + // Regression: a new active account must not inherit a stale SMTP result from another account. it('rejects a sending result after the active account changes mid-check', async () => { const pending = deferred(); connectSmtp.mockReturnValueOnce(pending.promise); diff --git a/apps/desktop/test/unit/src/store/slices/connection-account-activation.test.ts b/apps/desktop/test/unit/src/store/slices/connection-account-activation.test.ts new file mode 100644 index 00000000..7b5780ba --- /dev/null +++ b/apps/desktop/test/unit/src/store/slices/connection-account-activation.test.ts @@ -0,0 +1,271 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { account, loadConnectionSlice, teardownStoreEnv } from './connection-slice-harness'; + +// What breaks if this file fails: the renderer and main disagree about which +// mailbox is active. Main now REFUSES to activate an account its registry does +// not list (`{ success: false }`, main stays where it was), except while that +// account is being added. A renderer that carried on after a refusal would +// show — and act on — the previous account's mailbox under the selected +// account's name, or, mid-add, connect the NEW account's credentials on the +// PREVIOUS account's engine and sync its mail into that database. + +beforeEach(() => { vi.useFakeTimers(); vi.spyOn(console, 'log').mockImplementation(() => {}); }); +afterEach(() => { vi.runOnlyPendingTimers(); vi.useRealTimers(); teardownStoreEnv(); vi.restoreAllMocks(); }); + +const config = { username: 'new@example.com', host: 'imap.example.com', port: 993, secure: true, password: 'secret' }; + +describe('addAccount — the one activation allowed for an unlisted account', () => { + const addApi = (setActive: ReturnType) => ({ + imap: { + probeCredentials: vi.fn(async () => ({ success: true })), + connect: vi.fn(async () => ({ success: true })), + removeSyncProgressListener: vi.fn(), + onSyncProgress: vi.fn(), + }, + accounts: { setActive }, + secureCreds: { set: vi.fn(async () => ({ success: true })), get: vi.fn(async () => ({ success: true, data: null })) }, + }); + + // Breaks: adding an account — main refuses the new id (it is not in the + // registry until this add's connect succeeds) unless the add says so. + it('asks main to activate the new account as one being added, then connects it', async () => { + const setActive = vi.fn(async () => ({ success: true })); + const api = addApi(setActive); + const { state } = await loadConnectionSlice({ + loadFolders: vi.fn(async () => {}), syncEmails: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), + }, api); + + await state.addAccount(config); + + expect(setActive).toHaveBeenCalledExactlyOnceWith(state.accounts[0].id, { adding: true }); + expect(api.imap.connect).toHaveBeenCalledOnce(); + expect(state.activeAccountId).toBe(state.accounts[0].id); + }); + + // Breaks: main refused (its registry is unreadable), main is still on the + // previous account, and the add went on to connect the new account's + // credentials on THAT account's engine — its mail synced into the wrong + // database. Nothing durable had changed yet, so the add must stop cleanly. + it('stops before connecting when main refuses, leaving the previous account as it was', async () => { + const setActive = vi.fn(async () => ({ success: false, error: 'addon failed to load' })); + const api = addApi(setActive); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-old')], activeAccountId: 'acct-old', connected: true, + loadFolders: vi.fn(async () => {}), syncEmails: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), + }, api); + + await expect(state.addAccount(config)).rejects.toThrow('addon failed to load'); + + expect(api.imap.connect).not.toHaveBeenCalled(); + expect(api.secureCreds.set).not.toHaveBeenCalled(); + expect(state.activeAccountId).toBe('acct-old'); + expect(state.connected).toBe(true); + expect(state.accounts.map((a: { id: string }) => a.id)).toEqual(['acct-old']); + expect(localStorage.getItem('sarvinbox-active-account')).toBeNull(); + }); + + // Breaks: a refusal with no message reaches the user as "undefined". + it('explains a refusal that carries no message', async () => { + const api = addApi(vi.fn(async () => ({ success: false }))); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ loadLabels: vi.fn(async () => {}) }, api); + await expect(state.addAccount(config)).rejects.toThrow(/Could not prepare the new account/); + expect(api.imap.connect).not.toHaveBeenCalled(); + }); +}); + +describe('selectAccount — a refused switch does not happen', () => { + const stubs = () => ({ + loadFolders: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), loadQuota: vi.fn(), + startIdle: vi.fn(async () => {}), syncSingleFolder: vi.fn(async () => {}), + }); + + // Breaks: main refused the switch (the account is not in its registry) and + // stayed on acct-a, but the renderer switched anyway — showing acct-a's + // folders and mail under acct-b's name, and acting on acct-a's database. + it('stays on the current account when main refuses', async () => { + const api = { + accounts: { setActive: vi.fn(async () => ({ success: false, error: 'That account is not configured.' })) }, + imap: { isConnected: vi.fn(async () => ({ success: true, data: true })), connect: vi.fn() }, + }; + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + await state.selectAccount('acct-b'); + + expect(api.accounts.setActive).toHaveBeenCalledExactlyOnceWith('acct-b'); + expect(state.activeAccountId).toBe('acct-a'); + expect(state.loadFolders).not.toHaveBeenCalled(); + expect(api.imap.connect).not.toHaveBeenCalled(); + expect(localStorage.getItem('sarvinbox-active-account')).toBeNull(); + }); + + // Breaks: an ordinary switch to a configured account. + it('switches when main accepts', async () => { + const api = { + accounts: { setActive: vi.fn(async () => ({ success: true })) }, + imap: { isConnected: vi.fn(async () => ({ success: true, data: true })) }, + }; + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + await state.selectAccount('acct-b'); + + expect(state.activeAccountId).toBe('acct-b'); + expect(state.loadFolders).toHaveBeenCalledOnce(); + }); +}); + +describe('selectAccount — says whether it switched', () => { + const stubs = () => ({ + loadFolders: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), loadQuota: vi.fn(), + startIdle: vi.fn(async () => {}), syncSingleFolder: vi.fn(async () => {}), + }); + + // Breaks: callers that must not go on after a refused switch (removal's + // fallback, onboarding's retries) cannot tell a switch from a refusal. + it('resolves true on a switch or for the already-active account, false on a refusal or an unknown account', async () => { + const setActive = vi.fn(async (id: string) => ({ success: id !== 'acct-refused' })); + const api = { accounts: { setActive }, imap: { isConnected: vi.fn(async () => ({ success: true, data: true })) } }; + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b'), account('acct-refused')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + await expect(state.selectAccount('acct-a')).resolves.toBe(true); + await expect(state.selectAccount('acct-refused')).resolves.toBe(false); + await expect(state.selectAccount('acct-unknown')).resolves.toBe(false); + await expect(state.selectAccount('acct-b')).resolves.toBe(true); + expect(state.activeAccountId).toBe('acct-b'); + }); +}); + +describe('addAccount — the rollback checks that main went back', () => { + const addApi = (rollback: () => Promise) => ({ + imap: { + probeCredentials: vi.fn(async () => ({ success: true })), + connect: vi.fn(async () => ({ success: false, error: 'IMAP connect timed out' })), + removeSyncProgressListener: vi.fn(), + onSyncProgress: vi.fn(), + }, + accounts: { + setActive: vi.fn(async (_id: string, options?: { adding?: boolean }) => (options?.adding ? { success: true } : rollback())), + }, + secureCreds: { set: vi.fn(async () => ({ success: true })), get: vi.fn(async () => ({ success: true, data: null })) }, + }); + + // Breaks: an add whose connect failed shows the previous account again while + // main is back on it — the ordinary rollback. + it('puts the previous account back when main returns to it', async () => { + const api = addApi(async () => ({ success: true })); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-old')], activeAccountId: 'acct-old', connected: true, loadLabels: vi.fn(async () => {}), + }, api); + + await expect(state.addAccount(config)).rejects.toThrow('IMAP connect timed out'); + expect(api.accounts.setActive).toHaveBeenLastCalledWith('acct-old'); + expect(state.activeAccountId).toBe('acct-old'); + expect(state.connected).toBe(true); + }); + + // Breaks: the rollback's refusal was ignored — the window showed the previous + // account while main stayed on the half-added one, and the previous + // account's actions went into the new account's database. + it('shows no account active when main refuses to go back, keeping the previous one saved', async () => { + const api = addApi(async () => ({ success: false, error: 'addon failed to load' })); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-old')], activeAccountId: 'acct-old', connected: true, loadLabels: vi.fn(async () => {}), + }, api); + + await expect(state.addAccount(config)).rejects.toThrow('IMAP connect timed out'); + expect(state.activeAccountId).toBeNull(); + expect(state.connected).toBe(false); + // The previous account stays the saved one: the next launch (or a click in + // the switcher) reopens it. + expect(localStorage.getItem('sarvinbox-active-account')).toBe('acct-old'); + }); +}); + +describe('removeAccountById — a refused switch never leaves the deleted account active', () => { + const removalApi = (setActive: (id: string) => Promise) => ({ + imap: { disconnect: vi.fn(async () => {}), isConnected: vi.fn(async () => ({ success: true, data: true })) }, + smtp: { disconnect: vi.fn(async () => {}) }, + accounts: { remove: vi.fn(async () => ({ success: true })), setActive: vi.fn(setActive), save: vi.fn() }, + secureCreds: { delete: vi.fn(async () => {}) }, + }); + const stubs = () => ({ + loadFolders: vi.fn(async () => {}), loadLabels: vi.fn(async () => {}), loadQuota: vi.fn(), + startIdle: vi.fn(async () => {}), syncSingleFolder: vi.fn(async () => {}), + }); + + // Breaks (review item 2): the switch to the next account was refused, and + // activeAccountId stayed on the DELETED account with its mail on screen — + // nothing recovered from that. + it('tries the next remaining account when the first refuses', async () => { + const api = removalApi(async (id) => ({ success: id !== 'acct-b' })); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b'), account('acct-c')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + await state.removeAccountById('acct-a'); + + expect(api.accounts.setActive.mock.calls.map(([id]) => id)).toEqual(['acct-b', 'acct-c']); + expect(state.activeAccountId).toBe('acct-c'); + expect(state.accounts.map((a: { id: string }) => a.id)).toEqual(['acct-b', 'acct-c']); + }); + + // Breaks: with every remaining account refused, the deleted account stayed + // active. Main is on its pre-account slot (the removal closed the account), + // so the window shows no account either. + it('shows no account when every remaining account refuses', async () => { + const api = removalApi(async () => ({ success: false, error: 'addon failed to load' })); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + await state.removeAccountById('acct-a'); + + expect(state.activeAccountId).toBeNull(); + expect(state.folders).toEqual([]); + expect(state.emails).toEqual([]); + expect(state.accounts.map((a: { id: string }) => a.id)).toEqual(['acct-b']); + }); + + // Breaks (review item 3): while main waits on the removal (the OAuth + // revocation), a snapshot mirrored by any other change wrote the removed + // account's registry row straight back. + it('keeps the account being removed out of the registry mirror, and lets a kept one back', async () => { + let finishRemoval!: (value: unknown) => void; + const api = removalApi(async () => ({ success: true })); + api.accounts.remove = vi.fn(() => new Promise((resolve) => { finishRemoval = resolve; })) as never; + const { state } = await loadConnectionSlice({ + accounts: [account('acct-a'), account('acct-b')], activeAccountId: 'acct-a', ...stubs(), + }, api); + + // The slice's own helpers instance (loadConnectionSlice re-imports modules). + const { saveAccounts } = await import('../../../../../src/store/helpers'); + const removal = state.removeAccountById('acct-b'); + await vi.waitFor(() => expect(api.accounts.remove).toHaveBeenCalled()); + // A reconnect or a sending-setup change mirrors the whole list meanwhile. + saveAccounts(state.accounts); + expect(api.accounts.save.mock.lastCall![0].map((a: { id: string }) => a.id)).toEqual(['acct-a']); + // localStorage still holds it: a failed removal must keep its row. + expect(JSON.parse(localStorage.getItem('sarvinbox-accounts')!).map((a: { id: string }) => a.id)).toEqual(['acct-a', 'acct-b']); + + finishRemoval({ success: false, error: 'vault locked' }); + await expect(removal).rejects.toThrow('vault locked'); + saveAccounts(state.accounts); + expect(api.accounts.save.mock.lastCall![0].map((a: { id: string }) => a.id)).toEqual(['acct-a', 'acct-b']); + }); +}); diff --git a/apps/desktop/test/unit/src/store/slices/connection-remove-account.test.ts b/apps/desktop/test/unit/src/store/slices/connection-remove-account.test.ts index 4beea093..33df0a40 100644 --- a/apps/desktop/test/unit/src/store/slices/connection-remove-account.test.ts +++ b/apps/desktop/test/unit/src/store/slices/connection-remove-account.test.ts @@ -27,7 +27,10 @@ const loadSlice = async (initial: Record, electronAPI: any) => { if (providers) localStorage.setItem(AI_SETTINGS_KEY, JSON.stringify({ providers })); }, }); - state.selectAccount = vi.fn().mockResolvedValue(undefined); + // Changed deliberately: selectAccount now resolves whether the switch + // happened, and removal tries the next account when it did not — so the stub + // answers "switched", as the real one does when main accepts. + state.selectAccount = vi.fn().mockResolvedValue(true); return { state }; }; diff --git a/packages/core/src/extensions/panel-bridge.ts b/packages/core/src/extensions/panel-bridge.ts index 98f278ec..999804f1 100644 --- a/packages/core/src/extensions/panel-bridge.ts +++ b/packages/core/src/extensions/panel-bridge.ts @@ -110,9 +110,17 @@ const PANEL_REQUEST_PERMISSIONS: Readonly< 'panel.resize': null, }; -/** Whether `method` is one the bridge knows at all. */ +/** + * Whether `method` is one the bridge knows at all. + * + * An OWN key of the table, never `in`: `in` also walks the prototype, so + * `constructor`, `toString` or `__proto__` read as known methods, and the + * "permission" looked up for them was a function or an object. That was + * refused only because no grant set contains such a value — closed by + * accident. (`Object.hasOwn` is ES2022; the build targets ES2020.) + */ export function isPanelRequestMethod(value: unknown): value is PanelRequestMethod { - return typeof value === 'string' && value in PANEL_REQUEST_PERMISSIONS; + return typeof value === 'string' && Object.prototype.hasOwnProperty.call(PANEL_REQUEST_PERMISSIONS, value); } /** diff --git a/packages/core/test/unit/extensions/extension-hooks.test.ts b/packages/core/test/unit/extensions/extension-hooks.test.ts index c4f49a25..6fec4ef0 100644 --- a/packages/core/test/unit/extensions/extension-hooks.test.ts +++ b/packages/core/test/unit/extensions/extension-hooks.test.ts @@ -23,7 +23,7 @@ import type { ExtensionUIBackend, } from '../../../src/extensions/extension-api'; import { validateManifest } from '../../../src/extensions/extension-loader'; -import { panelRequestPermission } from '../../../src/extensions/panel-bridge'; +import { isPanelRequestMethod, PANEL_BRIDGE_CHANNEL, panelRequestPermission, parsePanelRequest } from '../../../src/extensions/panel-bridge'; import type { ExtensionManifest, ExtensionPermission, @@ -416,4 +416,26 @@ describe('panel mail methods', () => { it('returns undefined for a method with no entry', () => { expect(panelRequestPermission('mail.expunge' as never)).toBeUndefined(); }); + + // Regression (CASA 3.1.3, F5): the table was searched with `in`, which walks + // the prototype, so a panel naming `constructor`, `toString` or `__proto__` + // passed as a KNOWN method and its "permission" was a function or an object. + // It was refused only because no grant set holds such a value — closed by + // accident. Only the table's own keys are methods. + it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty', 'valueOf', 'isPrototypeOf', 'toLocaleString'])( + 'treats the inherited key %s as unknown, everywhere a method is checked', + (method) => { + expect(isPanelRequestMethod(method)).toBe(false); + expect(panelRequestPermission(method as never)).toBeUndefined(); + expect(parsePanelRequest({ channel: PANEL_BRIDGE_CHANNEL, requestId: 'r1', method })).toBeUndefined(); + }, + ); + + // The fix must not lose a real method: every listed one still parses. + it('still knows every real method', () => { + expect(isPanelRequestMethod('mail.get')).toBe(true); + expect(isPanelRequestMethod('panel.close')).toBe(true); + expect(parsePanelRequest({ channel: PANEL_BRIDGE_CHANNEL, requestId: 'r1', method: 'storage.get' })?.method).toBe('storage.get'); + expect(isPanelRequestMethod(42)).toBe(false); + }); }); From e36db8e52069340cab211d720d8319acfb01a934 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Thu, 3 Dec 2026 13:59:43 +0530 Subject: [PATCH 10/13] fix(agent): count the emails Inbox Agent sorted as reviewed The coverage line under an answer counted only emails opened with read_message or returned by deep search. A run that sorted all 389 unread emails with classify_messages (and staged changes to 102 of them) said "0 of 389 matching messages reviewed". Each email a classify_messages batch returned a verdict for now counts as reviewed in its own account, once per run: a registry set shared with read_message and deep search keeps sorting, re-sorting and reading the same email from counting it twice. An email in a batch the provider did not answer for is not counted. --- CHANGELOG.md | 6 ++ .../services/inbox-assistant-agent-tools.ts | 26 ++++++++- .../inbox-assistant-agent-tools.test.ts | 56 +++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a4a522d..5bf62557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Needs Response. It now shows in all of them, on every page of a tab, as does the star of a conversation starred on another copy. A draft kept in your provider's own Drafts folder (for example `INBOX.Drafts`) now counts too. +- **Inbox Agent's "reviewed" count includes the emails it sorted.** After + sorting every email that matched a request, such as all your unread mail, + the coverage line under the answer still said "0 of 389 matching messages + reviewed", because it counted only the emails the agent opened in full. Each + email the agent sorted now counts, once. An email it could not sort, because + the AI provider did not answer for its batch, still does not. ## [1.5.0] - 2026-11-25 diff --git a/apps/desktop/electron/services/inbox-assistant-agent-tools.ts b/apps/desktop/electron/services/inbox-assistant-agent-tools.ts index f98209a6..991e8580 100644 --- a/apps/desktop/electron/services/inbox-assistant-agent-tools.ts +++ b/apps/desktop/electron/services/inbox-assistant-agent-tools.ts @@ -59,6 +59,12 @@ export class InboxAgentRegistry { private resultCount = 0; /** Messages whose body (not just a list row) was read. */ readonly bodiesRead = new Set(); + /** + * Messages already counted in their account's "reviewed" total: read in + * full, sorted from an excerpt by classify_messages, or returned by deep + * search. Each counts once, however many tools looked at it. + */ + readonly reviewed = new Set(); /** The id for one email or attachment, created on first sight. Undefined once the run holds the maximum. */ source(key: string, create: () => Omit): string | undefined { @@ -264,6 +270,15 @@ export async function openAccount(context: InboxAgentToolContext, account: Inbox } } +/** Count one email as reviewed in its account's coverage, once per run. */ +function countReviewed(context: InboxAgentToolContext, source: Pick): void { + if (context.registry.reviewed.has(source.id)) return; + const account = context.accounts.find(item => item.id === source.accountId); + if (!account) return; + context.registry.reviewed.add(source.id); + coverageFor(context, account).reviewedMessages++; +} + export function coverageFor(context: Pick, account: InboxAssistantAccount): InboxAssistantAccountCoverage { let coverage = context.coverage.get(account.id); if (!coverage) { @@ -641,9 +656,9 @@ const readMessage: InboxAgentTool = { } if (!context.registry.bodiesRead.has(source.id)) { context.registry.bodiesRead.add(source.id); - coverage.reviewedMessages++; if (!body || unavailable) coverage.missingBodies++; } + countReviewed(context, source); const declared = await opened.mailbox.storage.getAttachments(email.id); const names = attachmentNames(email, declared); const header = `CC: ${addresses(email.ccAddress).join(', ')}\n`; @@ -777,7 +792,11 @@ const deepSearch: InboxAgentTool = { const block = inboxAssistantEvidenceText({ ...item, id }); if (used + block.length > INBOX_AGENT_LIMITS.deepSearchChars) break; used += block.length; - if (item.kind === 'message') context.registry.bodiesRead.add(id); + // Already in the coverage merged above: marked so no later tool counts it again. + if (item.kind === 'message') { + context.registry.bodiesRead.add(id); + context.registry.reviewed.add(id); + } context.registry.update(id, { text: item.text }); context.registry.show(id, block); blocks.push(block); @@ -859,6 +878,9 @@ const classifyMessages: InboxAgentTool = { for (let index = 0; index < batches.length; index += INBOX_AGENT_LIMITS.classifyParallel) { await Promise.all(batches.slice(index, index + INBOX_AGENT_LIMITS.classifyParallel).map(runBatch)); } + // An email the model judged was reviewed (from its excerpt), and the + // footer's "N of M reviewed" says so. One in a batch that failed was not. + for (const source of sources as InboxAssistantEvidence[]) if (verdicts.has(source.id)) countReviewed(context, source); const counts = new Map(labels.map(label => [label, 0])); const lines = ids.map(id => { const verdict = verdicts.get(id) ?? { label: UNSURE, reason: 'not classified' }; diff --git a/apps/desktop/test/unit/electron/services/inbox-assistant-agent-tools.test.ts b/apps/desktop/test/unit/electron/services/inbox-assistant-agent-tools.test.ts index ff513457..c1a356ab 100644 --- a/apps/desktop/test/unit/electron/services/inbox-assistant-agent-tools.test.ts +++ b/apps/desktop/test/unit/electron/services/inbox-assistant-agent-tools.test.ts @@ -433,6 +433,62 @@ describe('sorting emails', () => { expect(ctx.progress).toHaveBeenCalledWith(expect.objectContaining({ message: 'Sorting 1 email' })); }); + /** A classifier that labels every email in the prompt "no". */ + const labelAll = vi.fn(async (prompt: string) => JSON.stringify({ results: [...prompt.matchAll(/"id":"(S\d+)"/g)].map(match => ({ id: match[1], label: 'no' })) })); + + // Breaks: the answer's footer says "0 of 389 matching messages reviewed" + // after the agent sorted every one of them (it counted only emails opened + // with read_message). Sorting, re-sorting and then reading an email counts + // it once. + it('counts each sorted email as reviewed, once', async () => { + const { ctx, list } = await ids(3); + ctx.classify = labelAll; + await tool('classify_messages').run({ ids: list, question: 'Business?', labels: ['yes', 'no'] }, ctx); + expect(ctx.coverage.get('primary')).toMatchObject({ matchedMessages: 3, reviewedMessages: 3 }); + await tool('classify_messages').run({ ids: list, question: 'Newsletter?', labels: ['yes', 'no'] }, ctx); + await tool('read_message').run({ id: list[1] }, ctx); + expect(ctx.coverage.get('primary')).toMatchObject({ reviewedMessages: 3, missingBodies: 0 }); + expect(ctx.registry.bodiesRead).toEqual(new Set([list[1]])); + }); + + // Breaks: emails in a batch the AI could not sort (a timeout, a rate limit) + // are reported as reviewed, so the footer hides that they were not. + it('does not count emails in a batch that failed', async () => { + const { ctx, list } = await ids(12); + ctx.classify = vi.fn(async (prompt: string) => { + // The batch holding the first email (the prompt's format example also says "S1"). + if (prompt.includes(`"id":"${list[0]}","text"`)) throw new Error('timeout'); + return labelAll(prompt); + }); + const output = await tool('classify_messages').run({ ids: list, question: 'Business?', labels: ['yes', 'no'] }, ctx); + expect(output).toContain('1 of 2 batches could not be sorted'); + expect(ctx.coverage.get('primary')?.reviewedMessages).toBe(2); + }); + + // Breaks: one account's sorted mail is added to another account's footer line. + it('counts sorted emails under their own account (multi-account)', async () => { + await mail('p1'); + await mail('s1', {}, 'secondary'); + await mail('s2', {}, 'secondary'); + const ctx = context({ classify: labelAll }); + const output = await tool('search_mail').run({ limit: 50 }, ctx); + const list = [...output.matchAll(/^(S\d+) \|/gm)].map(match => match[1]!); + await tool('classify_messages').run({ ids: list, question: 'Business?', labels: ['yes', 'no'] }, ctx); + expect([ctx.coverage.get('primary')?.reviewedMessages, ctx.coverage.get('secondary')?.reviewedMessages]).toEqual([1, 2]); + }); + + // Breaks: an email deep search already reviewed (and counted) is counted + // again when it is sorted, so "reviewed" can exceed what was looked at. + it('does not count again an email deep search reviewed', async () => { + const ctx = context({ classify: labelAll, deepSearch: vi.fn(async () => ({ + evidence: [evidence({ emailId: 'm1', text: 'Quote' })], + coverage: [{ accountId: 'primary', email: 'rc@sarv.example', status: 'searched' as const, matchedMessages: 1, reviewedMessages: 1, missingBodies: 0, attachmentsRead: 0, attachmentsSkipped: 0, truncated: false, warnings: [] }], + })) }); + await tool('deep_search').run({ question: 'q' }, ctx); + await tool('classify_messages').run({ ids: ['S1'], question: 'Business?', labels: ['yes', 'no'] }, ctx); + expect(ctx.coverage.get('primary')?.reviewedMessages).toBe(1); + }); + // Breaks: Stop during sorting is swallowed as a failed batch and the run keeps going. it('stops when the run is stopped', async () => { const { list } = await ids(1); From 9e89ddbbd3c375e8e018c766381818ada92a1dec Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Thu, 3 Dec 2026 13:59:56 +0530 Subject: [PATCH 11/13] feat(filters): create a label from a filter's "Apply label" action MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "Apply label" dropdown ends with "+ Create new label…", and with no labels yet a "Create new label" button replaces the pointer to Settings → Labels. Either opens the shared NewLabelDialog and picks the created label for the row that asked for it. Cancelling, or a create the store refuses, leaves the row as it was; the dropdown's entry is never saved as a value. --- CHANGELOG.md | 4 + .../src/components/settings/FiltersTab.tsx | 21 ++- .../settings/FiltersTab.new-label.test.tsx | 140 ++++++++++++++++++ 3 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 apps/desktop/test/unit/src/components/settings/FiltersTab.new-label.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a4a522d..0e988b20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 one made with "Filter messages like this", and can be unticked. Filters you already have are unchanged until you tick it. A filter can do only this, and Inbox Agent can set it up when you ask. +- **Make a label without leaving a filter.** A filter's "Apply label" action + now offers **Create new label**, which opens the New label window and picks + the label you make, so you no longer have to go to Settings → Labels and come + back. ### Fixed - **macOS no longer asks to let "Electron" find devices on your local diff --git a/apps/desktop/src/components/settings/FiltersTab.tsx b/apps/desktop/src/components/settings/FiltersTab.tsx index 4c49d612..6f135d24 100644 --- a/apps/desktop/src/components/settings/FiltersTab.tsx +++ b/apps/desktop/src/components/settings/FiltersTab.tsx @@ -5,6 +5,7 @@ import { useState, useEffect } from 'react'; import { useEmailStore } from '../../store/email-store'; import { consumePendingFilterDraft } from '../../utils/filter-draft-bridge'; import { useConfirm } from '../ConfirmDialog'; +import { NewLabelDialog } from '../NewLabelDialog'; import { Tooltip } from '../Tooltip'; import { BlockedSendersPanel } from './BlockedSendersPanel'; @@ -21,6 +22,9 @@ const ACTION_LABELS: Record = { skipAI: 'Skip AI checks', }; /** The actions offered in the "Then" rows. "Skip AI checks" is its own tickbox. */ +/** The "Apply label" dropdown's entry that opens the New label dialog; never saved. */ +const NEW_LABEL_OPTION = '__new_label__'; + const ROW_ACTION_TYPES = (Object.keys(ACTION_LABELS) as FilterActionType[]).filter(t => t !== 'skipAI'); const emptyCondition = (): FilterCondition => ({ field: 'from', operator: 'contains', value: '' }); @@ -67,6 +71,8 @@ export function FiltersTab() { const [rules, setRules] = useState([]); const [loading, setLoading] = useState(false); const [draft, setDraft] = useState(null); + /** The action row whose "Apply label" is creating a label, or null. */ + const [newLabelFor, setNewLabelFor] = useState(null); const [saving, setSaving] = useState(false); const [dragIndex, setDragIndex] = useState(null); const [notice, setNotice] = useState(null); @@ -218,6 +224,12 @@ export function FiltersTab() { return (
{confirmDialog} + {newLabelFor !== null && ( + // The new label is picked for the row that asked for it, so the user + // does not have to leave the filter to make one and come back. + setNewLabelFor(null)} + onCreated={(name) => patchAction(newLabelFor, { value: name })} /> + )} {/* Sub-tabs: Filters | Blocked (nested inside the one Settings tab) */}
{([['filters', 'Filters'], ['blocked', 'Blocked']] as const).map(([id, label]) => ( @@ -351,13 +363,18 @@ export function FiltersTab() { )} {a.type === 'applyLabel' && ( labels.length > 0 ? ( - (e.target.value === NEW_LABEL_OPTION ? setNewLabelFor(i) : patchAction(i, { value: e.target.value }))} className="flex-1 px-2 py-1.5 border border-border rounded-md bg-background text-sm"> {labels.map(l => )} + ) : ( - No labels yet — create one in Settings → Labels. + ) )} diff --git a/apps/desktop/test/unit/src/components/settings/FiltersTab.new-label.test.tsx b/apps/desktop/test/unit/src/components/settings/FiltersTab.new-label.test.tsx new file mode 100644 index 00000000..15f3a44c --- /dev/null +++ b/apps/desktop/test/unit/src/components/settings/FiltersTab.new-label.test.tsx @@ -0,0 +1,140 @@ +// @vitest-environment happy-dom +import type { FilterRule, Label } from '@sarvinbox/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { FiltersTab } from '../../../../../src/components/settings/FiltersTab'; +import { cleanup, fire, render, settle, typeInto, type Mounted } from '../../../../helpers/render'; + +// "Create new label" in a filter's "Apply label" action. A regression here is +// a user who has to leave the filter half-made to create a label in +// Settings → Labels, a filter saved with the menu entry's placeholder value as +// its label, or the new label landing on the wrong action row. + +const store = vi.hoisted(() => ({ labels: [] as Label[], loadLabels: async () => {} })); +vi.mock('../../../../../src/store/email-store', () => ({ + useEmailStore: (select: (state: unknown) => unknown) => select({ folders: [], ...store }), +})); +vi.mock('../../../../../src/components/settings/BlockedSendersPanel', () => ({ BlockedSendersPanel: () => null })); + +const label = (name: string): Label => ({ id: `l-${name}`, name, color: '#000' } as Label); + +const api = { + filters: { + list: vi.fn(async () => ({ success: true, data: [] as FilterRule[] })), + create: vi.fn(async (input: unknown) => ({ success: true, data: { ...(input as object), id: 'new' } })), + update: vi.fn(), delete: vi.fn(), reorder: vi.fn(), applyToExisting: vi.fn(), countMatches: vi.fn(), + }, + labels: { + create: vi.fn(async (input: { name: string }) => { + store.labels = [...store.labels, label(input.name)]; + return { success: true }; + }), + }, +}; + +/** Pick an option of a