From 60068399a8caf29c5209f62ec7cac6853919fa27 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Thu, 19 Nov 2026 14:05:20 +0530 Subject: [PATCH 1/8] chore(security): drop withdrawn audit exceptions, update fast-xml-parser GitHub withdrew both advisories held in pnpm.auditConfig.ignoreCves (http-cache-semantics on 2026-10-28, braces on 2026-10-23), and on 2026-11-18 the picomatch advisory (GHSA-fc5q-39xc-vjpf) that had been failing the audit gate on main. pnpm audit --audit-level=high now exits 0 with no ignore list, so the list is removed. fast-xml-parser, which the desktop app ships to read text from office attachments, goes from 5.11.2 to 5.12.1 for GHSA-474x-hrwr-fgx4 (low). The app configures no stop nodes, so the affected code was never reached. SECURITY.md records the 2026-11-19 review: no high or critical advisory, and two moderate ones in build tools with no fix those tools accept. --- CHANGELOG.md | 7 ++++ SECURITY.md | 77 +++++++++++++++++++++++++-------------- apps/desktop/package.json | 2 +- package.json | 8 +--- pnpm-lock.yaml | 22 +++++------ 5 files changed, 70 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae4b63c2..06b251d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Security +- **The XML reader used for office attachments is updated to 5.12.** It fixes a + low-severity slowdown on malformed tags + ([GHSA-474x-hrwr-fgx4](https://github.com/advisories/GHSA-474x-hrwr-fgx4)). + Sarv Inbox never used the affected feature, so earlier versions were not + exposed. + ## [1.4.11] - 2026-11-18 ### Added diff --git a/SECURITY.md b/SECURITY.md index baf925a5..a9f0511e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -95,33 +95,56 @@ A handful cannot be fixed that way. Those are listed in pnpm 8 offers — and every entry must be justified here. An undocumented entry is a bug: the point of the gate is that nothing high-severity is silently carried. -Reviewed 2026-10-12 (`pnpm audit --audit-level=high` exits 0; the full report -without the ignore list shows 2 high, both below, and 3 moderate, noted after -the table). Neither high advisory has a fixed version that an override could -reach, so both exceptions stay: - -| CVE | Package | Why it is accepted | Removed when | -| --- | --- | --- | --- | -| [CVE-2026-93748](https://github.com/advisories/GHSA-ch52-4w7c-c8xp) | `http-cache-semantics` <= 4.2.0 | Cross-user response disclosure requires a shared HTTP cache accepting attacker-controlled `max-stale` directives. The dependency is reached only through the desktop **build tool** `electron-builder` → `app-builder-lib` → `@electron/get` → `got` → `cacheable-request`. Inbox does not use this chain to handle mail, OAuth, scanner requests, or shared user caches. **No patched release exists.** 4.3.0 (2026-10-04) is not one: it fixes a different advisory (CVE-2026-93750, `Vary` matching) and leaves `max-stale` handling unchanged. Because the advisory's range stops at 4.2.0, `pnpm audit` would nonetheless report this CVE as gone on 4.3.0, so do not read a clean audit after such a bump as a fix. This is a temporary exception for that reviewed tooling scope, not a vulnerability fix. | A release that actually changes `max-stale` handling ships (check its diff, not the advisory range), the build tool drops it, or a runtime/shared-cache path appears (reassess before shipping). | -| [CVE-2026-93687](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) | `braces` <= 3.0.3 | Stack exhaustion requires deeply nested glob patterns. All dependency paths are **tooling**: ESLint/globby, Tailwind/chokidar/fast-glob, and Metro/Jest. These tools process project patterns, not mail bodies, attachments, or user-supplied runtime patterns. **No patched release exists** (3.0.3 is the latest published version). The remaining build-tool risk is accepted temporarily; the package itself remains vulnerable. | A patched release becomes available, the tooling drops it, or an untrusted runtime-pattern path appears (reassess before shipping). | - -Moderate, no fixed version (below the gate, so not in `ignoreCves`; listed so -the full report holds no surprises): - -- [CVE-2026-97058](https://github.com/advisories/GHSA-hp3w-g68c-fv3c), - `sprintf-js` <= 1.1.3 (denial of service through unbounded precision - specifiers). 1.1.3 is the latest release. Reached only by dev and build - tooling: 1.0.3 via `packages/ui-primitives` → `react-native` (an optional - peer) → `babel-jest` → … → `js-yaml@3` → `argparse@1`, and 1.1.3 via - `electron-builder` → `@electron/get` → `global-agent` → `roarr`. Neither is - in the shipped app. -- [CVE-2026-104844](https://github.com/advisories/GHSA-rj75-hqrm-r3gf), - `postcss-selector-parser` < 7.1.6 (quadratic parsing of flat selectors). - Fixed only in 7.1.6. 6.1.4, the last 6.x release, comes from Tailwind CSS 3 - (`tailwindcss` and its `postcss-nested`), a devDependency that requires the - 6.x line. Forcing 7.x on it would be an incompatible major-version override. - It runs at build time over the app's own stylesheets and never parses email - or user CSS. +Reviewed 2026-11-19: `pnpm audit --audit-level=high` exits 0 with **no ignore +list**, and the full report shows no high or critical advisory. The list was +emptied because GitHub withdrew both advisories it held, so there is nothing +left to accept: + +- [CVE-2026-93748](https://github.com/advisories/GHSA-ch52-4w7c-c8xp), + `http-cache-semantics` <= 4.2.0, withdrawn 2026-10-28. It was reached only + through the build tool `electron-builder`. +- [CVE-2026-93687](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm), + `braces` <= 3.0.3, withdrawn 2026-10-23. It was reached only through + tooling (ESLint, Tailwind, Metro, Jest). + +[GHSA-fc5q-39xc-vjpf](https://github.com/advisories/GHSA-fc5q-39xc-vjpf) +(`picomatch` <= 4.0.7, high, no fixed version) failed the gate until GitHub +withdrew it on 2026-11-18, so no entry was added for it. If a withdrawn advisory +is ever reinstated, the gate fails again and it is reviewed here like any other. + +The one advisory in a package the app ships was fixed by upgrading: +[GHSA-474x-hrwr-fgx4](https://github.com/advisories/GHSA-474x-hrwr-fgx4) +(low, quadratic CPU when scanning unterminated stop-node tags) in +`fast-xml-parser` <= 5.11.2, which reads the text of office attachments for the +Inbox Agent. The app configures no stop nodes, so 1.4.11 and earlier never ran +the affected code; the dependency and its override now require 5.12.0 or later. + +Moderate, no fixed version these tools accept (below the gate, so not in +`ignoreCves`; listed so the full report holds no surprises): + +- [CVE-2026-118773](https://github.com/advisories/GHSA-3g3m-2fjr-6pw4), + `glob` 9.0.0 to 14.0.1 (an aborted walk can keep reading the filesystem + after its `AbortSignal` fires). Fixed only in 14.0.2. 13.0.6 comes from + `@electron/asar` and `@sentry/vite-plugin`, both desktop devDependencies used + while packaging. They walk the project's own build output and never cancel a + walk to bound untrusted input. +- [CVE-2026-118764](https://github.com/advisories/GHSA-g3hv-75wg-m249), + `minimatch` 7.0.0 to 11.0.0 (denial of service through globparts + amplification). Fixed only in 11.0.1. 9.0.9 comes from `@typescript-eslint` + 6 (lint) and `electron-builder` → `@electron/universal`; 10.2.6 from + `@electron/asar`, `electron-builder` → `app-builder-lib` and + `@sentry/bundler-plugins`. Every pattern is one the project's own build or + lint configuration supplies; none comes from mail or the user. + +Forcing either onto its new major line would be an incompatible major-version +override on those tools. Neither package is in the shipped app. + +The 2026-10-12 review also listed two moderates that are now gone: +[CVE-2026-97058](https://github.com/advisories/GHSA-hp3w-g68c-fv3c) +(`sprintf-js`) was withdrawn on 2026-10-22, and +[CVE-2026-104844](https://github.com/advisories/GHSA-rj75-hqrm-r3gf) +(`postcss-selector-parser`) gained a 6.x fix, 6.1.5, which the +`postcss-selector-parser@6` override already requires. The previous Vite exception (`CVE-2026-53571`) was removed: the desktop now uses Vite 8. The two `image-size` exceptions (`CVE-2025-71329` and diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 5431b399..0652e192 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -57,7 +57,7 @@ "dompurify": "^3.4.17", "electron-updater": "^6.8.9", "email-addresses": "^5.0.0", - "fast-xml-parser": "^5.5.6", + "fast-xml-parser": "^5.12.0", "fflate": "^0.8.3", "html-to-text": "^10.0.1", "ical.js": "^2.2.1", diff --git a/package.json b/package.json index 7268fd31..5e3d5a5a 100644 --- a/package.json +++ b/package.json @@ -93,7 +93,7 @@ "deepmerge-ts": "^8.0.1", "dompurify": "^3.4.17", "fast-uri@3": "^3.1.9", - "fast-xml-parser": "^5.5.6", + "fast-xml-parser": "^5.12.0", "flatted": "^3.4.4", "follow-redirects@1": "^1.16.2", "form-data": "^4.0.6", @@ -125,12 +125,6 @@ "ws@7": "^7.5.11", "yaml@2": "^2.8.3", "zod@4": "^4.6.6" - }, - "auditConfig": { - "ignoreCves": [ - "CVE-2026-93748", - "CVE-2026-93687" - ] } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9bef6384..0a81dcab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,7 +19,7 @@ overrides: deepmerge-ts: ^8.0.1 dompurify: ^3.4.17 fast-uri@3: ^3.1.9 - fast-xml-parser: ^5.5.6 + fast-xml-parser: ^5.12.0 flatted: ^3.4.4 follow-redirects@1: ^1.16.2 form-data: ^4.0.6 @@ -180,8 +180,8 @@ importers: specifier: ^5.0.0 version: 5.0.0 fast-xml-parser: - specifier: ^5.5.6 - version: 5.11.2 + specifier: ^5.12.0 + version: 5.12.1 fflate: specifier: ^0.8.3 version: 0.8.3 @@ -5907,20 +5907,20 @@ packages: resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} dev: true - /fast-xml-builder@1.3.1: - resolution: {integrity: sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==} + /fast-xml-builder@1.3.2: + resolution: {integrity: sha512-OX91VSlShLPDgRZV7tk/YQ4l8tT75QziF5Ixg8g4PFbCVPjuTWwN+yQfAxLJ0dufJpprdOd6HlM74Jhd39TcBQ==} dependencies: path-expression-matcher: 1.6.2 xml-naming: 0.3.0 dev: false - /fast-xml-parser@5.11.2: - resolution: {integrity: sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==} + /fast-xml-parser@5.12.1: + resolution: {integrity: sha512-wR8dO/fx+z8C5exuem1e7BKOWvjsuzvjS/tvA/Xu3Z1zQqJGcXrPzXbcAiaMgp2KjreEROcTkmnnisrcmJ2hYQ==} hasBin: true dependencies: '@nodable/entities': 3.1.0 - fast-xml-builder: 1.3.1 - is-unsafe: 2.0.2 + fast-xml-builder: 1.3.2 + is-unsafe: 2.0.3 path-expression-matcher: 1.6.2 strnum: 2.5.1 xml-naming: 0.3.0 @@ -6865,8 +6865,8 @@ packages: which-typed-array: 1.1.19 dev: true - /is-unsafe@2.0.2: - resolution: {integrity: sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==} + /is-unsafe@2.0.3: + resolution: {integrity: sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==} dev: false /is-weakmap@2.0.2: From 924e754ca0bfee1bfbf6b976a79fbd25eb30e199 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Tue, 24 Nov 2026 15:10:11 +0530 Subject: [PATCH 2/8] fix(extensions): retry a slow restart after a crash, run the escape test under the app's heap cap A follow-up to the OS-sandboxed extension renderer (#107, CASA item 15), which brought the sandbox-escape harness, its out-of-memory probe and the automatic restart after a crash. The "Extension sandbox escape test (macos-latest)" CI job failed about one run in six, never on Linux or Windows. Right after the probe ran out of memory, reloading it threw "The extension sandbox did not load" (15 s). Cause: the harness did not run Electron with the app's V8 flags. main.ts sets --js-flags=--max-old-space-size=2048 and Chromium hands it on to every renderer, extension sandboxes included. Without it the probe filled about 3.6 GB on a 7 GB runner (Heap: used=3586MB limit=3680MB in every failing run), and the next sandbox start took 1.6 to 14.8 s even in passing runs: a continuous tail against the 15 s timeout, not a hang. That exposed a product gap: if the restart planned after a crash was slow, its failure was only logged and recovery ended there. The extension stayed off until the app was restarted. - electron/v8-flags.ts: appJsFlags() is the one source of the heap cap, used by main.ts and the harness. - extension-host: a restart after a crash whose sandbox start timed out counts as one attempt and plans the next (2 s, 15 s, 60 s). A refused start, a first start, or extension code that timed out is not retried. The problem card is held while an attempt is pending and shown once when every attempt has failed. - Harness: after the out-of-memory crash it waits for the app's own restart (bounded by the delays and both timeouts) instead of racing a reload against it. New check "out of memory: it comes back by itself". run.mjs's kill timer goes from 240 s to 360 s to cover that wait. This changes what the harness checks there, deliberately. - Tests: five scripted-start cases in extension-sandbox-boundary.test.ts (retry after a slow start, give up after the bounded attempts with one card, no retry on refusal, on an extension-code timeout, or of a first start) and v8-flags.test.ts (main.ts and the harness both use the helper). - Docs: the project conventions file lists appJsFlags; docs/TESTING.md notes why the harness uses it; CHANGELOG Fixed entry. With the cap, the probe now stops at used=2052.6MB limit=2144.0MB locally. The harness passes all three scenarios (159 checks) and the escapes scenario passed 4 of 4 repeated runs. --- CHANGELOG.md | 7 + CLAUDE.md | 5 + apps/desktop/electron/main.ts | 6 +- apps/desktop/electron/v8-flags.ts | 24 +++ apps/desktop/test/sandbox-escape/harness.ts | 18 ++- apps/desktop/test/sandbox-escape/run.mjs | 4 +- .../test/unit/electron/v8-flags.test.ts | 34 ++++ docs/TESTING.md | 7 + .../core/src/extensions/extension-host.ts | 21 ++- .../extension-sandbox-boundary.test.ts | 147 ++++++++++++++++++ 10 files changed, 264 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/electron/v8-flags.ts create mode 100644 apps/desktop/test/unit/electron/v8-flags.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b19cf36..0d753f67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 reading it. A review can now be used for 60 minutes, counted from when it is ready. Before anything is changed, each conversation is still checked again and left alone if it has changed since the review. +- **A crashed extension comes back even when the computer is slow to + recover.** When an extension crashes, for example by running out of memory, + the app starts it again, up to three times. If the first of those starts was + slow because the computer was still freeing the memory the crash had used, + that one slow start ended the recovery: the extension stayed off until the + app was restarted. A start that is too slow now counts as one attempt and + the next one follows. You are told only once every attempt has failed. ### Security - **Your Sarv sign-in is no longer sent to the address in Blocklists.** If you diff --git a/CLAUDE.md b/CLAUDE.md index ccfe87db..2770bb23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -406,6 +406,11 @@ Established shared helpers (extend this list as you add more): `InboxAssistantServiceDeps` when a test asks the agent a question. The evaluation in `apps/desktop/test/eval/assistant/` is built on it; see [docs/TESTING.md](docs/TESTING.md), "Inbox Agent evaluation". +- `appJsFlags(extra?)` / `V8_MAX_OLD_SPACE_MB` — `apps/desktop/electron/v8-flags.ts`. + The app's V8 flags. Chromium passes `--js-flags` to every renderer, the extension + sandboxes included, so this 2 GB heap cap is also how much an extension can + take. Use it wherever Electron is launched with `js-flags`, the sandbox-escape + harness included, so a test runs under the cap that ships. ## Prefer a mature library over hand-rolled / regex logic diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 06b3d65f..dedea819 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -162,6 +162,7 @@ import { mainWindowWebPreferences } from './utils/main-window-preferences'; import { installNavigationGuards } from './utils/navigation-guards'; import { installPermissionPolicy } from './utils/permission-policy'; import { restoreAndFocusWindow } from './utils/window-focus'; +import { appJsFlags } from './v8-flags'; // App identity MUST be set before ANYTHING reads app.getPath('userData') — // initSentryMain(), the file logger, and the DB key store all derive their paths @@ -418,7 +419,8 @@ if (process.platform === 'darwin') { // Disable security warnings in development process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'; -// Increase Node.js memory limit to 2GB. +// V8's heap limit, 2 GB, for main and (the switch propagates) every renderer, +// the extension sandboxes included: see v8-flags.ts. // Opt-in diagnostic: set SARV_PROFILE=1 (dev only) to also turn on V8's tick // profiler (--prof). Use it to find a synchronous main-thread CPU hog (a // renderer freeze / beachball): the switch propagates to renderer processes @@ -429,7 +431,7 @@ const V8_PROFILE = isDev && process.env['SARV_PROFILE'] ? ` --prof --logfile=${join(app.getPath('userData'), 'v8prof-%p.log')}` : ''; -app.commandLine.appendSwitch('js-flags', `--max-old-space-size=2048${V8_PROFILE}`); +app.commandLine.appendSwitch('js-flags', appJsFlags(V8_PROFILE)); // Suppress EGL/GPU driver error messages app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds'); diff --git a/apps/desktop/electron/v8-flags.ts b/apps/desktop/electron/v8-flags.ts new file mode 100644 index 00000000..2b89f438 --- /dev/null +++ b/apps/desktop/electron/v8-flags.ts @@ -0,0 +1,24 @@ +/** + * The V8 flags the app runs with. + * + * `--js-flags` is not only main's: Chromium hands it on to every renderer it starts, + * the extension sandboxes included. So this heap cap is also how much memory an + * extension's code can take before it runs out and is stopped. + * + * One source for it, because the sandbox-escape harness must run extension code under + * the same cap the app ships. Without it, the harness's out-of-memory probe filled the + * default ~3.7 GB heap instead of 2 GB. On a 7 GB macOS CI runner that pushed the + * machine into swap, and the next sandbox start overran its load timeout about one + * run in six. + */ + +/** Old-space heap limit, in MB, for main and every renderer. */ +export const V8_MAX_OLD_SPACE_MB = 2048; + +/** + * The `--js-flags` value: the heap cap, plus anything a caller adds. `extra` must begin + * with a space. + */ +export function appJsFlags(extra = ''): string { + return `--max-old-space-size=${V8_MAX_OLD_SPACE_MB}${extra}`; +} diff --git a/apps/desktop/test/sandbox-escape/harness.ts b/apps/desktop/test/sandbox-escape/harness.ts index 1faabbd7..43cff2a5 100644 --- a/apps/desktop/test/sandbox-escape/harness.ts +++ b/apps/desktop/test/sandbox-escape/harness.ts @@ -17,13 +17,14 @@ import type { AddressInfo } from 'node:net'; import * as path from 'node:path'; import { pathToFileURL } from 'node:url'; -import { createEventBus, ExtensionManager } from '@sarvinbox/core'; +import { createEventBus, ExtensionManager, SANDBOX_RESTART_DELAYS_MS, SANDBOX_START_TIMEOUT_MS } from '@sarvinbox/core'; import { app, BrowserWindow, ipcMain, protocol, session, WebContentsView, webContents } from 'electron'; import { downloadScanners, isScannerExtensionAvailable } from '../../electron/services/attachment-download-protection'; import { createExtensionNetworkBackend } from '../../electron/services/extension-network-backend'; -import { createSandboxChannel, SANDBOX_SCHEME_PRIVILEGES, sandboxPartition } from '../../electron/services/extension-runtime'; +import { createSandboxChannel, PAGE_LOAD_TIMEOUT_MS, SANDBOX_SCHEME_PRIVILEGES, sandboxPartition } from '../../electron/services/extension-runtime'; import { installIpcSenderGuard } from '../../electron/utils/ipc-sender-guard'; +import { appJsFlags } from '../../electron/v8-flags'; const FIXTURES = process.env.SANDBOX_ESCAPE_FIXTURES as string; const WORK = process.env.SANDBOX_ESCAPE_WORK as string; @@ -31,6 +32,11 @@ const SCENARIO = process.env.SANDBOX_ESCAPE_SCENARIO ?? 'escapes'; app.setName('sarv-inbox-sandbox-escape'); app.setPath('userData', path.join(WORK, 'userData')); +// The app's V8 flags, which reach every renderer: extension code here runs under the +// heap cap it ships with. Without them the out-of-memory probe filled ~3.7 GB instead +// of 2 GB, and on a 7 GB CI runner the machine was still swapping when the next +// sandbox had to start. +app.commandLine.appendSwitch('js-flags', appJsFlags()); protocol.registerSchemesAsPrivileged([SANDBOX_SCHEME_PRIVILEGES]); installIpcSenderGuard(ipcMain as never, { mainWindow: () => null, @@ -283,9 +289,15 @@ async function escapes(): Promise { check('out of memory: the call ends with a reason', String(oom.threw).includes('stopped'), oom); check('out of memory: its renderer is gone', (await until(() => !isAlive(pidBefore), 5000)) === true); check('out of memory: another extension still answers', (await call(manager, 'victim', 'ping')) === 'victim alive'); + // It comes back by itself, through the restart the app plans after any crash, retries + // included. Not a reload raced against that restart: the machine is still reclaiming + // what the crashed renderer held, and a first start after it can overrun the load + // timeout. Bounded by every attempt: each delay, plus a start that times out. + const restartBound = SANDBOX_RESTART_DELAYS_MS.reduce((sum, delay) => sum + delay + PAGE_LOAD_TIMEOUT_MS + SANDBOX_START_TIMEOUT_MS, 0); + const restarted = await until(() => manager.getExtensionInfo('probe')?.state === 'active', restartBound); + check('out of memory: it comes back by itself', Boolean(restarted), manager.getExtensionInfo('probe')?.state); // A hang is killed, and the other keeps working while it spins. - await manager.getHost().reload('probe'); const hungPid = (sandboxOf('probe') as Electron.WebContents).getOSProcessId(); const started = Date.now(); const hanging = call(manager, 'probe', 'hang'); diff --git a/apps/desktop/test/sandbox-escape/run.mjs b/apps/desktop/test/sandbox-escape/run.mjs index 617f7231..7a896e79 100644 --- a/apps/desktop/test/sandbox-escape/run.mjs +++ b/apps/desktop/test/sandbox-escape/run.mjs @@ -81,7 +81,9 @@ function launch(scenario, extraArgs) { }, }); mkdirSync(join(work, scenario), { recursive: true }); - const timer = setTimeout(() => child.kill('SIGKILL'), 240_000); + // A safety net for a hang, above the longest wait a scenario has: after the + // out-of-memory crash, escapes waits up to ~212 s for the app's restarts. + const timer = setTimeout(() => child.kill('SIGKILL'), 360_000); const onData = (chunk) => { output += chunk; const lines = (partial + chunk).split('\n'); diff --git a/apps/desktop/test/unit/electron/v8-flags.test.ts b/apps/desktop/test/unit/electron/v8-flags.test.ts new file mode 100644 index 00000000..aee92ae3 --- /dev/null +++ b/apps/desktop/test/unit/electron/v8-flags.test.ts @@ -0,0 +1,34 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { appJsFlags, V8_MAX_OLD_SPACE_MB } from '../../../electron/v8-flags'; + +const desktop = join(__dirname, '../../..'); +const source = (relative: string) => readFileSync(join(desktop, relative), 'utf8'); +/** Every `appendSwitch('js-flags', …)` argument in a file, as written. */ +const jsFlagSwitches = (text: string) => [...text.matchAll(/appendSwitch\(\s*'js-flags'\s*,\s*([^)]*\))/g)].map((m) => m[1]); + +describe('the V8 flags', () => { + // Breaks: the heap cap changes shape, and main and every renderer (extension + // sandboxes included) get a different limit, or none. + it('cap the old-space heap at 2 GB and keep what a caller adds', () => { + expect(V8_MAX_OLD_SPACE_MB).toBe(2048); + expect(appJsFlags()).toBe('--max-old-space-size=2048'); + expect(appJsFlags(' --prof --logfile=/tmp/x-%p.log')).toBe('--max-old-space-size=2048 --prof --logfile=/tmp/x-%p.log'); + }); + + // Breaks: main.ts goes back to writing its own flag string, which can drift from the + // one the sandbox-escape harness runs under. + it('are the ones the app sets, from the shared helper only', () => { + expect(jsFlagSwitches(source('electron/main.ts'))).toEqual(['appJsFlags(V8_PROFILE)']); + }); + + // Breaks: the harness runs extension code without the app's heap cap. Its + // out-of-memory probe then fills ~3.7 GB instead of 2 GB, and on a 7 GB macOS CI + // runner the next sandbox start overran its load timeout about one run in six. + it('are the ones the sandbox-escape harness runs extension code under', () => { + expect(jsFlagSwitches(source('test/sandbox-escape/harness.ts'))).toEqual(['appJsFlags()']); + }); +}); diff --git a/docs/TESTING.md b/docs/TESTING.md index aa78120f..0076105a 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -31,6 +31,13 @@ upgrade Electron, and add to `fixtures/probe` when a new way out turns up. Never start it beside your own dev app without `SANDBOX_ESCAPE_ELECTRON`: see the note in `run.mjs`. +It runs extension code under the app's own V8 flags (`electron/v8-flags.ts`), so its +out-of-memory probe stops at the 2 GB heap cap that ships. Without them the probe +filled about 3.7 GB. On a 7 GB macOS CI runner that left the machine swapping, and +the next sandbox start overran its 15 s load timeout about one run in six. After +that crash the harness waits for the app's own restart, retries included, rather +than racing a reload against it. + ### The one gotcha: better-sqlite3's ABI `better-sqlite3` is a compiled addon, valid for exactly **one** ABI at a time, diff --git a/packages/core/src/extensions/extension-host.ts b/packages/core/src/extensions/extension-host.ts index 4617974f..2224e097 100644 --- a/packages/core/src/extensions/extension-host.ts +++ b/packages/core/src/extensions/extension-host.ts @@ -24,7 +24,7 @@ import type { WorkflowResult } from '../pipeline/types'; import { EmailWorkflow, WorkflowContext, WorkflowPriority } from '../pipeline/types'; import type { EmailRecord } from '../types/models'; import { logger } from '../utils/logger'; -import { withTimeout } from '../utils/timeout'; +import { isTimeoutError, withTimeout } from '../utils/timeout'; import { createExtensionContext, @@ -494,7 +494,7 @@ export class ExtensionHost { const timer = setTimeout(() => { const state = this.restarts.get(extensionId); if (state) state.timer = null; - void this.activate(loaded, installed.grantedPermissions).catch((error) => { + void this.activate(loaded, installed.grantedPermissions, { afterCrash: true }).catch((error) => { logger.warn(`Restarting ${extensionId} failed:`, error); }); }, delay); @@ -592,9 +592,15 @@ export class ExtensionHost { /** * Activate a single extension */ + /** + * @param options.afterCrash this start is one of the restarts planned after a crash + * (see `planRestart`): a sandbox that is too slow to start then gets the next + * attempt instead of ending the recovery. + */ async activate( loaded: LoadedExtension, - grantedPermissions: ExtensionPermission[] + grantedPermissions: ExtensionPermission[], + options: { afterCrash?: boolean } = {} ): Promise { const { manifest, entryPoint } = loaded; @@ -720,6 +726,15 @@ export class ExtensionHost { const message = error instanceof Error ? error.message : String(error); info.state = ExtensionState.ERROR; this.registry.setRuntimeInfo(manifest.id, info); + // A restart after a crash whose sandbox did not come up in time is the machine, + // not the extension: an out-of-memory crash leaves the OS reclaiming what the + // renderer held, and the first start after it can overrun the load timeout. That + // is one attempt, not the end of the recovery. Planned BEFORE the report, so no + // card is shown while another attempt is due; once they run out, it is. A refusal + // or the extension's own code failing is not retried. + if (options.afterCrash && !sandboxStarted && isTimeoutError(error)) { + this.planRestart(manifest.id); + } if (!sandboxStarted) { // The host refused or could not start it, and says why. this.reportProblem(manifest.id, message); diff --git a/packages/core/test/unit/extensions/extension-sandbox-boundary.test.ts b/packages/core/test/unit/extensions/extension-sandbox-boundary.test.ts index eb298e65..f831fe0e 100644 --- a/packages/core/test/unit/extensions/extension-sandbox-boundary.test.ts +++ b/packages/core/test/unit/extensions/extension-sandbox-boundary.test.ts @@ -33,6 +33,7 @@ import { ExtensionManager } from '../../../src/extensions/extension-manager'; import type { ExtensionRegistry } from '../../../src/extensions/extension-registry'; import { DEACTIVATE_TIMEOUT_MS, + DEFAULT_INVOKE_TIMEOUT_MS, ExtensionBridge, HOST_CALL_SLICE_MS, MAX_DESCRIPTION_LENGTH, @@ -59,6 +60,7 @@ import type { WorkflowContext } from '../../../src/pipeline/types'; import { captureLogs } from '../../../src/test-support/log-capture'; import type { EmailRecord } from '../../../src/types/models'; import { getLogLevel, setLogLevel, setLogSink } from '../../../src/utils/logger'; +import { TimeoutError } from '../../../src/utils/timeout'; let workDir: string; @@ -1582,6 +1584,46 @@ function restartableHost(modules: Record, regist return { host, closes, started }; } +/** + * A host whose Nth sandbox start does what `starts[N]` says: 'ok' starts it, 'slow' fails + * as a sandbox that did not load in time does (a TimeoutError), 'refused' fails as a host + * refusal does, 'hangs' starts the sandbox but the extension's own activate never returns. + * Past the end of the list every start is 'ok'. + */ +function scriptedStartHost( + starts: ('ok' | 'slow' | 'refused' | 'hangs')[], + registry: ReturnType, + ui?: ExtensionUIBackend +) { + const closes = new Map void>(); + const started: string[] = []; + const host = new ExtensionHost({ + registry, + eventBus: createEventBus(), + storageBackend: memoryStorage(), + settingsBackend: memorySettings(), + uiBackend: ui, + extensionStoragePath: join(workDir, 'storage'), + createChannel: (target) => { + const plan = starts[started.length] ?? 'ok'; + started.push(target.extensionId); + if (plan === 'slow') return Promise.reject(new TimeoutError('The extension sandbox did not load')); + if (plan === 'refused') return Promise.reject(new Error('Extensions are off')); + const pair = createInProcessChannelPair(); + startExtensionSandbox(pair.sandbox, () => (plan === 'hangs' ? { activate: () => new Promise(() => {}) } : { activate() {} })); + return { + post: (message: unknown) => pair.host.post(message), + onMessage: (handler: (message: unknown) => void) => pair.host.onMessage(handler), + onClose: (handler: (reason?: string, details?: { transient: boolean }) => void) => { + closes.set(target.extensionId, handler); + }, + close: () => pair.host.close(), + }; + }, + }); + return { host, closes, started }; +} + describe('after a sandbox dies', () => { const { 0: first, 1: second, 2: third } = SANDBOX_RESTART_DELAYS_MS; const fake = () => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); @@ -1702,6 +1744,111 @@ describe('after a sandbox dies', () => { vi.useRealTimers(); }); + // Breaks: an out-of-memory crash leaves the OS reclaiming what the renderer held, and + // the first restart's sandbox overruns its load timeout. That one slow start ended the + // recovery: the extension stayed off for the session although attempts were left. + it('tries again when a restart after a crash is too slow to start, and says nothing while it recovers', async () => { + fake(); + const loaded = extension('a'); + const reportProblem = vi.fn(); + const registry = registryWith({ a: { loaded } }); + const { host, closes, started } = scriptedStartHost(['ok', 'slow'], registry, { notify: vi.fn(), dismiss: vi.fn(), reportProblem }); + await host.activate(loaded, []); + + closes.get('a')?.('This extension ran out of memory and was stopped.', { transient: true }); + await vi.advanceTimersByTimeAsync(first + 1); + await vi.waitFor(() => expect(started).toHaveLength(2)); + expect(host.isActive('a')).toBe(false); + + await vi.advanceTimersByTimeAsync(second + 1); + await vi.waitFor(() => expect(host.isActive('a')).toBe(true)); + expect(started).toEqual(['a', 'a', 'a']); + // Recovered on the next attempt: nothing worth a card. + expect(reportProblem).not.toHaveBeenCalled(); + vi.useRealTimers(); + await host.dispose(); + }); + + // Breaks: a sandbox that never starts in time is retried for ever, or gives up without + // a word. The slow starts use up the same bounded attempts as crashes, then one card. + it('gives up after the bounded attempts when every restart is too slow, and only then says so', async () => { + fake(); + const loaded = extension('a'); + const reportProblem = vi.fn(); + const registry = registryWith({ a: { loaded } }); + const { host, closes, started } = scriptedStartHost(['ok', 'slow', 'slow', 'slow'], registry, { notify: vi.fn(), dismiss: vi.fn(), reportProblem }); + await host.activate(loaded, []); + + closes.get('a')?.('This extension ran out of memory and was stopped.', { transient: true }); + for (const delay of [first, second]) { + await vi.advanceTimersByTimeAsync(delay + 1); + expect(reportProblem).not.toHaveBeenCalled(); + } + await vi.advanceTimersByTimeAsync(third + 1); + await vi.advanceTimersByTimeAsync(10 * 60_000); + + expect(started).toHaveLength(1 + SANDBOX_RESTART_DELAYS_MS.length); + expect(host.isActive('a')).toBe(false); + expect(reportProblem).toHaveBeenCalledTimes(1); + expect(reportProblem.mock.calls[0][1].body).toContain('did not load'); + vi.useRealTimers(); + }); + + // Breaks: a restart the host refused is retried. A refusal is a fact about this + // computer, not a slow moment: it would be refused the same way each time. + it('does not retry a restart after a crash that the host refused', async () => { + fake(); + const loaded = extension('a'); + const reportProblem = vi.fn(); + const registry = registryWith({ a: { loaded } }); + const { host, closes, started } = scriptedStartHost(['ok', 'refused'], registry, { notify: vi.fn(), dismiss: vi.fn(), reportProblem }); + await host.activate(loaded, []); + + closes.get('a')?.('This extension crashed and was stopped.', { transient: true }); + await vi.advanceTimersByTimeAsync(10 * 60_000); + + expect(started).toEqual(['a', 'a']); + expect(reportProblem).toHaveBeenCalledTimes(1); + expect(reportProblem.mock.calls[0][1].body).toContain('Extensions are off'); + vi.useRealTimers(); + }); + + // Breaks: an extension whose own activate() never returns is started again and again. + // Its sandbox came up, so the machine was not the problem: its code was. + it('does not retry a restart whose extension code timed out starting', async () => { + fake(); + const loaded = extension('a'); + const reportProblem = vi.fn(); + const registry = registryWith({ a: { loaded } }); + const { host, closes, started } = scriptedStartHost(['ok', 'hangs'], registry, { notify: vi.fn(), dismiss: vi.fn(), reportProblem }); + await host.activate(loaded, []); + + closes.get('a')?.('This extension crashed and was stopped.', { transient: true }); + await vi.advanceTimersByTimeAsync(first + DEFAULT_INVOKE_TIMEOUT_MS + 1); + await vi.advanceTimersByTimeAsync(10 * 60_000); + + expect(started).toEqual(['a', 'a']); + expect(host.isActive('a')).toBe(false); + expect(reportProblem).toHaveBeenCalledTimes(1); + vi.useRealTimers(); + }); + + // Breaks: a first start (or the user's own restart) that times out starts a retry loop + // nobody asked for. Only the restarts planned after a crash try again. + it('does not retry a first start that was too slow', async () => { + fake(); + const loaded = extension('a'); + const registry = registryWith({ a: { loaded } }); + const { host, started } = scriptedStartHost(['slow'], registry); + + await expect(host.activate(loaded, [])).rejects.toThrow('did not load'); + await vi.advanceTimersByTimeAsync(10 * 60_000); + + expect(started).toEqual(['a']); + expect(host.isActive('a')).toBe(false); + vi.useRealTimers(); + }); + // Switched off while a restart was pending: it must stay off. it('cancels a pending restart when the extension is turned off', async () => { fake(); From 088f489d763e4cc2934aaddd419b7f734038cb97 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Tue, 24 Nov 2026 17:22:41 +0530 Subject: [PATCH 3/8] docs(changelog): keep the extension restart fix under Unreleased Merging main after the 1.4.12 release put this branch's entry inside the released 1.4.12 section, next to the entry it was written beside. Move it back under Unreleased. The 1.4.12 section is again byte-identical to the one in the v1.4.12 tag. --- CHANGELOG.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98afb73e..c278a9eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **A crashed extension comes back even when the computer is slow to + recover.** When an extension crashes, for example by running out of memory, + the app starts it again, up to three times. If the first of those starts was + slow because the computer was still freeing the memory the crash had used, + that one slow start ended the recovery: the extension stayed off until the + app was restarted. A start that is too slow now counts as one attempt and + the next one follows. You are told only once every attempt has failed. + ## [1.4.12] - 2026-11-24 ### Fixed @@ -25,13 +34,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 reading it. A review can now be used for 60 minutes, counted from when it is ready. Before anything is changed, each conversation is still checked again and left alone if it has changed since the review. -- **A crashed extension comes back even when the computer is slow to - recover.** When an extension crashes, for example by running out of memory, - the app starts it again, up to three times. If the first of those starts was - slow because the computer was still freeing the memory the crash had used, - that one slow start ended the recovery: the extension stayed off until the - app was restarted. A start that is too slow now counts as one attempt and - the next one follows. You are told only once every attempt has failed. ### Security - **Your Sarv sign-in is no longer sent to the address in Blocklists.** If you From 8a93e913f1a996464129fb27c008012a601b7cd5 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Mon, 23 Nov 2026 18:45:08 +0530 Subject: [PATCH 4/8] fix(security): name accounts, folders and paths by short codes in app.log MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rest of the app.log privacy work. The earlier fixes took mail text and correspondents' addresses out of the log. This takes out what still named the user, and makes crash reports and token requests carry less: - Account ids spell out the owner's address (`acct----`). They are now written as `accountLogLabel(id)`, a short stable hash. - Folders, Gmail labels, keywords and AI categories the user created are now written as `folderLogLabel` / `labelLogLabel` / `categoryLogLabel`. System folders keep their names. The helpers are in packages/core/src/utils/log-labels.ts. - Absolute paths no longer name the user through the home folder: `logPath` / `withoutHomeDir` in main, `pathForLog` / `redactHomeDir` in core. As a backstop, the release file logger and the crash-report scrubber rewrite the home folder as `~` and redact any account id they find. - Failures that could quote mail or a server's answer are logged by their kind (`errorDiagnostic` / `failureCause`), not by the error. - Crash reports: - The user id is a random `crashReportInstallId()` kept in userData, no longer a shortened hash of the address, which anyone guessing the address could confirm. - Request query strings are dropped. - The secret scrubber also removes sign-in codes, keys, passphrases and `Basic` passwords. - Token refreshes and the profile fetch after sign-in use `redirect: 'error'`, so a refresh token is never sent again to an address a redirect names. - The token refresher's error keeps a non-JSON response body in `detail`, not in its message. Callers log the message, and such a body can be a token in another encoding. - `apps/desktop/test/helpers/core-log-helpers.ts` gives desktop tests that mock `@sarvinbox/core` partially the real log helpers. - The CHANGELOG [Unreleased] Security section, privacy policy §2 and §4.2, and the shared-helpers list in the project conventions file all describe this. Pre-existing tests changed on purpose, because the log lines changed: - Their expectations now use the account and folder labels and the failure kind instead of the id, name or message. Files: body-reheal-scheduler, unified-pipeline-service-gmail-token, useFirstEmailSplit, first-split job/store, sync-slice, emails-slice, startup-thread-repair, update-service, sender-identity-service, file-logger, oauth-loopback, folder-classification. - token-refresher now checks the body in `detail` and not in the message. - Partial `@sarvinbox/core` mocks spread the real log helpers. - sentry-privacy and telemetry-scrub cover the new user id, the query strings and the wider scrubbing. Each changed expectation carries a "Changed deliberately (log privacy)" comment. None was loosened. --- CHANGELOG.md | 20 + CLAUDE.md | 28 ++ .../desktop/electron/ipc/accounts-handlers.ts | 9 +- apps/desktop/electron/ipc/agent-handlers.ts | 6 +- apps/desktop/electron/ipc/ai-handlers.ts | 54 +-- .../desktop/electron/ipc/contacts-handlers.ts | 6 +- apps/desktop/electron/ipc/draft-handlers.ts | 8 +- apps/desktop/electron/ipc/email-handlers.ts | 8 +- .../electron/ipc/image-trust-handlers.ts | 4 +- apps/desktop/electron/ipc/label-handlers.ts | 6 +- apps/desktop/electron/ipc/smtp-handlers.ts | 4 +- apps/desktop/electron/ipc/sync-handlers.ts | 35 +- apps/desktop/electron/main.ts | 9 +- apps/desktop/electron/sentry.ts | 27 +- .../electron/services/accounts-registry.ts | 7 +- .../electron/services/accounts-runtime.ts | 32 +- .../services/ai-categorization-service.ts | 8 +- .../electron/services/backfill-scheduler.ts | 8 +- .../services/body-reheal-scheduler.ts | 10 +- .../electron/services/bulk-backfill.ts | 6 +- .../electron/services/calendar-mail-sync.ts | 4 +- .../services/contact-enrichment-scheduler.ts | 6 +- .../conversation-extraction-scheduler.ts | 3 +- apps/desktop/electron/services/core-db.ts | 3 +- .../electron/services/crash-report-pref.ts | 32 ++ apps/desktop/electron/services/db-compact.ts | 14 +- .../services/extension-mail-backend.ts | 3 +- .../services/extension-marketplace.ts | 4 +- .../services/extension-workflow-runner.ts | 3 +- .../electron/services/follow-up-checker.ts | 4 +- .../electron/services/gmail-label-api.ts | 20 +- .../electron/services/notification-service.ts | 2 +- .../electron/services/oauth-service.ts | 3 + .../electron/services/outbox-service.ts | 3 +- .../services/sender-identity-service.ts | 7 +- .../services/spam-reputation-service.ts | 4 +- .../electron/services/spam-verdict-repair.ts | 7 +- .../services/startup-thread-repair.ts | 6 +- .../services/unified-pipeline-service.ts | 102 ++--- .../electron/services/update-service.ts | 11 +- .../electron/services/vault-credentials.ts | 7 +- apps/desktop/electron/utils/file-logger.ts | 37 +- apps/desktop/electron/utils/log-path.ts | 35 ++ .../components/aibox/AIBoxCategoryView.tsx | 3 +- .../email-detail/hooks/useFirstEmailSplit.ts | 8 +- apps/desktop/src/services/first-split/job.ts | 8 +- .../desktop/src/services/first-split/store.ts | 12 +- .../src/store/slices/connection-slice.ts | 3 +- .../src/store/slices/email-actions-slice.ts | 3 +- apps/desktop/src/store/slices/emails-slice.ts | 23 +- apps/desktop/src/store/slices/sync-slice.ts | 21 +- .../desktop/src/utils/account-scoped-cache.ts | 4 +- apps/desktop/test/helpers/core-log-helpers.ts | 15 + .../ipc/accounts-unified-search-log.test.ts | 6 +- .../ipc/imap-oauth-host-binding.test.ts | 2 + .../electron/ipc/imap-vault-password.test.ts | 2 + .../test/unit/electron/sentry-privacy.test.ts | 60 ++- .../accounts-runtime-attachments.test.ts | 4 +- .../services/accounts-runtime.test.ts | 36 +- .../services/ai-categorization-log.test.ts | 27 +- .../services/body-reheal-scheduler.test.ts | 6 +- .../contact-enrichment-scheduler.test.ts | 30 +- .../services/extension-mail-backend.test.ts | 15 + .../services/follow-up-checker.test.ts | 4 +- .../electron/services/gmail-label-api.test.ts | 37 +- .../electron/services/oauth-loopback.test.ts | 16 + .../electron/services/outbox-service.test.ts | 2 + .../services/sender-identity-service.test.ts | 36 +- .../services/startup-thread-repair.test.ts | 37 +- .../unified-pipeline-auto-send-log.test.ts | 31 ++ ...ified-pipeline-service-gmail-token.test.ts | 11 +- .../electron/services/update-service.test.ts | 22 ++ .../unit/electron/utils/file-logger.test.ts | 57 ++- .../test/unit/electron/utils/log-path.test.ts | 47 +++ .../email-detail/useFirstEmailSplit.test.tsx | 8 +- .../unit/src/services/first-split/job.test.ts | 4 +- .../src/services/first-split/store.test.ts | 12 +- .../src/store/slices/emails-slice.test.ts | 10 + .../unit/src/store/slices/sync-slice.test.ts | 33 ++ apps/desktop/tsconfig.json | 4 +- apps/desktop/vite/renderer-aliases.ts | 7 +- docs/legal/privacy-policy.md | 22 +- packages/core/src/config/folder-mapping.ts | 7 +- packages/core/src/imap/connection-pool.ts | 3 +- packages/core/src/imap/folder-syncer.ts | 28 +- packages/core/src/imap/imapflow-client.ts | 23 +- packages/core/src/imap/incremental-fetch.ts | 3 +- packages/core/src/imap/label-strategy.ts | 5 +- packages/core/src/imap/message-processor.ts | 99 ++--- packages/core/src/imap/operation-queue.ts | 38 +- packages/core/src/imap/qresync-reconcile.ts | 10 +- packages/core/src/imap/realtime-manager.ts | 36 +- packages/core/src/imap/sync-engine.ts | 69 ++-- packages/core/src/imap/sync-state.ts | 3 +- packages/core/src/oauth/token-refresher.ts | 36 +- packages/core/src/utils/index.ts | 2 + packages/core/src/utils/log-labels.ts | 116 ++++++ packages/core/src/utils/log-paths.ts | 81 ++++ packages/core/src/utils/telemetry-scrub.ts | 82 +++- .../unit/config/folder-classification.test.ts | 12 + .../unit/imap/folder-name-log-privacy.test.ts | 358 ++++++++++++++++++ .../oauth/token-refresher-redirect.test.ts | 103 +++++ .../test/unit/oauth/token-refresher.test.ts | 64 +++- .../core/test/unit/utils/log-labels.test.ts | 124 ++++++ .../core/test/unit/utils/log-paths.test.ts | 60 +++ .../test/unit/utils/telemetry-scrub.test.ts | 103 +++++ .../src/repositories/ai-repository.ts | 5 +- .../src/repositories/folder-repository.ts | 4 +- .../src/repositories/thread-sql.ts | 5 +- packages/storage-node/src/shared-contacts.ts | 7 +- packages/storage-node/src/sqlite-storage.ts | 7 +- .../test/unit/log-privacy.test.ts | 85 +++++ 112 files changed, 2391 insertions(+), 490 deletions(-) create mode 100644 apps/desktop/electron/utils/log-path.ts create mode 100644 apps/desktop/test/helpers/core-log-helpers.ts create mode 100644 apps/desktop/test/unit/electron/utils/log-path.test.ts create mode 100644 packages/core/src/utils/log-labels.ts create mode 100644 packages/core/src/utils/log-paths.ts create mode 100644 packages/core/test/unit/imap/folder-name-log-privacy.test.ts create mode 100644 packages/core/test/unit/oauth/token-refresher-redirect.test.ts create mode 100644 packages/core/test/unit/utils/log-labels.test.ts create mode 100644 packages/core/test/unit/utils/log-paths.test.ts create mode 100644 packages/storage-node/test/unit/log-privacy.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index de28a82d..898d0eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Security +- **The log file no longer names your accounts, folders or user folder.** + Every line about an account carried its internal id, which spells out the + email address, and lines about syncing named your folders, labels and AI + categories. These are now written as short codes (system folders such as + Inbox and Sent keep their names), file locations are written without your + home folder, and failures that could quote mail or a server's answer are + recorded by their kind only. +- **Crash reports carry less about you.** A report no longer identifies you by + a shortened hash of your email address, which anyone guessing your address + could confirm; it uses a random code made on your computer instead. Web + requests in a report no longer keep their query string (which can hold keys + and search words), and sign-in codes, keys, passphrases and `Basic` + passwords are removed from reports and the log file wherever they appear. +- **Sign-in tokens are never resent to a redirected address.** If an email + provider's token service answered a refresh with a redirect, the app would + have sent your refresh token again to wherever it pointed. It now refuses + the redirect and retries later, and the same goes for fetching your profile + after sign-in. + ## [1.4.12] - 2026-11-24 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index ccfe87db..7d17d5bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,6 +67,15 @@ lands in `app.log` consistently: field NAMES (`setFieldNamesForLog`), a URL's scheme (`urlSchemeForLog`) and `errorDiagnostic(error)` instead of the error, whose message can quote any of those. Prove it with a sentinel test (`captureLogs`). +- **Names that belong to the user are labels in a log line.** An account id + spells out its owner's address (`acct----`): + write `accountLogLabel(id)`. A folder, Gmail label, keyword or AI category + the user created is text they typed: `folderLogLabel(path)` (system folders + stay readable), `labelLogLabel(name)`, `categoryLogLabel(slug, isSystem)`. + An absolute path names the user through their home folder: `logPath(p)` in + main (`/…`, `~/…`), `pathForLog` / `basename` elsewhere. The file + logger rewrites the home folder as `~` and, in a release, account ids it + finds, and crash reports get the same — a backstop, not a licence. ## Native modules: better-sqlite3 has TWO ABIs — never flip it by hand @@ -400,6 +409,25 @@ Established shared helpers (extend this list as you add more): An http(s) address that is an origin and nothing else (no userinfo, path, query or fragment). The Sarv reputation rule and the scanner origin are built on it; use it for any setting that must name a service origin. +- `accountLogLabel(id, missing?)` / `folderLogLabel(path)` / `labelLogLabel(name)` / + `categoryLogLabel(slug, system)` / `redactAccountIds(text)` — + `packages/core/src/utils/log-labels.ts` (renderer: `@sarvinbox/core/log-labels`). + The stand-ins a log line uses for the account (`acct#1a2b3c4d`), a folder, + label or AI category the user named: a short stable hash, so lines still + match and grep. `redactAccountIds` is the backstop the release file logger + and the crash-report scrubber run over every line. +- `pathForLog(path, { userData, home })` / `redactHomeDir(text, home)` — + `packages/core/src/utils/log-paths.ts` (Node only); in main, `logPath(path)` / + `withoutHomeDir(text)` — `apps/desktop/electron/utils/log-path.ts`, rooted at + this app's data folder and the user's home. A path for a log line without the + home folder (and the user's name in it). +- `crashReportInstallId()` — `apps/desktop/electron/services/crash-report-pref.ts`. + The crash reports' user id: a random UUID kept in userData, never anything + derived from an address. +- `apps/desktop/test/helpers/core-log-helpers.ts` — the REAL core log helpers + (`errorDiagnostic`, the log labels, `pathForLog`) for a desktop test that mocks + `@sarvinbox/core` partially. Spread it first in the mock factory; a mock + without them fails at the first log line the code under test writes. - `createAssistantHarness()` — `apps/desktop/test/helpers/assistant-harness.ts`. The real Inbox Agent end to end for tests (real databases, history store and provider call path; scripted network). Use it instead of hand-wiring diff --git a/apps/desktop/electron/ipc/accounts-handlers.ts b/apps/desktop/electron/ipc/accounts-handlers.ts index 524fb2da..69a5bddf 100644 --- a/apps/desktop/electron/ipc/accounts-handlers.ts +++ b/apps/desktop/electron/ipc/accounts-handlers.ts @@ -16,10 +16,9 @@ * is active on launch, so no account can grab the primary's database. */ import type { EmailRecord, SearchQuery, ViewFilter } from '@sarvinbox/core'; -import { createLogger, errorDiagnostic } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, errorDiagnostic, redactAccountIds } from '@sarvinbox/core'; import { ipcMain } from 'electron'; - import { settleRevocation, type AccountRevocation } from '../services/account-revocation'; import { listRegistryAccounts, @@ -197,7 +196,7 @@ export function registerAccountsHandlers(): void { try { keepAccountIds = readRegistryAccounts().map((a) => a.id); const removed = cleanupOrphanedAccountDbs({ keepAccountIds, staleAfterMs: 0 }); - if (removed.length) logger.info(`[Accounts] removal swept ${removed.length} orphan file(s):`, removed.join(', ')); + if (removed.length) logger.info(`[Accounts] removal swept ${removed.length} orphan file(s):`, redactAccountIds(removed.join(', '))); } catch (e) { logger.warn('[Accounts] orphan DB sweep after removal failed or was skipped:', (e as Error).message); } @@ -360,7 +359,7 @@ export function registerAccountsHandlers(): void { ]); return { emails: emails.map((e) => ({ ...e, accountId })), total }; } catch (e) { - logger.warn('[Accounts] unifiedInbox: skipping account', accountId, (e as Error).message); + logger.warn('[Accounts] unifiedInbox: skipping account', accountLogLabel(accountId), (e as Error).message); return { emails: [], total: 0 }; } }), @@ -449,7 +448,7 @@ export function registerAccountsHandlers(): void { return { emails: emails.map((e) => ({ ...e, accountId })), total }; } catch (e) { // Class and code only: a search error can name the query's words. - logger.warn('[Accounts] unifiedSearch: skipping account', accountId, errorDiagnostic(e)); + logger.warn('[Accounts] unifiedSearch: skipping account', accountLogLabel(accountId), errorDiagnostic(e)); return { emails: [], total: 0 }; } }), diff --git a/apps/desktop/electron/ipc/agent-handlers.ts b/apps/desktop/electron/ipc/agent-handlers.ts index 1eccced6..47363c24 100644 --- a/apps/desktop/electron/ipc/agent-handlers.ts +++ b/apps/desktop/electron/ipc/agent-handlers.ts @@ -6,7 +6,7 @@ */ import type { UserActionType, ActionSource } from '@sarvinbox/core'; -import { createLogger, setEmailReadFlag } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, setEmailReadFlag } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { openAccountStorages, requireNamedOrActiveStorage, requireTargetAccountId } from '../services/account-target'; @@ -97,9 +97,9 @@ function runBackfillForNewAccounts(limit: number): void { const n = (store as any).getRepositories().agent.requeueRecentInboxForAgent(limit); done.push(id); changed = true; - logger.info(`[Agent] AI Assist on — re-queued ${n} existing Inbox emails for account ${id}`); + logger.info(`[Agent] AI Assist on — re-queued ${n} existing Inbox emails for account ${accountLogLabel(id)}`); } catch (e) { - logger.error(`[Agent] backfill re-queue failed for account ${id}:`, e); + logger.error(`[Agent] backfill re-queue failed for account ${accountLogLabel(id)}:`, e); } } if (changed) saveAgentConfig({ backfillRequeuedAccounts: done }); diff --git a/apps/desktop/electron/ipc/ai-handlers.ts b/apps/desktop/electron/ipc/ai-handlers.ts index ffddb6af..d5dd1463 100644 --- a/apps/desktop/electron/ipc/ai-handlers.ts +++ b/apps/desktop/electron/ipc/ai-handlers.ts @@ -5,6 +5,9 @@ */ import { + failureCause, + folderLogLabel, + accountLogLabel, conversationSenders, createLogger, errorDiagnostic, @@ -99,7 +102,7 @@ export async function clearFirstSplitsInEveryAccount(): Promise { failedAccounts.push(accountId); - logger.warn(`firstSplit:clearAll failed for account ${accountId}: ${(error as Error)?.message ?? error}`); + logger.warn(`firstSplit:clearAll failed for account ${accountLogLabel(accountId)}: ${failureCause(error)}`); }; const add = (counts: FirstSplitClearCounts): void => { cleared += counts.removed; @@ -189,7 +192,7 @@ export function registerAIHandlers(): void { const emails = await storage.getEmailsByDynamicCategory(category, { limit, offset, folderId }); return { success: true, data: emails }; } catch (error) { - logger.error('AI getByCategory error:', error); + logger.error('AI getByCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } } @@ -204,7 +207,7 @@ export function registerAIHandlers(): void { const counts = storage.getDynamicCategoryCounts(folderId, mode); return { success: true, data: counts }; } catch (error) { - logger.error('AI getCategoryCounts error:', error); + logger.error('AI getCategoryCounts error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -218,7 +221,7 @@ export function registerAIHandlers(): void { const defs = storage.getCategoryDefinitions(); return { success: true, data: defs }; } catch (error) { - logger.error('AI getCategoryDefinitions error:', error); + logger.error('AI getCategoryDefinitions error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -246,7 +249,7 @@ export function registerAIHandlers(): void { } return { success: true, data: merged }; } catch (error) { - logger.error('AI getEmailCategoriesBatch error:', error); + logger.error('AI getEmailCategoriesBatch error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -266,7 +269,7 @@ export function registerAIHandlers(): void { void onCategoryDefinitionUpserted(oldName, def?.name); return { success: true }; } catch (error) { - logger.error('AI upsertCategoryDefinition error:', error); + logger.error('AI upsertCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -280,7 +283,7 @@ export function registerAIHandlers(): void { const deleted = storage.deleteCategoryDefinition(slug); return { success: true, data: { deleted } }; } catch (error) { - logger.error('AI deleteCategoryDefinition error:', error); + logger.error('AI deleteCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -294,7 +297,7 @@ export function registerAIHandlers(): void { storage.toggleCategoryDefinition(slug, enabled); return { success: true }; } catch (error) { - logger.error('AI toggleCategoryDefinition error:', error); + logger.error('AI toggleCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -308,7 +311,7 @@ export function registerAIHandlers(): void { const summary = await storage.getThreadSummary(threadId); return { success: true, data: summary }; } catch (error) { - logger.error('AI getThreadSummary error:', error); + logger.error('AI getThreadSummary error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -322,7 +325,7 @@ export function registerAIHandlers(): void { await storage.upsertThreadSummary(summary); return { success: true }; } catch (error) { - logger.error('AI saveThreadSummary error:', error); + logger.error('AI saveThreadSummary error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -335,7 +338,7 @@ export function registerAIHandlers(): void { const storage = await requireAccountStorage(accountId); return { success: true, data: readFirstSplit(storage, threadId, !!options?.withSource) }; } catch (error) { - logger.warn(`firstSplit:get failed acct=${accountId} thread=${threadId}: ${(error as Error).message}`); + logger.warn(`firstSplit:get failed acct=${accountLogLabel(accountId)} thread=${threadId}: ${failureCause(error)}`); return { success: false, error: (error as Error).message }; } }, @@ -347,11 +350,11 @@ export function registerAIHandlers(): void { const storage = await requireAccountStorage(accountId); const result = storage.saveFirstSplit(request); if (result.reason === 'invalid') { - logger.warn(`firstSplit:save refused an invalid payload acct=${accountId} thread=${request?.key?.threadId ?? '?'} status=${request?.status ?? '?'}`); + logger.warn(`firstSplit:save refused an invalid payload acct=${accountLogLabel(accountId)} thread=${request?.key?.threadId ?? '?'} status=${request?.status ?? '?'}`); } return { success: true, data: result }; } catch (error) { - logger.warn(`firstSplit:save failed acct=${accountId} thread=${request?.key?.threadId ?? '?'}: ${(error as Error).message}`); + logger.warn(`firstSplit:save failed acct=${accountLogLabel(accountId)} thread=${request?.key?.threadId ?? '?'}: ${failureCause(error)}`); return { success: false, error: (error as Error).message }; } }); @@ -365,9 +368,8 @@ export function registerAIHandlers(): void { } catch (error) { // Only the registry read can throw here: which accounts exist is unknown, // so nothing may be reported as cleared. - const message = (error as Error)?.message ?? String(error); - logger.warn(`firstSplit:clearAll could not read the account list: ${message}`); - return { success: false, error: `Could not read the account list: ${message}` }; + logger.warn(`firstSplit:clearAll could not read the account list: ${failureCause(error)}`); + return { success: false, error: `Could not read the account list: ${(error as Error)?.message ?? String(error)}` }; } }); @@ -380,7 +382,7 @@ export function registerAIHandlers(): void { await storage.upsertEmailAICategory(category); return { success: true }; } catch (error) { - logger.error('AI saveCategory error:', error); + logger.error('AI saveCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -394,7 +396,7 @@ export function registerAIHandlers(): void { await storage.removeEmailAICategory(emailId); return { success: true }; } catch (error) { - logger.error('AI removeCategory error:', error); + logger.error('AI removeCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -408,7 +410,7 @@ export function registerAIHandlers(): void { const emails = await storage.getEmailsWithoutAICategory(limit); return { success: true, data: emails }; } catch (error) { - logger.error('AI getUnprocessedEmails error:', error); + logger.error('AI getUnprocessedEmails error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -422,7 +424,7 @@ export function registerAIHandlers(): void { const saved = storage.upsertCategoryBatch(categories); return { success: true, data: { saved } }; } catch (error) { - logger.error('AI saveCategoriesBatch error:', error); + logger.error('AI saveCategoriesBatch error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -436,7 +438,7 @@ export function registerAIHandlers(): void { const count = await storage.getUnprocessedEmailCount(limit, skipRead); return { success: true, data: count }; } catch (error) { - logger.error('AI getUnprocessedEmailCount error:', error); + logger.error('AI getUnprocessedEmailCount error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -484,7 +486,7 @@ export function registerAIHandlers(): void { try { return { success: true, data: { cap: setAutoBacklogCap(cap) } }; } catch (error) { - logger.error('AI setBacklogCap error:', error); + logger.error('AI setBacklogCap error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -531,7 +533,7 @@ export function registerAIHandlers(): void { const repo = (storage as any).getRepositories?.()?.prompts; return { success: true, data: repo?.list?.() || [] }; } catch (error) { - logger.error('AI listPromptTemplates error:', error); + logger.error('AI listPromptTemplates error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -546,7 +548,7 @@ export function registerAIHandlers(): void { const updated = repo?.update?.(id, content) || false; return { success: updated }; } catch (error) { - logger.error('AI updatePromptTemplate error:', error); + logger.error('AI updatePromptTemplate error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -558,7 +560,7 @@ export function registerAIHandlers(): void { const reset = repo?.reset?.(id) || false; return { success: reset }; } catch (error) { - logger.error('AI resetPromptTemplate error:', error); + logger.error('AI resetPromptTemplate error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -645,7 +647,7 @@ export function registerAIHandlers(): void { sortOrder: 'desc', }); - logger.info(`[AI Search] Found ${emails.length} results (folder=${folderPath || 'all'}, aiCategory=${searchQuery.aiCategory ? 'set' : 'none'})`); + logger.info(`[AI Search] Found ${emails.length} results (folder=${folderPath ? folderLogLabel(folderPath) : 'all'}, aiCategory=${searchQuery.aiCategory ? 'set' : 'none'})`); return { success: true, data: emails }; } catch (error) { // A full-text search error names the query's tokens: class and code only. diff --git a/apps/desktop/electron/ipc/contacts-handlers.ts b/apps/desktop/electron/ipc/contacts-handlers.ts index 8416d201..1ddd608a 100644 --- a/apps/desktop/electron/ipc/contacts-handlers.ts +++ b/apps/desktop/electron/ipc/contacts-handlers.ts @@ -4,7 +4,7 @@ * Handles contact management operations. */ -import { classifyDomainPhones, classifyDomainUrls, htmlMiningWindow, htmlToPlainText, isSentMailFolder, mineAttributedPhones, mineContactSignals, phoneDomainOf, parseAddresses, type SenderPhones, type SenderUrls, createLogger } from '@sarvinbox/core'; +import { folderLogLabel, accountLogLabel, classifyDomainPhones, classifyDomainUrls, htmlMiningWindow, htmlToPlainText, isSentMailFolder, mineAttributedPhones, mineContactSignals, phoneDomainOf, parseAddresses, type SenderPhones, type SenderUrls, createLogger } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { refreshContactClassifications } from '../services/contact-classification-service'; @@ -447,7 +447,7 @@ async function scanMailbox( // Report what was actually read, not the paging offset — a folder holding // one email used to log "500 emails" because `offset` jumps by batchSize. - logger.info(`[Contacts] ${label}: scanned folder "${folder.name}": ${inFolder} emails (${direction})`); + logger.info(`[Contacts] ${label}: scanned folder ${folderLogLabel(folder.path || folder.name)}: ${inFolder} emails (${direction})`); } // Write the tallied totals absolutely, so re-scanning converges instead of @@ -680,7 +680,7 @@ export function registerContactsHandlers(): void { } catch (err) { // One mailbox failing (a locked DB mid-sync, usually transient) must // not cost the scan every OTHER account's contacts. - logger.error(`[Contacts] Scan skipped mailbox ${accountId}:`, err); + logger.error(`[Contacts] Scan skipped mailbox ${accountLogLabel(accountId)}:`, err); } } diff --git a/apps/desktop/electron/ipc/draft-handlers.ts b/apps/desktop/electron/ipc/draft-handlers.ts index 5a05a44d..1a10c040 100644 --- a/apps/desktop/electron/ipc/draft-handlers.ts +++ b/apps/desktop/electron/ipc/draft-handlers.ts @@ -6,7 +6,7 @@ import { basename } from 'path'; -import { emailContentHash, errorDiagnostic, resolveStandardFolder, createLogger, messageIdKey, withFolderSelected } from '@sarvinbox/core'; +import { folderLogLabel, emailContentHash, errorDiagnostic, resolveStandardFolder, createLogger, messageIdKey, withFolderSelected } from '@sarvinbox/core'; import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, accountDraftRowSql, bodyLengthFromParam, cleanBodyExpression, rawBodyExpression, rawBodyForStorage, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, type IpcMainInvokeEvent } from 'electron'; @@ -421,7 +421,7 @@ export async function saveDraftToIMAP(draft: { draftLog('save:uid-update:error', { error: errorDiagnostic(e) }); } } - logger.info('[Drafts] Draft saved to IMAP', folderPath, messageId, 'uid', appendedUid); + logger.info('[Drafts] Draft saved to IMAP', folderLogLabel(folderPath), messageId, 'uid', appendedUid); } catch (err: any) { logger.error('[Drafts] IMAP append failed (local copy kept):', err); return { success: true, folderPath, messageId, error: `IMAP append failed: ${err?.message || err}` }; @@ -465,7 +465,7 @@ export async function writeLocalDraftRow(storage: ReturnType 0) { uid = uids[0]; } else { - logger.warn(`[Main] Message-ID ${msgId} not found in ${sourceFolder.path}, skipping IMAP ${mode}`); + logger.warn(`[Main] Message-ID ${msgId} not found in ${folderLogLabel(sourceFolder.path)}, skipping IMAP ${mode}`); return; } } finally { @@ -2089,7 +2089,7 @@ export function registerEmailHandlers(): void { const deletable = items.filter((i) => typeof i.uid === 'number' && i.uid > 0); failedIds.push(...items.filter((i) => !deletable.includes(i)).map((i) => i.id)); if (deletable.length < items.length) { - logger.warn(`[bulkAction] ${folderPath}: ${items.length - deletable.length} uid-less row(s) left in place for delete (no server UID — avoids a local/server mismatch)`); + logger.warn(`[bulkAction] ${folderLogLabel(folderPath)}: ${items.length - deletable.length} uid-less row(s) left in place for delete (no server UID — avoids a local/server mismatch)`); } // Permanent expunge ONLY when the source folder truly IS Trash (exact // classification, never a `path.includes('trash')` substring that @@ -2122,7 +2122,7 @@ export function registerEmailHandlers(): void { catch (error) { logger.error('[Main] Accepted bulk delete local cleanup failed:', error); } } else { if (isTrash && allowPermanent !== true) { - logger.warn(`[bulkAction] delete in ${folderPath}: permanent expunge NOT confirmed by renderer — moving to Trash instead (no silent data loss)`); + logger.warn(`[bulkAction] delete in ${folderLogLabel(folderPath)}: permanent expunge NOT confirmed by renderer — moving to Trash instead (no silent data loss)`); } // Find trash folder for local DB update (exact classification). const trashFolder = findFolderByType(allFolders as any, 'trash') as any; diff --git a/apps/desktop/electron/ipc/image-trust-handlers.ts b/apps/desktop/electron/ipc/image-trust-handlers.ts index 6f6c243d..dd606e85 100644 --- a/apps/desktop/electron/ipc/image-trust-handlers.ts +++ b/apps/desktop/electron/ipc/image-trust-handlers.ts @@ -11,7 +11,7 @@ * 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. */ -import { createLogger } from '@sarvinbox/core'; +import { accountLogLabel, createLogger } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { requireNamedOrActiveStorage } from '../services/account-target'; @@ -27,7 +27,7 @@ export function registerImageTrustHandlers(): void { await (await requireNamedOrActiveStorage(accountId)).allowSenderImages(address); return { success: true }; } catch (error) { - logger.warn(`images:allowSender failed for account ${accountId ?? '(active)'}: ${(error as Error)?.message ?? error}`); + logger.warn(`images:allowSender failed for account ${accountLogLabel(accountId, '(active)')}: ${(error as Error)?.message ?? error}`); return fail(error); } }); diff --git a/apps/desktop/electron/ipc/label-handlers.ts b/apps/desktop/electron/ipc/label-handlers.ts index bd561ef3..f98a32f3 100644 --- a/apps/desktop/electron/ipc/label-handlers.ts +++ b/apps/desktop/electron/ipc/label-handlers.ts @@ -6,7 +6,7 @@ * Local-only, like AI-category tags — no IMAP keyword sync. */ -import { createLogger, type LabelInput } from '@sarvinbox/core'; +import { failureCause, labelLogLabel, createLogger, type LabelInput } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { ensureAccountRuntime } from '../services/accounts-runtime'; @@ -61,10 +61,10 @@ export function registerLabelHandlers(): void { if (engine?.isConnected?.()) { syncedToServer = await engine.createServerLabel(name); } else { - logger.warn(`[labels] syncToServer requested for "${name}" but the account isn't connected — created local-only`); + logger.warn(`[labels] syncToServer requested for ${labelLogLabel(name)} but the account isn't connected — created local-only`); } } catch (e) { - logger.warn(`[labels] server CREATE for "${name}" failed — created local-only: ${(e as Error).message}`); + logger.warn(`[labels] server CREATE for ${labelLogLabel(name)} failed — created local-only: ${failureCause(e)}`); } } return { success: true, data: await storage.createLabel({ name, color: input.color }, syncedToServer) }; diff --git a/apps/desktop/electron/ipc/smtp-handlers.ts b/apps/desktop/electron/ipc/smtp-handlers.ts index 36fae5b8..d47bcab9 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 { 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, withFolderSelected, messageIdKey, parseAddresses, STARTTLS_UNAVAILABLE, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, bodyLengthFromParam, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, dialog } from 'electron'; @@ -744,7 +744,7 @@ export async function appendSentCopy( } else { await run((syncEngine as any).getClient()); } - logger.info('[SMTP] Sent copy appended (UID stamped by the next Sent sync)', sentPath, messageId); + logger.info('[SMTP] Sent copy appended (UID stamped by the next Sent sync)', folderLogLabel(sentPath), messageId); } /** diff --git a/apps/desktop/electron/ipc/sync-handlers.ts b/apps/desktop/electron/ipc/sync-handlers.ts index 2ba2af36..bc199411 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 { withTimeout, transportOptInsOf, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, STARTTLS_UNAVAILABLE } 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 { ipcMain } from 'electron'; import { identifyClient } from '../sentry'; @@ -259,14 +259,14 @@ async function reconcileFolderDrift( : polled; if (plan.reconcileFlags) { logger.info( - `[Accounts] flag drift in ${f.path} (server unseen ${st.unseen ?? 0}, ` + + `[Accounts] flag drift in ${folderLogLabel(f.path)} (server unseen ${st.unseen ?? 0}, ` + `modseq ${st.highestModseq ?? '-'} vs synced ${f.highestModseq ?? '-'}) — reconciling`, ); } else if (plan.recountFromRows) { // Named in the log: a badge that outlived its mail is invisible from the // outside, and this line is the only place it leaves a trace. logger.info( - `[Accounts] unread badge for ${f.path} disagrees with the server ` + + `[Accounts] unread badge for ${folderLogLabel(f.path)} disagrees with the server ` + `(stored ${f.unreadCount ?? 0} thread(s) vs server unseen ${st.unseen ?? 0}) — recounting from rows`, ); } @@ -297,7 +297,7 @@ async function reconcileFolderDrift( // renderer re-runs that folder's list query, not just the badges. notify: (path) => sendToWindow('folders:updated', { accountId, folderPath: path }), onError: (stage, path, error) => - logger.warn(`[Accounts] ${stage} reconcile failed for`, path, error.message), + logger.warn(`[Accounts] ${stage} reconcile failed for`, folderLogLabel(path), failureCause(error)), }); } catch { /* skip this folder */ } } @@ -394,7 +394,7 @@ export function registerSyncHandlers(): void { if (!getSyncEngine() && accountId && accountDbExists(accountId)) { await ensureAccountRuntime(accountId); setCurrentAccount(accountId); - logger.info(`[Main] imap:connect self-activated account ${accountId} (storage was uninitialized)`); + logger.info(`[Main] imap:connect self-activated account ${accountLogLabel(accountId)} (storage was uninitialized)`); } const syncEngine = requireSyncEngine(); const storage = getStorage(); @@ -416,7 +416,6 @@ export function registerSyncHandlers(): void { // Attribute every subsequent error/breadcrumb to this client + mailbox. // Set BEFORE connecting so a failed connect is also attributed correctly. identifyClient({ - email: config.username, provider: config.oauthProvider ?? 'imap', host: config.host, port: config.port, @@ -892,7 +891,7 @@ export function registerSyncHandlers(): void { const activeId = getCurrentAccountId(); const parkedMs = quotaBackoff.remainingMs(activeId); if (parkedMs > 0) { - logger.info(`[Main] resetAndReconnect skipped — quota back-off active for ${activeId} (server connection cap); ${Math.round(parkedMs / 1000)}s left`); + logger.info(`[Main] resetAndReconnect skipped — quota back-off active for ${accountLogLabel(activeId)} (server connection cap); ${Math.round(parkedMs / 1000)}s left`); return { success: true, data: { connected: syncEngine.isConnected() } }; } @@ -1196,7 +1195,7 @@ export function registerSyncHandlers(): void { const mode = await syncEngine.startRealTime(folderPath); if (mode) { - logger.info(`[Main] Real-time sync started using: ${mode} for ${folderPath}`); + logger.info(`[Main] Real-time sync started using: ${mode} for ${folderLogLabel(folderPath)}`); } return { success: true, data: !!mode, mode }; @@ -1345,9 +1344,9 @@ export function registerSyncHandlers(): void { registerIdleBridges(accountId, engine); try { const mode = await engine.startRealTime('INBOX'); - logger.info('[IDLE] backgroundSync re-armed IDLE (socket alive) for', accountId, '→', mode); + logger.info('[IDLE] backgroundSync re-armed IDLE (socket alive) for', accountLogLabel(accountId), '→', mode); } catch (e) { - logger.warn('[IDLE] backgroundSync IDLE re-arm failed for', accountId, (e as Error).message); + logger.warn('[IDLE] backgroundSync IDLE re-arm failed for', accountLogLabel(accountId), (e as Error).message); } return { success: true, data: { unread: await totalUnread(rt.storage), live: true, reidled: true } }; } @@ -1382,7 +1381,7 @@ export function registerSyncHandlers(): void { // that config for auto-reconnect to hammer). Skip this cycle; the next // background tick retries once the vault is readable. if (cfg.authMethod !== 'oauth2' && !cfg.password) { - logger.warn(`[Accounts] backgroundSync: no password available yet for ${accountId} — skipping connect this cycle`); + logger.warn(`[Accounts] backgroundSync: no password available yet for ${accountLogLabel(accountId)} — skipping connect this cycle`); return { success: false, error: 'Credentials not ready', retryable: true }; } const dialConfig = attachImapBearer(cfg); @@ -1414,7 +1413,7 @@ export function registerSyncHandlers(): void { 'Background sync timed out', ); } catch (e) { - logger.warn('[Accounts] background INBOX catch-up sync failed (going LIVE anyway) for', accountId, (e as Error).message); + logger.warn('[Accounts] background INBOX catch-up sync failed (going LIVE anyway) for', accountLogLabel(accountId), (e as Error).message); } // STATUS-then-reconcile sweep across this account's non-INBOX folders (fresh @@ -1423,7 +1422,7 @@ export function registerSyncHandlers(): void { try { await reconcileFolderDrift(engine, rt.storage, accountId); } catch (e) { - logger.warn('[Accounts] STATUS sweep failed for', accountId, (e as Error).message); + logger.warn('[Accounts] STATUS sweep failed for', accountLogLabel(accountId), (e as Error).message); } // Go LIVE: tagged IDLE bridges + real-time push. Idempotent. @@ -1434,9 +1433,9 @@ export function registerSyncHandlers(): void { retryPipelineInitOnConnect(); try { const mode = await engine.startRealTime('INBOX'); - logger.info('[IDLE] backgroundSync startRealTime for', accountId, '→ mode:', mode); + logger.info('[IDLE] backgroundSync startRealTime for', accountLogLabel(accountId), '→ mode:', mode); } catch (e) { - logger.warn('[IDLE] startRealTime FAILED for', accountId, (e as Error).message); + logger.warn('[IDLE] startRealTime FAILED for', accountLogLabel(accountId), (e as Error).message); } return { success: true, data: { unread: await totalUnread(rt.storage) } }; @@ -1455,14 +1454,14 @@ export function registerSyncHandlers(): void { // saturated cap, which prolongs the lockout and risks a real rate-limit. const parked = quotaBackoff.parkOnError(accountId, error); if (parked.reason === 'quota') { - logger.warn(`[Accounts] backgroundSync: quota hit for ${accountId} (too many connections) — backing off ${Math.round(parked.backoffMs / 1000)}s (attempt ${parked.attempt})`); + logger.warn(`[Accounts] backgroundSync: quota hit for ${accountLogLabel(accountId)} (too many connections) — backing off ${Math.round(parked.backoffMs / 1000)}s (attempt ${parked.attempt})`); return { success: false, error: (error as Error).message, quotaExceeded: true }; } if (parked.reason === 'timeout') { - logger.warn(`[Accounts] backgroundSync: connect timed out for ${accountId} — backing off ${Math.round(parked.backoffMs / 60000)}m`); + logger.warn(`[Accounts] backgroundSync: connect timed out for ${accountLogLabel(accountId)} — backing off ${Math.round(parked.backoffMs / 60000)}m`); return { success: false, error: (error as Error).message }; } - logger.warn('[Accounts] backgroundSync failed for', accountId, (error as Error).message); + 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/main.ts b/apps/desktop/electron/main.ts index 06b3d65f..d71f0592 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -17,7 +17,7 @@ import netModule from 'net'; import { join } from 'path'; import { pathToFileURL } from 'url'; -import { SyncEngine, ExtensionManager, createLogger, errorDiagnostic, getEventBus, getLogLevel, setLogLevel, isConnectionError, raiseAutoSelectFamilyAttemptTimeout } from '@sarvinbox/core'; +import { accountLogLabel, SyncEngine, ExtensionManager, createLogger, errorDiagnostic, getEventBus, getLogLevel, setLogLevel, isConnectionError, raiseAutoSelectFamilyAttemptTimeout } from '@sarvinbox/core'; import { SQLiteStorage } from '@sarvinbox/storage-node'; import { app, BrowserWindow, Menu, dialog, ipcMain, powerMonitor, protocol, session, shell } from 'electron'; @@ -158,6 +158,7 @@ import { devServerUrlFor, isDevBuild, isReleaseBundle } from './utils/dev-mode'; import { initFileLogger, flushFileLogger, muteTerminalOutput, appendExternalLog } from './utils/file-logger'; import { installIpcSenderGuard } from './utils/ipc-sender-guard'; import { loadDotEnv, defaultDotEnvPaths } from './utils/load-env'; +import { logPath } from './utils/log-path'; import { mainWindowWebPreferences } from './utils/main-window-preferences'; import { installNavigationGuards } from './utils/navigation-guards'; import { installPermissionPolicy } from './utils/permission-policy'; @@ -638,7 +639,7 @@ async function initializeStorage(): Promise { send: sendToWindow, accountId: () => getAccountIdForStorage(storage), }); - logger.info('[Main] Storage initialized:', dbPath); + logger.info('[Main] Storage initialized:', logPath(dbPath)); } /** @@ -754,14 +755,14 @@ async function initializeAccountRegistry(): Promise { // 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:', 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); rebindOutboxStorage(); - logger.info('[Main] Auto-activated persisted account:', activeId); + logger.info('[Main] Auto-activated persisted account:', accountLogLabel(activeId)); } catch (e) { logger.warn('[Main] Auto-activate persisted account failed:', (e as Error)?.message); } diff --git a/apps/desktop/electron/sentry.ts b/apps/desktop/electron/sentry.ts index 784aa016..c2d25e5a 100644 --- a/apps/desktop/electron/sentry.ts +++ b/apps/desktop/electron/sentry.ts @@ -33,7 +33,6 @@ * repo-root .env. A Sentry DSN is public by design (safe to embed in a shipped * client). With no DSN configured, Sentry stays completely inert. */ -import { createHash } from 'crypto'; import { rmSync } from 'fs'; import { join } from 'path'; @@ -42,7 +41,7 @@ import { setSlowQueryReporter, type SlowQueryEvent } from '@sarvinbox/storage-no import * as Sentry from '@sentry/electron/main'; import { app } from 'electron'; -import { readCrashReportChoice, writeCrashReportChoice, type CrashReportChoice } from './services/crash-report-pref'; +import { crashReportInstallId, readCrashReportChoice, writeCrashReportChoice, type CrashReportChoice } from './services/crash-report-pref'; let sentryEnabled = false; /** @@ -271,6 +270,11 @@ export function initSentryMain(): void { sentryEnabled = true; + // Which installation a report came from: a random id, never anything derived + // from the user's address (see crashReportInstallId). Nothing is sent + // without a yes, whatever is set here. + Sentry.setUser({ id: crashReportInstallId() }); + // Tag runtime versions/platform so we can slice issues by build & OS. The // OS/device/electron contexts are added automatically by @sentry/electron; // these are the app-specific bits worth filtering on. @@ -313,27 +317,22 @@ export function initSentryMain(): void { } /** - * Identify which client an event came from, and tag the mailbox it was talking - * to. Called on every successful IMAP connect. No-op when Sentry is disabled. + * Tag the mailbox server an event's client was talking to. Called on every + * IMAP connect. No-op when Sentry is disabled. * - * We DON'T send the raw email address (PII). Instead the user id is a stable, - * one-way hash of the email — it still groups a given client's events together - * for support, but the address itself never leaves the machine. Provider + host - * are infrastructure identifiers (not personal) and are kept for triage. + * Takes no address: the report's user is the installation's random id, set + * once at init (see crashReportInstallId). It used to be a hash of the + * address, which a guess at the address confirms. Provider + host are + * infrastructure identifiers (not personal) and are kept for triage. */ export function identifyClient(params: { - email?: string; provider?: string; host?: string; port?: number; }): void { if (!sentryEnabled) return; - const { email, provider, host, port } = params; + const { provider, host, port } = params; - if (email) { - const id = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16); - Sentry.setUser({ id }); - } if (provider) Sentry.setTag('imap.provider', provider); if (host) Sentry.setTag('imap.host', host); Sentry.setContext('imap', { diff --git a/apps/desktop/electron/services/accounts-registry.ts b/apps/desktop/electron/services/accounts-registry.ts index 9cc04dec..cd053e45 100644 --- a/apps/desktop/electron/services/accounts-registry.ts +++ b/apps/desktop/electron/services/accounts-registry.ts @@ -15,10 +15,9 @@ import { existsSync, unlinkSync } from 'fs'; import { join } from 'path'; -import { accountIdFor, oauthImapPreset, createLogger, type OAuthProviderId } from '@sarvinbox/core'; +import { accountLogLabel, accountIdFor, oauthImapPreset, createLogger, type OAuthProviderId } from '@sarvinbox/core'; import { app } from 'electron'; - import { getAccountIdForStorage } from '../shared'; import { loadPrimaryAccountId } from './accounts-runtime'; @@ -313,7 +312,7 @@ export async function seedAccountRegistryFromDurableStores(): Promise { smtpConfigured: false, }); existing.add(id); - logger.info('[Registry] seeded account from imap-account store:', id); + logger.info('[Registry] seeded account from imap-account store:', accountLogLabel(id)); } } } catch (e) { @@ -344,7 +343,7 @@ export async function seedAccountRegistryFromDurableStores(): Promise { smtpConfigured: false, }); existing.add(id); - logger.info(`[Registry] seeded OAuth account from oauth store: ${id} (${oa.provider})`); + logger.info(`[Registry] seeded OAuth account from oauth store: ${accountLogLabel(id)} (${oa.provider})`); } } catch (e) { logger.warn('[Registry] oauth store seed skipped:', (e as Error)?.message); diff --git a/apps/desktop/electron/services/accounts-runtime.ts b/apps/desktop/electron/services/accounts-runtime.ts index 78f7b98c..b5a1e249 100644 --- a/apps/desktop/electron/services/accounts-runtime.ts +++ b/apps/desktop/electron/services/accounts-runtime.ts @@ -13,15 +13,13 @@ import { createHash } from 'crypto'; import { existsSync, readdirSync, readFileSync, renameSync, unlinkSync, statSync, openSync, readSync, closeSync } from 'fs'; import { join } from 'path'; - -import { SyncEngine, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, failureCause, redactAccountIds, SyncEngine, createLogger } from '@sarvinbox/core'; 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 { logPath } from '../utils/log-path'; import { listRegistryAccounts } from './accounts-registry'; import { deleteAccountAttachments, rekeyAccountAttachments } from './attachment-cache'; @@ -114,7 +112,7 @@ export async function createAccountRuntime( // second account does not double the queries sent about the same sender. attachReputation(syncEngine); attachAutocrypt(syncEngine); - logger.info('[Accounts] Created runtime ->', dbPath); + logger.info('[Accounts] Created runtime ->', logPath(dbPath)); return { storage, syncEngine, smtpClient: null }; } @@ -237,7 +235,7 @@ export async function ensureAccountRuntime(accountId: string): Promise await rekeyAccountSecrets(oldId, newId); if (loadPrimaryAccountId() === oldId) savePrimaryAccountId(newId); rekeyRuntime(oldId, newId); - logger.info('[AccountMigration] rekeyed account', oldId, '->', newId); + logger.info('[AccountMigration] rekeyed account', accountLogLabel(oldId), '->', accountLogLabel(newId)); } // ===== Account removal (wipe local data) =================================== @@ -331,7 +329,7 @@ function deleteDbFiles(dbFullPath: string): void { try { if (existsSync(p)) unlinkSync(p); } catch (e) { - logger.warn('[Accounts] Failed to delete DB file', p, e); + logger.warn('[Accounts] Failed to delete DB file', logPath(p), failureCause(e)); } } } @@ -406,7 +404,7 @@ export async function deleteAccountData(accountId: string): Promise { try { await deleteAccountSecrets(accountId); } catch (e) { logger.warn('[Accounts] vault delete failed', e); } // Its cached attachments too (CASA M-7): they used to outlive the account. try { await deleteAccountAttachments(accountId); } catch (e) { logger.warn('[Accounts] attachment cache delete failed', e); } - logger.info('[Accounts] wiped account data', accountId, isPrimary ? '(primary/sarvinbox.db)' : `(${dbFile})`); + logger.info('[Accounts] wiped account data', accountLogLabel(accountId), isPrimary ? '(primary/sarvinbox.db)' : `(${dbFile})`); } finally { // The account is gone, but the id must not stay marked: re-adding the same // address later resolves to the same id, and it would be unopenable. @@ -493,7 +491,7 @@ export function cleanupOrphanedAccountDbs(opts?: { try { entries = readdirSync(dir); } catch (e) { - logger.warn('[Accounts] cleanup: could not read userData dir', e); + logger.warn('[Accounts] cleanup: could not read userData dir', failureCause(e)); return removed; } for (const name of entries) { @@ -508,7 +506,7 @@ export function cleanupOrphanedAccountDbs(opts?: { if (keepFiles && !keepFiles.has(name) && isStale(name)) { deleteDbFiles(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed orphaned hashed account DB:', name); + logger.info('[Accounts] removed orphaned hashed account DB:', redactAccountIds(name)); } continue; } @@ -519,12 +517,12 @@ export function cleanupOrphanedAccountDbs(opts?: { // file is far more likely to be a store added since this code was // written than a stale one. Leave it and say so. if (!LEGACY_ACCOUNT.test(name)) { - logger.warn('[Accounts] cleanup: keeping unrecognised DB file (not an account DB):', name); + logger.warn('[Accounts] cleanup: keeping unrecognised DB file (not an account DB):', redactAccountIds(name)); continue; } deleteDbFiles(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed orphaned legacy DB:', name); + logger.info('[Accounts] removed orphaned legacy DB:', redactAccountIds(name)); continue; } // Oldest scheme: per-account DB named by the RAW account id with no @@ -535,9 +533,9 @@ export function cleanupOrphanedAccountDbs(opts?: { try { unlinkSync(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed legacy plaintext account DB:', name); + logger.info('[Accounts] removed legacy plaintext account DB:', redactAccountIds(name)); } catch (e) { - logger.warn('[Accounts] could not remove legacy plaintext DB', name, e); + logger.warn('[Accounts] could not remove legacy plaintext DB', redactAccountIds(name), failureCause(e)); } } } @@ -569,7 +567,7 @@ export function cleanupStaleUserDataArtifacts(): string[] { unlinkSync(p); removed.push(name); } catch (e) { - logger.warn('[Accounts] could not remove stale artifact', name, (e as Error).message); + logger.warn('[Accounts] could not remove stale artifact', redactAccountIds(name), failureCause(e)); } }; @@ -583,7 +581,7 @@ export function cleanupStaleUserDataArtifacts(): string[] { } } catch { /* dir unreadable — nothing to do */ } - if (removed.length) logger.info('[Accounts] removed stale artifacts:', removed.join(', ')); + if (removed.length) logger.info('[Accounts] removed stale artifacts:', redactAccountIds(removed.join(', '))); return removed; } diff --git a/apps/desktop/electron/services/ai-categorization-service.ts b/apps/desktop/electron/services/ai-categorization-service.ts index cd20b66e..1a633e79 100644 --- a/apps/desktop/electron/services/ai-categorization-service.ts +++ b/apps/desktop/electron/services/ai-categorization-service.ts @@ -7,7 +7,7 @@ * Runs entirely in the Electron main process for reliability. */ -import { parseLLMJsonArray, valueShapeForLog, cleanEmailHtmlForLLM, errorDiagnostic, failureCause, isConnectionError, isUpstreamError, describeNetworkError, classifyAIError, createLogger, applySecurityGate, buildSecurityContext, formatSecurityLines, buildCategorizationPrompt, buildAIAuthHeaders, buildAIChatRequestOptions, effectiveAIBaseUrl, aiApiKeyHeaders, existingCategoryClassification, automaticCategorizationDeferred, isSpamProtectedEmail, formatSenderBehaviorFacts, SENDER_BEHAVIOR_UNAVAILABLE } from '@sarvinbox/core'; +import { categoryLogLabel, parseLLMJsonArray, valueShapeForLog, cleanEmailHtmlForLLM, errorDiagnostic, failureCause, isConnectionError, isUpstreamError, describeNetworkError, classifyAIError, createLogger, applySecurityGate, buildSecurityContext, formatSecurityLines, buildCategorizationPrompt, buildAIAuthHeaders, buildAIChatRequestOptions, effectiveAIBaseUrl, aiApiKeyHeaders, existingCategoryClassification, automaticCategorizationDeferred, isSpamProtectedEmail, formatSenderBehaviorFacts, SENDER_BEHAVIOR_UNAVAILABLE } from '@sarvinbox/core'; import type { EmailRecord , AIErrorInfo, EmailSecurityContext, SenderSignals } from '@sarvinbox/core'; import { getMainWindow, requireStorage } from '../shared'; @@ -186,6 +186,8 @@ export class AICategorizationService { private skipRead: boolean = true; private categoryDefs: LoadedCategoryDef[] = []; private categorySlugs: Set = new Set(); + /** The built-in categories' slugs: logged as written; the user's own are logged as labels. */ + private systemCategorySlugs: Set = new Set(['spam']); private autoTimer: ReturnType | null = null; private autoConfig: AIProviderConfig | null = null; private autoOptions: { userEmail?: string; maxEmails?: number; skipRead?: boolean } = {}; @@ -265,6 +267,7 @@ export class AICategorizationService { const defs = storage.getEnabledCategoryDefinitions(); this.categoryDefs = defs.map(d => ({ slug: d.slug, name: d.name, prompt: d.prompt })); this.categorySlugs = new Set(defs.map(d => d.slug)); + this.systemCategorySlugs = new Set(['spam', ...defs.filter(d => d.isSystem).map(d => d.slug)]); logger.info(`[AICategorizationService] Starting in ${mode} mode (skipRead=${this.skipRead}, maxEmails=${this.maxEmails}, categories=${this.categoryDefs.length})`); if (mode === 'bulk') { await this.processBulk(run); @@ -1171,7 +1174,8 @@ Return format (categories is an array of matching slugs from: ${categorySlugs}): for (const c of r.categories) acc[c] = (acc[c] || 0) + 1; return acc; }, {} as Record); - const categorySummary = Object.entries(categoryCounts).map(([k, v]) => `${k}:${v}`).join(' ') || 'none'; + // A category the user created is named after what they typed: its label, never its slug. + const categorySummary = Object.entries(categoryCounts).map(([k, v]) => `${categoryLogLabel(k, this.systemCategorySlugs)}:${v}`).join(' ') || 'none'; this.emitLog('info', `Saved ${saved} categorizations (${categorySummary})`); // Update progress with category breakdown and recent activity diff --git a/apps/desktop/electron/services/backfill-scheduler.ts b/apps/desktop/electron/services/backfill-scheduler.ts index 4ab9ea4e..c1cfb8b0 100644 --- a/apps/desktop/electron/services/backfill-scheduler.ts +++ b/apps/desktop/electron/services/backfill-scheduler.ts @@ -21,7 +21,7 @@ * - Idle tick: 30 min once every folder's backfill is complete */ -import { buildStandardFolderAliasMap, createLogger, getEventBus, isTrashFolder, isSpamFolder, isAllMailSuperset, LARGE_MAILBOX_THRESHOLD } from '@sarvinbox/core'; +import { failureCause, folderLogLabel, accountLogLabel, buildStandardFolderAliasMap, createLogger, getEventBus, isTrashFolder, isSpamFolder, isAllMailSuperset, LARGE_MAILBOX_THRESHOLD } from '@sarvinbox/core'; import { getStorage, getSyncEngine, getAllAccountRuntimes, getCurrentAccountId, sendToWindow } from '../shared'; @@ -352,10 +352,10 @@ async function maybeReconcileDeletions(storage: any, engine: any, folder: any): try { const r = await engine.reconcileFolderDeletionsFull(folder.path); if (r && r.deleted > 0) { - logger.info(`[Backfill] Deletion reconcile ${folder.path}: ${r.deleted} removed, ${r.updated} flags updated`); + logger.info(`[Backfill] Deletion reconcile ${folderLogLabel(folder.path)}: ${r.deleted} removed, ${r.updated} flags updated`); } } catch (e) { - logger.warn(`[Backfill] Deletion reconcile ${folder.path} failed (isolated): ${(e as Error).message}`); + logger.warn(`[Backfill] Deletion reconcile ${folderLogLabel(folder.path)} failed (isolated): ${failureCause(e)}`); } } @@ -395,7 +395,7 @@ async function runTick(): Promise { // connection self-heals and the next tick picks it up. if (isConnectionRecentlyUnstable(t.engine)) { drained = false; // still has work; just deferred until it settles - logger.info(`[Backfill] skipping ${t.accountId} — connection churning, letting it settle`); + logger.info(`[Backfill] skipping ${accountLogLabel(t.accountId)} — connection churning, letting it settle`); continue; } // One-time bulk backfill (idempotent, self-throttled, fire-and-forget) so diff --git a/apps/desktop/electron/services/body-reheal-scheduler.ts b/apps/desktop/electron/services/body-reheal-scheduler.ts index 157fcdcb..79d160e0 100644 --- a/apps/desktop/electron/services/body-reheal-scheduler.ts +++ b/apps/desktop/electron/services/body-reheal-scheduler.ts @@ -28,7 +28,7 @@ * entirely (never downloaded — the body-prefetch's job) and are dropped by a * cheap probe rather than spending the repair budget; see drainEmptyBodies. */ -import { createLogger, createLoopYielder, isDeferredFetchError, isFirstSplitCurrent, repairedCleanBody } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, createLoopYielder, isDeferredFetchError, isFirstSplitCurrent, repairedCleanBody } from '@sarvinbox/core'; import { areBodyLengthsReady, cleanBodyExpression, rawBodyExpression, rawBodyLengthExpression } from '@sarvinbox/storage-node'; import { getAllAccountRuntimes } from '../shared'; @@ -115,8 +115,8 @@ async function scanAccount(accountId: string, storage: any): Promise { queues.set(accountId, q); emptyQueues.set(accountId, emptyIds); scanned.add(accountId); - if (q.length > 0) logger.info(`Body re-heal: queued ${q.length} corrupted bodies for ${accountId}`); - if (emptyIds.length > 0) logger.info(`Body re-heal: queued ${emptyIds.length} empty clean bodies for local repair for ${accountId}`); + if (q.length > 0) logger.info(`Body re-heal: queued ${q.length} corrupted bodies for ${accountLogLabel(accountId)}`); + if (emptyIds.length > 0) logger.info(`Body re-heal: queued ${emptyIds.length} empty clean bodies for local repair for ${accountLogLabel(accountId)}`); } /** @@ -308,7 +308,7 @@ async function tick(): Promise { // stuck — never reached app.log. One line per account per 3 minutes, // and only when there was work, so it costs nothing and goes quiet. logger.info( - `Body re-heal ${accountId}: repaired ${repaired}, failed ${failed}, ${remaining} queued` + + `Body re-heal ${accountLogLabel(accountId)}: repaired ${repaired}, failed ${failed}, ${remaining} queued` + (skippedOffline ? ` (SKIPPED — account offline, ${skippedOffline} waiting)` : '') + ` | local rebuild ${local.repaired} repaired, ${local.skipped} unrepairable, ` + `${local.notDownloaded} body not downloaded yet, ${localRemaining} queued`, @@ -318,7 +318,7 @@ async function tick(): Promise { // Isolate one account's failure so the loop still covers the rest — at // WARN, because at debug a permanently-failing account looked identical // to one with nothing to do. - logger.warn(`Body re-heal: account ${accountId} tick failed: ${(error as Error).message}`); + logger.warn(`Body re-heal: account ${accountLogLabel(accountId)} tick failed: ${(error as Error).message}`); } } } catch (error) { diff --git a/apps/desktop/electron/services/bulk-backfill.ts b/apps/desktop/electron/services/bulk-backfill.ts index 64a48d62..e2eb1009 100644 --- a/apps/desktop/electron/services/bulk-backfill.ts +++ b/apps/desktop/electron/services/bulk-backfill.ts @@ -14,7 +14,7 @@ * conversations (tagging prevents FUTURE mis-merges; it doesn't retroactively split). */ -import { addTag, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, addTag, createLogger } from '@sarvinbox/core'; import { getMeta, setMeta } from './core-db'; @@ -98,9 +98,9 @@ export async function maybeBackfillBulk(storage: any, engine: any, accountId: st // Mark done only on a clean full pass — a mid-run disconnect throws and leaves // the flag unset so it resumes (re-classifying is idempotent) next launch. setMeta(key, String(Date.now())); - logger.info(`[BulkBackfill] ${accountId}: done — scanned ${scanned}, tagged ${tagged} bulk in ${Date.now() - t0}ms`); + logger.info(`[BulkBackfill] ${accountLogLabel(accountId)}: done — scanned ${scanned}, tagged ${tagged} bulk in ${Date.now() - t0}ms`); } catch (e) { - logger.warn(`[BulkBackfill] ${accountId}: interrupted (scanned ${scanned}, tagged ${tagged}) — will resume: ${(e as Error).message}`); + logger.warn(`[BulkBackfill] ${accountLogLabel(accountId)}: interrupted (scanned ${scanned}, tagged ${tagged}) — will resume: ${(e as Error).message}`); } finally { inFlight.delete(accountId); } diff --git a/apps/desktop/electron/services/calendar-mail-sync.ts b/apps/desktop/electron/services/calendar-mail-sync.ts index c25fb4cc..39cbf2f5 100644 --- a/apps/desktop/electron/services/calendar-mail-sync.ts +++ b/apps/desktop/electron/services/calendar-mail-sync.ts @@ -1,5 +1,5 @@ import { authenticationFailed } from '@sarv-in/mailguard'; -import { classifyFolder, createLogger, getEventBus, hasTag, sanitizeIcsText, type EmailRecord } from '@sarvinbox/core'; +import { accountLogLabel, classifyFolder, createLogger, getEventBus, hasTag, sanitizeIcsText, type EmailRecord } from '@sarvinbox/core'; import type Database from 'better-sqlite3'; import { findStorageForEmail, getAccountIdForStorage, getAllAccountRuntimes, getMainWindow, getSyncEngineFor } from '../shared'; @@ -94,7 +94,7 @@ export class CalendarMailSync { const state = error instanceof BlockedCalendarMail ? 'blocked' : error instanceof InvalidCalendarMail ? 'ignored' : 'pending'; this.database().prepare('UPDATE local_calendar_mail_work SET state=?,attempts=attempts+1,next_attempt=? WHERE account_id=? AND email_id=?') .run(state, this.clock() + Math.min(30 * 60_000, 30_000 * 2 ** Math.min(row.attempts, 6)), row.accountId, row.emailId); - log.debug('Calendar invitation deferred or ignored', row.accountId, row.emailId, error instanceof Error ? error.message : 'Unavailable'); + log.debug('Calendar invitation deferred or ignored', accountLogLabel(row.accountId), row.emailId, error instanceof Error ? error.message : 'Unavailable'); } } } finally { this.draining = false; } diff --git a/apps/desktop/electron/services/contact-enrichment-scheduler.ts b/apps/desktop/electron/services/contact-enrichment-scheduler.ts index f5b232af..75c69763 100644 --- a/apps/desktop/electron/services/contact-enrichment-scheduler.ts +++ b/apps/desktop/electron/services/contact-enrichment-scheduler.ts @@ -18,7 +18,7 @@ * renderer-side (2s between LLM calls). */ -import { getEventBus, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, getEventBus, createLogger } from '@sarvinbox/core'; import { getMainWindow, getStorage, getAllAccountRuntimes } from '../shared'; const logger = createLogger('contact-enrichment-scheduler'); @@ -279,7 +279,7 @@ async function runTick(manual = false): Promise { ...(excludeContactIds.length ? { excludeContactIds } : {}), }); } catch (e) { - logger.error(`[EnrichmentScheduler] list candidates failed (acct=${id ?? 'active'}):`, e); + logger.error(`[EnrichmentScheduler] list candidates failed (acct=${accountLogLabel(id, 'active')}):`, e); continue; } if (generation !== tickGeneration) return 0; @@ -294,7 +294,7 @@ async function runTick(manual = false): Promise { // Lock already held from the claim above; refresh the start time so the // stale-lock timeout measures from the actual dispatch, not the claim. batchStartedAt = Date.now(); - logger.info(`[EnrichmentScheduler] dispatching batch of ${candidates.length} contacts (acct=${id ?? 'active'})`); + logger.info(`[EnrichmentScheduler] dispatching batch of ${candidates.length} contacts (acct=${accountLogLabel(id, 'active')})`); activeBatch = { batchId: `${Date.now()}-${++batchSequence}`, contactIds: candidates.map((c) => c.id), diff --git a/apps/desktop/electron/services/conversation-extraction-scheduler.ts b/apps/desktop/electron/services/conversation-extraction-scheduler.ts index dd45ebd3..cc4ae9fd 100644 --- a/apps/desktop/electron/services/conversation-extraction-scheduler.ts +++ b/apps/desktop/electron/services/conversation-extraction-scheduler.ts @@ -36,6 +36,7 @@ */ import { + accountLogLabel, FIRST_SPLIT_MAX_ATTEMPTS, FIRST_SPLIT_VERSION, createLogger, @@ -148,7 +149,7 @@ async function nominateCandidates(): Promise { // again next pass. if (noEvidence.length > 0) retired += storage.skipFirstSplits(noEvidence, now); } catch (error) { - logger.warn(`nominate acct=${accountId} failed: ${(error as Error)?.message ?? error}`); + logger.warn(`nominate acct=${accountLogLabel(accountId)} failed: ${(error as Error)?.message ?? error}`); } } // The renderer re-nominates nothing it acted on, but a thread it cannot diff --git a/apps/desktop/electron/services/core-db.ts b/apps/desktop/electron/services/core-db.ts index 2150f1e1..53f04706 100644 --- a/apps/desktop/electron/services/core-db.ts +++ b/apps/desktop/electron/services/core-db.ts @@ -30,6 +30,7 @@ import { applyDbKey } from '@sarvinbox/storage-node/db-encryption'; import Database from 'better-sqlite3'; import { app } from 'electron'; +import { logPath } from '../utils/log-path'; import { getDbEncryptionKey } from './db-key-store'; @@ -83,7 +84,7 @@ export function getCoreDb(): Database.Database { ); `); db = handle; - logger.info('[CoreDB] opened', dbPath); + logger.info('[CoreDB] opened', logPath(dbPath)); return db; } diff --git a/apps/desktop/electron/services/crash-report-pref.ts b/apps/desktop/electron/services/crash-report-pref.ts index 854f2d00..f707bbfc 100644 --- a/apps/desktop/electron/services/crash-report-pref.ts +++ b/apps/desktop/electron/services/crash-report-pref.ts @@ -7,12 +7,15 @@ * module load in main.ts, before storage exists (and the DB may be what is * crashing), so the preference must be readable synchronously that early. */ +import { randomUUID } from 'crypto'; import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; +import { readRegularFileSync, writePrivateFileAtomicSync } from '@sarvinbox/core'; import { app } from 'electron'; const FILE = 'crash-reports.json'; +const ID_FILE = 'crash-report-id'; /** * The user's answer. `unasked` means no answer yet: nothing is sent, and the @@ -52,3 +55,32 @@ export function readCrashReportChoice(): CrashReportChoice { export function writeCrashReportChoice(choice: CrashReportAnswer): void { writeFileSync(prefPath(), `${JSON.stringify({ choice })}\n`, { encoding: 'utf8', mode: 0o600 }); } + +// A random UUID (v4), lower-case, nothing else. +const INSTALL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +/** + * The id crash reports from this installation carry, so reports from one + * computer group together: a random UUID made on first use and kept in its + * own file in userData. Random, so it is derived from nothing — it used to be + * a truncated SHA-256 of the account's address, which anyone holding a guess + * at the address could confirm, and which changed with whichever account + * connected last. The same for every account on this computer. + * + * A missing, unreadable or malformed file gets a new id (written owner-only, + * whole or not at all). If even that write fails, the new id is used for this + * run only: a fresh id each launch splits one computer's reports apart, which + * is better than tying them to anything about the user. + */ +export function crashReportInstallId(): string { + const path = join(app.getPath('userData'), ID_FILE); + try { + const saved = readRegularFileSync(path, { minBytes: 36, maxBytes: 64 }).toString('utf8').trim(); + if (INSTALL_ID.test(saved)) return saved; + } catch { /* missing or unreadable: make one */ } + const id = randomUUID(); + try { + writePrivateFileAtomicSync(path, `${id}\n`); + } catch { /* this run only */ } + return id; +} diff --git a/apps/desktop/electron/services/db-compact.ts b/apps/desktop/electron/services/db-compact.ts index 7bc7cbae..da7bf6dd 100644 --- a/apps/desktop/electron/services/db-compact.ts +++ b/apps/desktop/electron/services/db-compact.ts @@ -27,6 +27,7 @@ import { join } from 'node:path'; import { Worker } from 'node:worker_threads'; import { + accountLogLabel, compactionEstimate, formatBytes, hasCompactionHeadroom, @@ -37,7 +38,6 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; - import { getAccountRuntime } from '../shared'; import type { CompactWorkerResult } from '../workers/db-compact.worker'; @@ -118,7 +118,7 @@ export function estimateCompaction(accountId: string): CompactionReport | null { const estimate = compactionEstimate(storage.getPageStats()); return { accountId, ...estimate, worthwhile: isCompactionWorthwhile(estimate) }; } catch (error) { - logger.warn(`[Compact] could not read page stats for ${accountId}`, error); + logger.warn(`[Compact] could not read page stats for ${accountLogLabel(accountId)}`, error); return null; } } @@ -212,7 +212,7 @@ export async function compactAccountDatabase(accountId: string): Promise ${formatBytes(after.fileBytes)}, ` + `${result.rowsAfter ?? '?'} emails, auto_vacuum=${result.autoVacuum}`, ); @@ -248,7 +248,7 @@ export async function compactAccountDatabase(accountId: string): Promise 0) { logger.info( `${extensionId} changed ${email.id}: ` + - `+[${(changes.add ?? []).join(',')}] -[${(changes.remove ?? []).join(',')}]` + `+[${(changes.add ?? []).map(labelLogLabel).join(',')}] -[${(changes.remove ?? []).map(labelLogLabel).join(',')}]` ); } }, diff --git a/apps/desktop/electron/services/extension-marketplace.ts b/apps/desktop/electron/services/extension-marketplace.ts index 8a2d0ece..b59487c9 100644 --- a/apps/desktop/electron/services/extension-marketplace.ts +++ b/apps/desktop/electron/services/extension-marketplace.ts @@ -39,6 +39,7 @@ import { MAX_DOWNLOAD_BYTES, buildCatalog, createLogger, + errorDiagnostic, isNewerCompatibleRelease, isTrustedRegistryUrl, mergeRegistries, @@ -57,6 +58,7 @@ import { app } from 'electron'; import * as tar from 'tar'; import { getExtensionManager } from '../shared'; +import { logPath } from '../utils/log-path'; import { isAllowedArchiveEntry } from './extension-archive-rules.mjs'; import { chromiumFetch } from './net-fetch'; @@ -253,7 +255,7 @@ export function getExtensionsConfig(): ParsedExtensionsConfig { try { raw = JSON.parse(fs.readFileSync(configPath(), 'utf-8')); } catch (error) { - logger.warn(`Could not read ${configPath()}; using defaults:`, error); + logger.warn(`Could not read ${logPath(configPath())}; using defaults:`, errorDiagnostic(error)); } config = parseExtensionsConfig(raw); for (const warning of config.warnings) logger.warn(`extensions.config.json: ${warning}`); diff --git a/apps/desktop/electron/services/extension-workflow-runner.ts b/apps/desktop/electron/services/extension-workflow-runner.ts index ebf2a0e4..5705e0b5 100644 --- a/apps/desktop/electron/services/extension-workflow-runner.ts +++ b/apps/desktop/electron/services/extension-workflow-runner.ts @@ -25,6 +25,7 @@ */ import { + accountLogLabel, createLoopYielder, createLogger, extensionDebugEnabled, @@ -162,7 +163,7 @@ async function runOne(message: QueuedMessage): Promise { if (DEBUG_RUNNER) { logger.debug( - `${message.stage} ${email.id} acct=${getAccountIdForStorage(storage) ?? 'active'} ` + + `${message.stage} ${email.id} acct=${accountLogLabel(getAccountIdForStorage(storage), 'active')} ` + `workflows=${results.size} tags=${plan.changed ? plan.tags : 'unchanged'}` ); } diff --git a/apps/desktop/electron/services/follow-up-checker.ts b/apps/desktop/electron/services/follow-up-checker.ts index 29685897..594c209a 100644 --- a/apps/desktop/electron/services/follow-up-checker.ts +++ b/apps/desktop/electron/services/follow-up-checker.ts @@ -7,7 +7,7 @@ * just the active one, so a reminder on a background account still fires. */ -import { createLogger, type FollowUp, type FollowUpStatus } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, type FollowUp, type FollowUpStatus } from '@sarvinbox/core'; import { getAllAccountIds, getMainWindow, getStorage, getStorageFor } from '../shared'; @@ -59,7 +59,7 @@ export async function checkFollowUpsForAccount( else replied += 1; } } catch (error) { - logger.warn(`[FollowUp] Check failed for account ${accountId}:`, error); + logger.warn(`[FollowUp] Check failed for account ${accountLogLabel(accountId)}:`, error); } return { due, replied }; } diff --git a/apps/desktop/electron/services/gmail-label-api.ts b/apps/desktop/electron/services/gmail-label-api.ts index b00123e4..8be1a8d6 100644 --- a/apps/desktop/electron/services/gmail-label-api.ts +++ b/apps/desktop/electron/services/gmail-label-api.ts @@ -1,4 +1,4 @@ -import { createLogger } from '@sarvinbox/core'; +import { failureCause, labelLogLabel, createLogger } from '@sarvinbox/core'; const logger = createLogger('gmail-label-api'); /** * Gmail label COLOR via the Gmail REST API. Used ONLY for Gmail accounts @@ -112,22 +112,22 @@ export async function ensureGmailLabelColor(token: string, name: string, hex?: s // Gmail API calls when provisioning runs more than once. const cur = existing.color || {}; if (cur.backgroundColor === color.backgroundColor && cur.textColor === color.textColor) return false; - try { await api(token, 'PATCH', `/${existing.id}`, { color }); logger.info(`[GmailLabels] colored "${name}"`); return true; } - catch (e) { logger.warn(`[GmailLabels] color PATCH "${name}" failed:`, (e as Error).message); return false; } + try { await api(token, 'PATCH', `/${existing.id}`, { color }); logger.info(`[GmailLabels] colored ${labelLogLabel(name)}`); return true; } + catch (e) { logger.warn(`[GmailLabels] color PATCH ${labelLogLabel(name)} failed:`, failureCause(e)); return false; } } const base = { name, labelListVisibility: 'labelShow', messageListVisibility: 'show' }; try { await api(token, 'POST', '', color ? { ...base, color } : base); - logger.info(`[GmailLabels] created "${name}"${color ? ' (colored)' : ''}`); + logger.info(`[GmailLabels] created ${labelLogLabel(name)}${color ? ' (colored)' : ''}`); return true; } catch (e) { - logger.warn(`[GmailLabels] create "${name}" with color failed:`, (e as Error).message); - try { await api(token, 'POST', '', base); logger.info(`[GmailLabels] created "${name}" (plain — color rejected)`); return true; } - catch (e2) { logger.warn(`[GmailLabels] create "${name}" plain failed:`, (e2 as Error).message); return false; } + logger.warn(`[GmailLabels] create ${labelLogLabel(name)} with color failed:`, failureCause(e)); + try { await api(token, 'POST', '', base); logger.info(`[GmailLabels] created ${labelLogLabel(name)} (plain — color rejected)`); return true; } + catch (e2) { logger.warn(`[GmailLabels] create ${labelLogLabel(name)} plain failed:`, failureCause(e2)); return false; } } } catch (e) { - logger.warn(`[GmailLabels] ensure "${name}" failed:`, (e as Error).message); + logger.warn(`[GmailLabels] ensure ${labelLogLabel(name)} failed:`, failureCause(e)); return false; } } @@ -141,7 +141,7 @@ export async function renameGmailLabel(token: string, oldName: string, newName: if (!existing) return; await api(token, 'PATCH', `/${existing.id}`, { name: newName }).catch(() => { /* target may already exist */ }); } catch (e) { - logger.warn('[GmailLabels] rename best-effort failed:', (e as Error).message); + logger.warn('[GmailLabels] rename best-effort failed:', failureCause(e)); } } @@ -161,7 +161,7 @@ export async function deleteGmailLabelsUnder(token: string, prefix: string): Pro } return n; } catch (e) { - logger.warn('[GmailLabels] delete-under best-effort failed:', (e as Error).message); + logger.warn('[GmailLabels] delete-under best-effort failed:', failureCause(e)); return 0; } } diff --git a/apps/desktop/electron/services/notification-service.ts b/apps/desktop/electron/services/notification-service.ts index 7b7365cf..bc748dcb 100644 --- a/apps/desktop/electron/services/notification-service.ts +++ b/apps/desktop/electron/services/notification-service.ts @@ -132,7 +132,7 @@ export function notifyNewMail(m: NewMailNotice): void { }; try { if (logger.isLevelEnabled('trace')) { - logger.trace(`[notifications] consider ${m.emailId} mode=${config.mode} cats=${m.categories ? `[${m.categories.join(',')}]` : 'none'} date=${m.date} from=${m.fromAddress}`); + logger.trace(`[notifications] consider ${m.emailId} mode=${config.mode} cats=${m.categories ? m.categories.length : 'none'} date=${m.date} from=${m.fromAddress}`); } if (config.mode === 'off') return drop('mode=off'); if (notified.has(m.emailId)) return drop('already notified'); diff --git a/apps/desktop/electron/services/oauth-service.ts b/apps/desktop/electron/services/oauth-service.ts index 5befaf36..72e19155 100644 --- a/apps/desktop/electron/services/oauth-service.ts +++ b/apps/desktop/electron/services/oauth-service.ts @@ -1184,6 +1184,9 @@ async function fetchUserInfo( ): Promise { const res = await fetch(provider.userInfoEndpoint, { headers: { Authorization: `Bearer ${accessToken}` }, + // Never followed: the access token rides on the request, and a redirect + // is not where the provider said its user-info endpoint is. + redirect: 'error', }); if (!res.ok) { throw new OAuthError(`userinfo failed (${res.status})`, 'USERINFO_FAILED'); diff --git a/apps/desktop/electron/services/outbox-service.ts b/apps/desktop/electron/services/outbox-service.ts index dc5c9ad5..a37e190c 100644 --- a/apps/desktop/electron/services/outbox-service.ts +++ b/apps/desktop/electron/services/outbox-service.ts @@ -15,6 +15,7 @@ */ import { + accountLogLabel, SendQueue, nextDrainDelayMs, type SendFn, @@ -215,7 +216,7 @@ export async function drainOutboxForAccount(accountId: string): Promise { await q.processQueue(); notifyOutboxChanged(); } catch (e) { - logger.error('[Outbox] Per-account drain failed:', accountId, e); + logger.error('[Outbox] Per-account drain failed:', accountLogLabel(accountId), e); } } diff --git a/apps/desktop/electron/services/sender-identity-service.ts b/apps/desktop/electron/services/sender-identity-service.ts index 9063a68c..62a52339 100644 --- a/apps/desktop/electron/services/sender-identity-service.ts +++ b/apps/desktop/electron/services/sender-identity-service.ts @@ -24,6 +24,7 @@ */ import { + failureCause, createLogger, DEFAULT_SENDER_IDENTITY_POLICY, discoverFavicon, @@ -85,7 +86,7 @@ export function setSenderIdentityPolicy(raw: unknown): SenderIdentityPolicy { try { setBlob(POLICY_BLOB_KEY, Buffer.from(JSON.stringify(cachedPolicy), 'utf8')); } catch (e) { - logger.warn(`[SenderIdentity] policy not persisted: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] policy not persisted: ${failureCause(e)}`); } return cachedPolicy; } @@ -388,14 +389,14 @@ export async function senderIdentityTick(svc: SenderIdentityService = getSenderI try { domains.push(...(await storage.getRecentSenderDomains(DOMAINS_PER_ACCOUNT))); } catch (e) { - logger.warn(`[SenderIdentity] could not list sender domains: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] could not list sender domains: ${failureCause(e)}`); } } const refreshed = await svc.refreshStale(domains, REFRESH_PER_TICK); if (refreshed > 0) logger.info(`[SenderIdentity] refreshed ${refreshed} domain(s)`); return refreshed; } catch (e) { - logger.warn(`[SenderIdentity] tick failed: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] tick failed: ${failureCause(e)}`); return 0; } finally { ticking = false; diff --git a/apps/desktop/electron/services/spam-reputation-service.ts b/apps/desktop/electron/services/spam-reputation-service.ts index 7e88b282..56f9604e 100644 --- a/apps/desktop/electron/services/spam-reputation-service.ts +++ b/apps/desktop/electron/services/spam-reputation-service.ts @@ -39,6 +39,8 @@ import { type RdapBootstrap, } from '@sarv-in/mailguard'; import { + failureCause, + folderLogLabel, SPAM_THRESHOLD, addTag, computeFilterActionResult, @@ -486,7 +488,7 @@ async function judgeRows( await target.storage.updateEmail(row.id, { tags: moved.tags, folderId: moved.folderId }); if (moved.changed && target.engine) { target.engine.moveToSpam(row.folderPath, row.uid).catch((err: unknown) => { - logger.warn(`[Reputation] server-side move failed for uid ${row.uid} in ${row.folderPath}: ${(err as Error)?.message ?? err}`); + logger.warn(`[Reputation] server-side move failed for uid ${row.uid} in ${folderLogLabel(row.folderPath)}: ${failureCause(err)}`); }); } summary.filed += 1; diff --git a/apps/desktop/electron/services/spam-verdict-repair.ts b/apps/desktop/electron/services/spam-verdict-repair.ts index be2a06d4..87c6bc25 100644 --- a/apps/desktop/electron/services/spam-verdict-repair.ts +++ b/apps/desktop/electron/services/spam-verdict-repair.ts @@ -36,6 +36,9 @@ * every later launch a single empty SELECT. */ import { + failureCause, + folderLogLabel, + accountLogLabel, bodyStage, createLogger, hasTag, @@ -135,7 +138,7 @@ export async function repairMessage( // move lands, and the queue persists it across a disconnect. if (moved && queue && email.uid > 0) { queue.move(moved.sourcePath, email.uid, moved.destPath).catch((err: unknown) => { - logger.warn(`[SpamRepair] server move failed for uid ${email.uid} in ${moved!.sourcePath}: ${(err as Error)?.message ?? err}`); + logger.warn(`[SpamRepair] server move failed for uid ${email.uid} in ${folderLogLabel(moved!.sourcePath)}: ${failureCause(err)}`); }); } return { rescored: update.spamScore !== undefined, unfiled }; @@ -197,7 +200,7 @@ async function run(): Promise { try { await repairAccount(storage, queue, accountId); } catch (e) { - logger.warn(`[SpamRepair] ${accountId}: repair failed (isolated): ${(e as Error).message}`); + logger.warn(`[SpamRepair] ${accountLogLabel(accountId)}: repair failed (isolated): ${(e as Error).message}`); } } } diff --git a/apps/desktop/electron/services/startup-thread-repair.ts b/apps/desktop/electron/services/startup-thread-repair.ts index 160ad382..c048945f 100644 --- a/apps/desktop/electron/services/startup-thread-repair.ts +++ b/apps/desktop/electron/services/startup-thread-repair.ts @@ -13,7 +13,7 @@ * tick so it's independent of that scheduler's tested behavior. */ -import { createLogger } from '@sarvinbox/core'; +import { accountLogLabel, createLogger } from '@sarvinbox/core'; import { getStorage, getSyncEngine, getAllAccountRuntimes, getCurrentAccountId } from '../shared'; @@ -102,13 +102,13 @@ async function handleAccount(storage: any, accountId: string): Promise { recordThreadRepairPass(accountId, t0); if (r) { const scope = sinceCreatedAt === undefined ? 'full' : 'incremental'; - logger.info(`[ThreadRepair] ${accountId}: ${scope}, ${r.emailsRetargeted} retargeted, ${r.threadsBefore}->${r.threadsAfter} threads, ${r.iterations} iter (${Date.now() - t0}ms)`); + logger.info(`[ThreadRepair] ${accountLogLabel(accountId)}: ${scope}, ${r.emailsRetargeted} retargeted, ${r.threadsBefore}->${r.threadsAfter} threads, ${r.iterations} iter (${Date.now() - t0}ms)`); } } catch (e) { // Leave it OUT of `done` (and unstamped) and clear the throttle so it retries // promptly on the next tick rather than waiting out REPAIR_INTERVAL_MS. lastRepairAt.delete(storage); - logger.warn(`[ThreadRepair] ${accountId} failed (will retry): ${(e as Error).message}`); + logger.warn(`[ThreadRepair] ${accountLogLabel(accountId)} failed (will retry): ${(e as Error).message}`); return; } diff --git a/apps/desktop/electron/services/unified-pipeline-service.ts b/apps/desktop/electron/services/unified-pipeline-service.ts index 22979154..dbfb0799 100644 --- a/apps/desktop/electron/services/unified-pipeline-service.ts +++ b/apps/desktop/electron/services/unified-pipeline-service.ts @@ -12,6 +12,11 @@ */ import { + errorDiagnostic, + failureCause, + categoryLogLabel, + folderLogLabel, + accountLogLabel, BehaviorIntelligence, LogAggregator, MAX_API_RETRIES, @@ -121,7 +126,7 @@ async function restorePersistedAIConfig(persisted: AIProviderConfig): Promise { - logger.warn(`[Pipeline] could not re-check the saved AI provider's sign-in: ${e.message}`); + logger.warn(`[Pipeline] could not re-check the saved AI provider's sign-in: ${failureCause(e)}`); }); } @@ -441,7 +446,8 @@ let aiConfigPushes = 0; function refuseAIConfig(error: AIEndpointRefusedError): void { aiConfig = null; lastAIErrorReason = error.message; - logger.warn(`[Pipeline] AI provider refused — background AI is off until it is fixed: ${error.message}`); + // The reason, not the message: the message describes the address it refused. + logger.warn(`[Pipeline] AI provider refused — background AI is off until it is fixed: ${error.reason}`); emitAiPipelineStatus(); reportAIEndpointRefused(error); } @@ -569,7 +575,7 @@ export async function disablePipelineAIIfProviderRemoved(): Promise { try { saved = oauthSignInOfAIConfig(loadPipelineAIConfigSync()); } catch (error) { - logger.warn(`[Pipeline] could not read the saved AI config: ${(error as Error).message}`); + logger.warn(`[Pipeline] could not read the saved AI config: ${failureCause(error)}`); } const liveGone = !!live && !(await getOAuthAccount(live.provider, live.email)); const savedGone = !!saved && !(await getOAuthAccount(saved.provider, saved.email)); @@ -759,7 +765,7 @@ export function initializeUnifiedPipeline( try { ensureBundledAgentPrompts((repos as any).prompts); } catch (err) { - logger.warn('[Pipeline] Failed to seed prompt templates:', err); + logger.warn('[Pipeline] Failed to seed prompt templates:', errorDiagnostic(err)); } // Create UnifiedPipeline @@ -808,7 +814,7 @@ export function initializeUnifiedPipeline( getPromptTemplate: (id: string) => { try { const promptRepo = (pRepos() as any)?.prompts; - return readBundledAgentPrompt(promptRepo, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', error)); + return readBundledAgentPrompt(promptRepo, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', errorDiagnostic(error))); } catch { return null; } }, @@ -887,7 +893,7 @@ export function initializeUnifiedPipeline( if (m > 0) logger.info(`[Pipeline] Built ${m} sender memories`); } } catch (e) { - logger.warn('[Pipeline] deferred initial learning failed:', (e as Error).message); + logger.warn('[Pipeline] deferred initial learning failed:', failureCause(e)); } }, 3000); initialLearnTimer.unref?.(); @@ -926,7 +932,7 @@ export function initializeUnifiedPipeline( const m = repos.agent.buildAllSenderMemories(email); if (m > 0) logger.info(`[Pipeline] Built ${m} sender memories`); } - } catch (e) { logger.error('[Pipeline] Backfill check error:', e); clearInterval(backfillCheck); } + } catch (e) { logger.error('[Pipeline] Backfill check error:', errorDiagnostic(e)); clearInterval(backfillCheck); } }, 10_000); } } @@ -988,7 +994,7 @@ export async function runPipeline1(emailId: string, storage: any = getStorage()) try { storage.getRepositories()?.agent?.markExtractionDone(emailId); } catch (error) { - logger.error(`[Pipeline] P1 error for ${emailId}:`, error); + logger.error(`[Pipeline] P1 error for ${emailId}:`, errorDiagnostic(error)); } } @@ -1044,7 +1050,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi priorityReasoning = score.reasoning; recommendedAction = score.recommendedAction || null; } catch (err) { - logger.error(`[Pipeline] Scoring error for ${emailId}:`, err); + logger.error(`[Pipeline] Scoring error for ${emailId}:`, errorDiagnostic(err)); } finally { activeProcessingStorage = prevProcessingStorage; } @@ -1132,7 +1138,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // disconnected engine / restart / burst can never strand it unlabeled. } } catch (err) { - logger.error(`[Pipeline] Categorization error for ${emailId}:`, err); + logger.error(`[Pipeline] Categorization error for ${emailId}:`, errorDiagnostic(err)); // Auth/credit terminal errors pause categorization globally + raise the // Fix banner. A per-email 4xx ('client', not paused) is a doomed request // for THIS message only — accept it (mark done, no categories) so we @@ -1292,7 +1298,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // 4. Auto-draft reply when pipeline proposes "reply" action if (proposed && (recommendedAction === 'reply' || recommendedAction === 'reply_all') && aiConfig) { autoDraftReply(emailId, storage).catch(err => - logger.error(`[Pipeline] Auto-draft failed for ${emailId}:`, err) + logger.error(`[Pipeline] Auto-draft failed for ${emailId}:`, errorDiagnostic(err)) ); } @@ -1316,7 +1322,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi }); } } catch (error) { - logger.error(`[Pipeline] P2 error for ${emailId}:`, error); + logger.error(`[Pipeline] P2 error for ${emailId}:`, errorDiagnostic(error)); } } @@ -1403,7 +1409,7 @@ function lateAutoDraftStop( try { reason = autoDraftSkipReason(storage, email); } catch (err) { - logger.warn(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — thread gates could not be checked:`, err); + logger.warn(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — thread gates could not be checked:`, errorDiagnostic(err)); return 'gates-unreadable'; } if (reason) logger.info(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — ${reason} (changed while drafting)`); @@ -1425,7 +1431,7 @@ async function settleLateAutoDraftStop( try { await agentRepo.updateDecisionStatus(decision.id, 'rejected', 'dismissed', USER_HAS_DRAFT_FEEDBACK); } catch (err) { - logger.warn(`[Pipeline] Could not resolve decision ${decision.id} as '${USER_HAS_DRAFT_FEEDBACK}':`, err); + logger.warn(`[Pipeline] Could not resolve decision ${decision.id} as '${USER_HAS_DRAFT_FEEDBACK}':`, errorDiagnostic(err)); } } @@ -1462,7 +1468,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( try { skip = autoDraftSkipReason(storage, email); } catch (err) { - logger.warn(`[Pipeline] Skip auto-draft for ${emailId} — thread gates could not be checked:`, err); + logger.warn(`[Pipeline] Skip auto-draft for ${emailId} — thread gates could not be checked:`, errorDiagnostic(err)); return; } if (skip === 'not-active-account') { @@ -1649,7 +1655,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( } } } catch (err) { - logger.warn('[Pipeline] Relationship gate check failed, continuing:', err); + logger.warn('[Pipeline] Relationship gate check failed, continuing:', errorDiagnostic(err)); } // The AI's `should_auto_draft` decision already weighed reply-worthiness, @@ -1724,7 +1730,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( getPromptTemplate: (id: 'agent_plan' | 'agent_draft') => { try { const r = (storage as any).getRepositories?.()?.prompts; - return readBundledAgentPrompt(r, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', error)); + return readBundledAgentPrompt(r, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', errorDiagnostic(error))); } catch { return null; } }, getNotes: (e: string) => agentRepo.getNotesForPrompt(e), @@ -1902,14 +1908,14 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( try { draftKeyRecorded = agentRepo.recordDecisionDraftMessageId(decision.id, draftMessageId); } catch (err) { - logger.warn(`[Pipeline] Could not record the draft Message-ID for decision ${decision.id}:`, err); + logger.warn(`[Pipeline] Could not record the draft Message-ID for decision ${decision.id}:`, errorDiagnostic(err)); } const forgetDraftKey = (): void => { if (!draftKeyRecorded) return; try { agentRepo.clearDecisionDraftMessageId(decision.id, draftMessageId); } catch (err) { - logger.warn(`[Pipeline] Could not clear the draft Message-ID for decision ${decision.id}:`, err); + logger.warn(`[Pipeline] Could not clear the draft Message-ID for decision ${decision.id}:`, errorDiagnostic(err)); } }; @@ -1946,7 +1952,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( 'draft saved to Drafts folder', ); } catch (err) { - logger.warn(`[Pipeline] Could not mark decision ${decision.id} as auto:`, err); + logger.warn(`[Pipeline] Could not mark decision ${decision.id} as auto:`, errorDiagnostic(err)); } // Log in the user_action_log timeline (source='agent_auto') so the // Activity Log tab shows the draft alongside auto-read / auto-archive @@ -1959,11 +1965,13 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( }); } else { forgetDraftKey(); - logger.warn(`[Pipeline] IMAP draft save failed for ${emailId}: ${result.error}`); + // Our own words only (what precedes the first colon): the rest of a + // save error can quote the server's answer or the encryption failure. + logger.warn(`[Pipeline] IMAP draft save failed for ${emailId}: ${String(result.error ?? 'no result').split(':')[0]}`); } } catch (err) { forgetDraftKey(); - logger.error(`[Pipeline] IMAP draft save error for ${emailId}:`, err); + logger.error(`[Pipeline] IMAP draft save error for ${emailId}:`, errorDiagnostic(err)); } // Notify renderer that draft is ready @@ -1976,7 +1984,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( }); } } catch (error) { - logger.error(`[Pipeline] Auto-draft error for ${emailId}:`, error); + logger.error(`[Pipeline] Auto-draft error for ${emailId}:`, errorDiagnostic(error)); } } @@ -2131,7 +2139,7 @@ async function tryAutoSendReply(params: { try { await appendSentCopy(result.rawMessage, result.messageId, sendOptions); } catch (err) { - logger.warn(`[Pipeline] Sent-folder append for auto-sent ${emailId} failed (non-fatal):`, (err as Error)?.message || err); + logger.warn(`[Pipeline] Sent-folder append for auto-sent ${emailId} failed (non-fatal):`, failureCause(err)); } } @@ -2146,7 +2154,7 @@ async function tryAutoSendReply(params: { REPLY_SENT_FEEDBACK, ); } catch (err) { - logger.warn(`[Pipeline] Could not mark decision ${decision.id} as sent:`, err); + logger.warn(`[Pipeline] Could not mark decision ${decision.id} as sent:`, errorDiagnostic(err)); } // Same activity-log surface as every other agent action (learning + @@ -2174,7 +2182,7 @@ async function tryAutoSendReply(params: { } return true; } catch (err) { - logger.error(`[Pipeline] Auto-send error for ${emailId} — falling back to Drafts:`, err); + logger.error(`[Pipeline] Auto-send error for ${emailId} — falling back to Drafts:`, errorDiagnostic(err)); return false; } } @@ -2213,7 +2221,7 @@ async function resolveGmailToken(accountId: string | null): Promise a.provider === 'gmail' && a.email?.toLowerCase() === email); @@ -2222,13 +2230,13 @@ async function resolveGmailToken(accountId: string | null): Promise { - logger.warn(`[Pipeline] resolveGmailToken: token fetch failed for ${grant.email}:`, e?.message || e); + logger.warn(`[Pipeline] resolveGmailToken: token fetch failed for ${grant.email}:`, failureCause(e)); return null; }); if (traceEnabled()) logger.trace(`[Pipeline] resolveGmailToken: token=${token ? 'yes' : 'no'} (${grant.email})`); return token; } catch (e) { - logger.warn('[Pipeline] resolveGmailToken error:', (e as Error).message); + logger.warn('[Pipeline] resolveGmailToken error:', failureCause(e)); return null; } } @@ -2297,7 +2305,7 @@ async function applyEmailLabels( if (stale.length) { if (canApply && !await canApply()) return 'superseded'; try { await queue.removeGmailLabels(folderPath, email.uid, stale); } - catch (e) { logger.warn('[Pipeline] stale Gmail label cleanup failed:', (e as Error).message); } + catch (e) { logger.warn('[Pipeline] stale Gmail label cleanup failed:', failureCause(e)); } } } @@ -2369,7 +2377,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu // label is re-applied later (next categorization / the backfill action). const engine: any = getSyncEngineForStorage(storage); if (!engine) { - logger.warn(`[Pipeline] mirror skipped acct=${acct} uid=${email.uid}: no engine for this account's storage (won't apply to a wrong account)`); + logger.warn(`[Pipeline] mirror skipped acct=${accountLogLabel(acct)} uid=${email.uid}: no engine for this account's storage (won't apply to a wrong account)`); return; } if (!engine.isConnected?.() || !engine.operationQueue) { @@ -2379,7 +2387,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu const folder = await storage.getFolder(email.folderId); if (!folder?.path) { - logger.info(`[Pipeline] mirror skipped acct=${acct} uid=${email.uid}: folder ${email.folderId} has no path`); + logger.info(`[Pipeline] mirror skipped acct=${accountLogLabel(acct)} uid=${email.uid}: folder ${email.folderId} has no path`); return; } @@ -2393,7 +2401,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu // ACTIVE account, so a background Gmail account's labels used to be created // and coloured in the active account's mailbox instead of its own. const token = isGmail ? await resolveGmailToken(accountId) : null; - if (traceEnabled()) logger.trace(`[Pipeline] mirror acct=${acct} uid=${email.uid} folder="${folder.path}" isGmail=${isGmail} token=${token ? 'yes' : 'no'} cats=[${cats.map((c) => c.slug).join(',')}]`); + if (traceEnabled()) logger.trace(`[Pipeline] mirror acct=${accountLogLabel(acct)} uid=${email.uid} folder=${folderLogLabel(folder.path)} isGmail=${isGmail} token=${token ? 'yes' : 'no'} cats=[${cats.map((c) => categoryLogLabel(c.slug, defs.some((d: any) => d.slug === c.slug && d.isSystem))).join(',')}]`); const result = await applyEmailLabels(engine, email, folder.path, cats, isGmail, token, bySlug, canApply); // Automatic mirrors mark label_status → 'done' only on a CONFIRMED apply. A merely-'queued' op // (background account mid-sync) is NOT yet on the server — if it later @@ -2403,7 +2411,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu try { (storage as any).getRepositories?.()?.agent?.markLabelDone?.(email.id); } catch { /* non-fatal */ } } } catch (e) { - logger.warn(`[Pipeline] mirror acct=${acct} uid=${email?.uid} best-effort failed:`, (e as Error).message); + logger.warn(`[Pipeline] mirror acct=${accountLogLabel(acct)} uid=${email?.uid} best-effort failed:`, failureCause(e)); } }); } @@ -2445,7 +2453,7 @@ export async function backfillCategoryLabels(limit = 50): Promise<{ accounts: nu labeled++; } } catch (e) { - logger.warn('[Pipeline] backfill (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] backfill (one account) failed:', failureCause(e)); } } logger.info(`[Pipeline] category-label backfill: ${labeled} mail(s) across ${accounts} account(s)`); @@ -2505,7 +2513,7 @@ async function provisionAccountLabels( } return { handled: true, created }; } catch (e) { - logger.warn('[Pipeline] provision (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] provision (one account) failed:', failureCause(e)); return { handled: false, created: 0 }; } } @@ -2614,7 +2622,7 @@ export async function renameCategoryLabelEverywhere(oldName: string, newName: st await queue.renameCategoryLabel({ slug: '', name: oldName }, { slug: '', name: newName }, categoryLabelConfig.folderMode); } } catch (e) { - logger.warn('[Pipeline] rename label (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] rename label (one account) failed:', failureCause(e)); } } } @@ -2654,7 +2662,7 @@ export async function removeAllCategoryLabels(): Promise<{ accounts: number; rem removed += await queue.removeSarvInboxLabels(categoryLabelConfig.folderMode); } } catch (e) { - logger.warn('[Pipeline] remove labels (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] remove labels (one account) failed:', failureCause(e)); } } logger.info(`[Pipeline] removed ${removed} Sarv Inbox label(s) across ${accounts} account(s)`); @@ -2708,7 +2716,7 @@ async function executeAgentAction(emailId: string, action: UserActionType, _valu // Failures are logged, never swallowed to console (CLAUDE.md: always the // shared logger). A dropped line here is a divergence nobody can see. const onFail = (what: string) => (err: unknown) => - logger.error(`[Pipeline] agent ${what} did not reach IMAP for ${emailId}:`, err); + logger.error(`[Pipeline] agent ${what} did not reach IMAP for ${emailId}:`, errorDiagnostic(err)); if (action === 'read') syncEngine.markAsRead(folder.path, email.uid).catch(onFail('mark-read')); else if (action === 'star') syncEngine.markAsStarred(folder.path, email.uid, true).catch(onFail('star')); else if (action === 'archive') (syncEngine as any).operationQueue?.archive(folder.path, email.uid).catch(onFail('archive')); @@ -2775,7 +2783,7 @@ async function triggerCategorizeFor(emailId: string, hintAccountId?: string, sou const threadId = email.threadId; if (!threadId) return; - logger.info(`[Pipeline:Event] ${source} → ${emailId} thread=${threadId} acct=${getAccountIdForStorage(storage) ?? 'active'}`); + logger.info(`[Pipeline:Event] ${source} → ${emailId} thread=${threadId} acct=${accountLogLabel(getAccountIdForStorage(storage), 'active')}`); processEmail(emailId, threadId, storage); } @@ -2878,7 +2886,7 @@ function startPollingTrigger(): void { stillStuck.map((r: { id: string; reason: string }) => `${r.id}(${r.reason})`).join(', ')); } } catch (e) { - logger.warn('[Pipeline:Poll] stuck-row heal failed:', (e as Error).message); + logger.warn('[Pipeline:Poll] stuck-row heal failed:', failureCause(e)); } // Per-account snapshot for the log line — body-FREE. This used to call @@ -2957,7 +2965,7 @@ function startPollingTrigger(): void { } catch (e) { // Isolate one account's failure so it never skips the accounts after it // in this tick (the loop must keep fanning out across all accounts). - logger.warn('[Pipeline:Poll] account tick failed (isolated):', (e as Error).message); + logger.warn('[Pipeline:Poll] account tick failed (isolated):', failureCause(e)); } } @@ -3067,7 +3075,7 @@ function registerPipelineIPC(): void { try { await clearPipelineAIConfig(); } catch (e) { - logger.warn(`[Pipeline] could not clear the saved AI config: ${(e as Error).message}`); + logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`); } return { success: true }; }); @@ -3089,7 +3097,7 @@ function registerPipelineIPC(): void { logger.warn(`[Pipeline] AI config refused: its ${signIn.provider} sign-in is no longer on this device`); dropLiveAIConfig(); lastAIErrorReason = reason; - void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${e.message}`)); + void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`)); emitAiPipelineStatus(); // The renderer ignores a push's answer, and a provider still listed there // with no sign-in behind it would otherwise show no sign of a problem. @@ -3105,10 +3113,10 @@ function registerPipelineIPC(): void { if (isAIEndpointRefusedError(error)) { refuseAIConfig(error); // Nor is a refused provider the one to bring back after a restart. - void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${e.message}`)); + void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`)); return { success: false, error: error.message }; } - logger.error('[Pipeline] AI config could not be prepared:', error); + logger.error('[Pipeline] AI config could not be prepared:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } if (push !== aiConfigPushes) return overtaken; diff --git a/apps/desktop/electron/services/update-service.ts b/apps/desktop/electron/services/update-service.ts index 6ac2909b..71639f74 100644 --- a/apps/desktop/electron/services/update-service.ts +++ b/apps/desktop/electron/services/update-service.ts @@ -27,6 +27,7 @@ import { app, Notification } from 'electron'; import { autoUpdater, type Logger as UpdaterLogger } from 'electron-updater'; import { getMainWindow } from '../shared'; +import { withoutHomeDir } from '../utils/log-path'; import { restoreAndFocusWindow } from '../utils/window-focus'; import { verifyUpdate } from './update-manifest'; @@ -66,9 +67,13 @@ const logger = createLogger('update-service'); * calls it when it exists, and it is per-request noise. */ const electronUpdaterLog = createLogger('electron-updater'); -/** Keeps an Error's stack; electron-updater mostly logs plain strings. */ -const describeUpdaterMessage = (message: unknown): string => - message instanceof Error ? (message.stack ?? message.message) : String(message); +/** + * Keeps an Error's stack; electron-updater mostly logs plain strings. Its + * lines name the update cache and the installer by absolute path ("downloaded + * to /Users//Library/Caches/…"), so the home folder is written as `~`. + */ +export const describeUpdaterMessage = (message: unknown): string => + withoutHomeDir(message instanceof Error ? (message.stack ?? message.message) : String(message)); const updaterLogger: UpdaterLogger = { info: (message) => electronUpdaterLog.info(describeUpdaterMessage(message)), warn: (message) => electronUpdaterLog.warn(describeUpdaterMessage(message)), diff --git a/apps/desktop/electron/services/vault-credentials.ts b/apps/desktop/electron/services/vault-credentials.ts index 3e38e20f..277d7492 100644 --- a/apps/desktop/electron/services/vault-credentials.ts +++ b/apps/desktop/electron/services/vault-credentials.ts @@ -30,6 +30,7 @@ * `assertOAuthMailHost`, and an entry holding only a token is never returned. */ import { + accountLogLabel, accountIdFor, createLogger, limitTransport, @@ -139,7 +140,7 @@ export function vaultIdCandidates(accountId: string | undefined | null, username const acct = registryAccount(accountId); if (acct) ids.push(accountIdFor(acct.email, acct.imapConfig?.host)); } catch (error) { - logger.warn(`[Vault] account registry unreadable while resolving ids for ${accountId}: ${(error as Error).message}`); + logger.warn(`[Vault] account registry unreadable while resolving ids for ${accountLogLabel(accountId)}: ${(error as Error).message}`); } } ids.push(accountIdFor(username, host), accountIdFor(username)); @@ -258,7 +259,7 @@ async function savedTransport(id: string, kind: VaultCredentialKind, entry: Vaul allowPlaintext: typeof entry.allowPlaintext === 'boolean' ? entry.allowPlaintext : legacy.allowPlaintext, }; await bindAccountSecretTransport(id, kind, bound); - logger.info(`[Vault] bound how the saved ${kind} password for ${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: self-signed ${bound.allowInsecureTLS ? 'allowed' : 'refused'}, unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); return bound; } @@ -302,7 +303,7 @@ export async function resolveVaultPassword( continue; } await bindAccountSecretHost(id, kind, wanted); - logger.info(`[Vault] bound the saved ${kind} password for ${id} to ${wanted} (${decision.because})`); + logger.info(`[Vault] bound the saved ${kind} password for ${accountLogLabel(id)} to ${wanted} (${decision.because})`); } const transport = await savedTransport(id, kind, entry, wanted); if (!transport) continue; diff --git a/apps/desktop/electron/utils/file-logger.ts b/apps/desktop/electron/utils/file-logger.ts index 73cced74..c7172c59 100644 --- a/apps/desktop/electron/utils/file-logger.ts +++ b/apps/desktop/electron/utils/file-logger.ts @@ -5,9 +5,11 @@ * dir (next to sarvinbox.db), capped at 20 MB — once past the cap the oldest * half is dropped so it never grows unbounded. Enabled in BOTH dev and packaged * builds so a shipped release has a log to attach to bug reports; safe to ship - * because every line is run through redactSecrets() first (no passwords/tokens), - * and in a release run through redactEmailAddresses() too (CASA L-7: account - * and sender addresses are mailbox data). Dev keeps the addresses — the + * because every line is run through redactSecrets() first (no passwords/tokens) + * and has the home folder written as `~` (an absolute path names the user), and + * in a release run through redactEmailAddresses() and redactAccountIds() too + * (CASA L-7: account and sender addresses are mailbox data, and an account id + * spells out its owner's address). Dev keeps the addresses and ids — the * developer debugs from the dev app.log. The file (and its rotated sibling) is * readable by the owner only (0600). * @@ -18,10 +20,11 @@ */ import { chmodSync, existsSync, lstatSync, mkdirSync, renameSync, statSync, unlinkSync } from 'fs'; +import { homedir } from 'os'; import { dirname, join } from 'path'; import { inspect } from 'util'; -import { isLogLevel, redactEmailAddresses, redactSecrets, toOneLine } from '@sarvinbox/core'; +import { isLogLevel, redactAccountIds, redactEmailAddresses, redactHomeDir, redactSecrets, toOneLine } from '@sarvinbox/core'; import { app } from 'electron'; import pino from 'pino'; @@ -74,8 +77,10 @@ const LEVEL_BY_METHOD: Record = { let active = false; let logPath = ''; let bytesWritten = 0; -// Release runs: also redact email addresses from every line (set at init). +// Release runs: also redact email addresses and account ids from every line (set at init). let redactAddresses = false; +// The user's home folder, written as `~` in every line (read once at init). +let home: string | undefined; // pino's async file destination (sonic-boom): buffered, NON-blocking writes on // a background flush, with a reliable flushSync on exit. Replaces the old // synchronous appendFileSync, which stalled the main-process event loop on every @@ -110,11 +115,11 @@ function render(arg: unknown): string { return inspect(arg, { depth: 4, breakLength: Infinity }); } -/** The redaction every line gets before it is written: secrets always, email - * addresses too in a release run. */ +/** The redaction every line gets before it is written: secrets and the home + * folder always, email addresses and account ids too in a release run. */ function scrub(text: string): string { - const safe = redactSecrets(text); - return redactAddresses ? redactEmailAddresses(safe) : safe; + const safe = redactHomeDir(redactSecrets(text), home); + return redactAddresses ? redactAccountIds(redactEmailAddresses(safe)) : safe; } /** @@ -184,7 +189,9 @@ function write(method: string, args: unknown[]): void { // fall back to the console method for raw console.* calls. const prefix = LOGGER_PREFIX.exec(raw); const level = prefix?.[1] ?? LEVEL_BY_METHOD[method] ?? method.toUpperCase(); - const name = prefix?.[2]; + // The name is scrubbed like the text: a backfill's names its database + // file, and a legacy file name is built from the account's address. + const name = prefix?.[2] ? scrub(prefix[2]) : undefined; const message = scrub(raw.replace(LOGGER_PREFIX, '')); const line = `[${timestamp()}] [${level}] ${name ? `[${name}] ` : ''}${message}\n`; stream.write(line); @@ -235,9 +242,9 @@ export function appendExternalLog(source: string, level: unknown, name: unknown, export interface FileLoggerOptions { /** - * Redact email addresses from every line. main.ts passes `!isDev`: a - * release's app.log must not name the user's accounts or correspondents, - * while the dev log keeps them for debugging. Decided by `isDevBuild()`, not + * Redact email addresses and account ids from every line. main.ts passes + * `!isDev`: a release's app.log must not name the user's accounts or + * correspondents, while the dev log keeps them for debugging. Decided by `isDevBuild()`, not * `app.isPackaged`, which misreports in dev (see the header). */ redactAddresses?: boolean; @@ -251,6 +258,7 @@ export function initFileLogger(options: FileLoggerOptions = {}): string | null { if (active) return logPath; redactAddresses = options.redactAddresses === true; + try { home = homedir(); } catch { home = undefined; } logPath = join(app.getPath('userData'), 'app.log'); try { mkdirSync(dirname(logPath), { recursive: true }); } catch { /* dir exists */ } bytesWritten = existsSync(logPath) ? statSync(logPath).size : 0; @@ -282,7 +290,8 @@ export function initFileLogger(options: FileLoggerOptions = {}): string | null { process.on('exit', flushFileLogger); } catch { /* ignore */ } - console.log(`[file-logger] writing local logs to ${logPath} (cap ${MAX_BYTES / (1024 * 1024)} MB)`); + // Where the file is, without the absolute path: the home folder names the user. + console.log(`[file-logger] writing local logs to /app.log (cap ${MAX_BYTES / (1024 * 1024)} MB)`); // Flush the first line immediately so app.log proves itself on startup rather // than depending on the 1s timer / a later burst. flushFileLogger(); diff --git a/apps/desktop/electron/utils/log-path.ts b/apps/desktop/electron/utils/log-path.ts new file mode 100644 index 00000000..1142170e --- /dev/null +++ b/apps/desktop/electron/utils/log-path.ts @@ -0,0 +1,35 @@ +import { homedir } from 'os'; + +import { pathForLog, redactHomeDir } from '@sarvinbox/core'; +import { app } from 'electron'; + +function home(): string | undefined { + try { + return homedir(); + } catch { + return undefined; + } +} + +function userData(): string | undefined { + try { + return app.getPath('userData'); + } catch { + return undefined; + } +} + +/** + * A path for a main-process log line: `/…`, `~/…` or the file name + * (core's `pathForLog`, rooted at this app's data folder and the user's home). + * Use it wherever a line would otherwise print an absolute path, which names + * the user through their home folder. + */ +export function logPath(path: unknown): string { + return pathForLog(path, { userData: userData(), home: home() }); +} + +/** `text` with the user's home folder written as `~` (core's `redactHomeDir`). */ +export function withoutHomeDir(text: string): string { + return redactHomeDir(text, home()); +} diff --git a/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx b/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx index b93222bf..62673056 100644 --- a/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx +++ b/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx @@ -1,4 +1,5 @@ import type { EmailRecord } from '@sarvinbox/core'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; import { Loader2 } from 'lucide-react'; import { useState, useEffect } from 'react'; @@ -69,7 +70,7 @@ export function AIBoxCategoryView({ setEmails(result.data); } } catch (error) { - console.error('Failed to load AI category emails:', error); + console.error('Failed to load AI category emails:', errorDiagnostic(error)); } finally { setLoadingAICategoryEmails(false); } diff --git a/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts b/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts index 92609d21..9c066468 100644 --- a/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts +++ b/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts @@ -24,6 +24,7 @@ * persisted failure gets its own automatic retry when it is due. */ import type { EmailRecord } from '@sarvinbox/core'; +import { failureCause } from '@sarvinbox/core/error-diagnostic'; import { FIRST_SPLIT_BACKOFF_CAP_SECONDS, firstMemberKeyOf, @@ -35,6 +36,7 @@ import { type FirstSplitRow, type FirstSplitState, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -159,7 +161,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail bridge.get(accountId, threadId).then( (result) => { if (!result.success || !result.data) { - if (live) log.warn(`get acct=${accountId} thread=${threadId} failed: ${result.error ?? 'no data'}`); + if (live) log.warn(`get acct=${accountLogLabel(accountId)} thread=${threadId} failed: ${result.error ? 'error' : 'no data'}`); land(null); return; } @@ -170,7 +172,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail // it caches belongs to this email. Once per email, not per read. if (live && warnedRef.current !== identity) { warnedRef.current = identity; - log.warn(`acct=${accountId} thread=${threadId} main's first member is not the one on screen — no AI split for it`); + log.warn(`acct=${accountLogLabel(accountId)} thread=${threadId} main's first member is not the one on screen — no AI split for it`); } land(null); return; @@ -178,7 +180,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail land(result.data); }, (error: unknown) => { - if (live) log.warn(`get acct=${accountId} thread=${threadId} threw: ${(error as Error)?.message ?? error}`); + if (live) log.warn(`get acct=${accountLogLabel(accountId)} thread=${threadId} threw: ${failureCause(error)}`); land(null); }, ); diff --git a/apps/desktop/src/services/first-split/job.ts b/apps/desktop/src/services/first-split/job.ts index 7040a24f..5e6f8e45 100644 --- a/apps/desktop/src/services/first-split/job.ts +++ b/apps/desktop/src/services/first-split/job.ts @@ -23,10 +23,12 @@ * item, for a switch flipped mid-drain. Refs are deduped (per account * and thread) into one queue, capped, and drained serially. */ +import { failureCause } from '@sarvinbox/core/error-diagnostic'; import { firstSplitStateFor, type FirstSplitGetResult, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { aiEligibilityFor, firstEmailFacts } from '../../components/email-detail/ai-view-compose'; @@ -103,7 +105,7 @@ export async function processCandidate(ref: FirstSplitRef, deps: FirstSplitJobDe const bridge = deps.bridge ?? defaultFirstSplitBridge; const answer = await bridge.get(ref.accountId, ref.threadId, { withSource: true }); if (!answer.success || !answer.data) { - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} get failed`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} get failed`); return 'error'; } const got: FirstSplitGetResult = answer.data; @@ -172,14 +174,14 @@ export function createFirstSplitJob(deps: FirstSplitJobDeps = {}): FirstSplitJob try { result = await processCandidate(ref, deps); } catch (error) { - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} threw: ${(error as Error)?.message ?? error}`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} threw: ${failureCause(error)}`); result = 'error'; } finally { known.delete(`${ref.accountId}|${ref.threadId}`); } tally[result] += 1; processed += 1; - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} -> ${result}`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} -> ${result}`); } // Only drained with at least one ref, so at least one count is non-zero. const counts = (Object.keys(tally) as JobItemResult[]) diff --git a/apps/desktop/src/services/first-split/store.ts b/apps/desktop/src/services/first-split/store.ts index f0ad4984..9739550d 100644 --- a/apps/desktop/src/services/first-split/store.ts +++ b/apps/desktop/src/services/first-split/store.ts @@ -39,6 +39,7 @@ import { type FirstSplitSaveRequest, type FirstSplitSaveResult, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { createSingleFlight } from '@sarvinbox/core/single-flight'; @@ -212,7 +213,8 @@ async function run( if (!got) { const answer = await bridge.get(ref.accountId, ref.threadId, { withSource: true }); if (!answer.success || !answer.data) { - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} get failed: ${answer.error ?? 'no data'}`); + // Whether main said why, not what it said: its error text can quote the stored record. + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} get failed: ${answer.error ? 'error' : 'no data'}`); return { state: 'error', error: answer.error ?? 'no data' }; } got = answer.data; @@ -221,7 +223,7 @@ async function run( if (!current || !source || !(source.rawBody ?? '').trim()) return { state: 'unknown' }; // Main hands back its own first member; a record that is not it cannot be split under this key. if (firstMemberKeyOf(source) !== current.firstKey) { - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} source is not the first member — not run`); + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} source is not the first member — not run`); return { state: 'unknown' }; } if (!force && isUsableSplit(row, current)) return { state: 'usable', current, row: row! }; @@ -271,7 +273,7 @@ async function splitAndSave( hub.publish({ running: false, status: null }); } const seconds = ((Date.now() - started) / 1000).toFixed(1); - const line = `split acct=${ref.accountId} thread=${ref.threadId} trigger=${options.trigger} ${countsOf(outcome)}`; + const line = `split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} trigger=${options.trigger} ${countsOf(outcome)}`; if (outcome.status === 'provider') { log.warn(`${line} status=provider (nothing saved) ${seconds}s: ${outcome.reason ?? ''}`); @@ -288,7 +290,7 @@ async function splitAndSave( }; const saved = await bridge.save(ref.accountId, request); if (!saved.success || !saved.data) { - log.warn(`${line} status=${outcome.status} save failed ${seconds}s: ${saved.error ?? 'no data'}`); + log.warn(`${line} status=${outcome.status} save failed ${seconds}s: ${saved.error ? 'error' : 'no data'}`); return { state: 'error', error: saved.error ?? 'no data' }; } const result = saved.data.applied ? `saved=${saved.data.status ?? outcome.status}` : `not-saved=${saved.data.reason}`; @@ -314,7 +316,7 @@ export function runFirstSplit( const message = error instanceof Error ? error.message : String(error); // By class, code and status: the message of a split that threw can quote // the email it was splitting, or a provider's response body. - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} threw`, errorDiagnostic(error)); + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} threw`, errorDiagnostic(error)); return { state: 'error', error: message }; } }); diff --git a/apps/desktop/src/store/slices/connection-slice.ts b/apps/desktop/src/store/slices/connection-slice.ts index 242555d6..aedb1cf5 100644 --- a/apps/desktop/src/store/slices/connection-slice.ts +++ b/apps/desktop/src/store/slices/connection-slice.ts @@ -1,4 +1,5 @@ import type { SMTPConfig } from '@sarvinbox/core'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { createSingleFlight } from '@sarvinbox/core/single-flight'; @@ -355,7 +356,7 @@ const connectionSlice = ( const pending = connectInFlight.pending(acctId); if (pending) { - console.log(`[Store] connect() already in flight for ${acctId} — joining it`); + console.log(`[Store] connect() already in flight for ${accountLogLabel(acctId)} — joining it`); return pending; } diff --git a/apps/desktop/src/store/slices/email-actions-slice.ts b/apps/desktop/src/store/slices/email-actions-slice.ts index ee646857..503d2bf1 100644 --- a/apps/desktop/src/store/slices/email-actions-slice.ts +++ b/apps/desktop/src/store/slices/email-actions-slice.ts @@ -5,6 +5,7 @@ // declared in vite.config.ts, vitest.config.ts and tsconfig.json. import { conversationFoldersOf, isDraftRow } from '@sarvinbox/core/conversation-membership'; import { classifyFolder, isStarredFolder } from '@sarvinbox/core/folder-mapping'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { addTag, removeTag, hasTag } from '../../utils/tags'; @@ -430,7 +431,7 @@ async function dispatchBulkByAccount(grouped: Map, queuedIds: ids.filter((id) => result.data!.queuedIds?.includes(id) && !failed.has(id)), }; } catch (error) { - console.warn('[Store] bulkAction failed for account', acct ?? '(active)', error); + console.warn('[Store] bulkAction failed for account', accountLogLabel(acct, '(active)'), error); return { processedIds: [], failedIds: ids, queuedIds: [] }; } })); diff --git a/apps/desktop/src/store/slices/emails-slice.ts b/apps/desktop/src/store/slices/emails-slice.ts index ec75fc91..8ebe620e 100644 --- a/apps/desktop/src/store/slices/emails-slice.ts +++ b/apps/desktop/src/store/slices/emails-slice.ts @@ -5,6 +5,8 @@ import { isDraftRow, isExcludedFolderCopy, } from '@sarvinbox/core/conversation-membership'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; +import { accountLogLabel, folderLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { clearCategoryBadgeCache } from '../../components/email-list/CategoryBadges'; @@ -458,7 +460,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ clearCategoryBadgeCache(); const selectedFolder = get().folders.find(f => f.id === folderId); - console.log(`[View] Selected folder: ${selectedFolder?.path || selectedFolder?.name || folderId} (inboxType=${get().inboxType})`); + console.log(`[View] Selected folder: ${folderLogLabel(selectedFolder?.path || selectedFolder?.name || folderId)} (inboxType=${get().inboxType})`); // NOTE: sectionData is intentionally NOT cleared here. It only ever // holds INBOX section data and is only rendered in the INBOX sectioned // view, so keeping it cached lets a return to INBOX show the previous @@ -490,9 +492,9 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ if (folder && !get().syncing && get().connectionStatus !== 'disconnected') { const { syncingFolders } = get(); if (syncingFolders.has(folder.path)) { - console.log(`[Store] Skipping sync for ${folder.path} - this folder already syncing`); + console.log(`[Store] Skipping sync for ${folderLogLabel(folder.path)} - this folder already syncing`); } else { - console.log(`[Store] Starting background sync for folder: ${folder.path}`); + console.log(`[Store] Starting background sync for folder: ${folderLogLabel(folder.path)}`); // syncSingleFolder now owns the post-sync view-refresh routing // (AI-category → loadAICategoryEmails, sectioned INBOX → // loadAllSections, flat → mergeNewEmails, virtual-all/starred @@ -501,7 +503,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // callers of syncSingleFolder (ensureConnectionAndSync's // periodic poll, etc.) missed the section/AI-category refresh. get().syncSingleFolder(folder.path).catch((err) => { - console.error(`[Store] Sync failed for ${folder.path}:`, err); + console.error(`[Store] Sync failed for ${folderLogLabel(folder.path)}:`, errorDiagnostic(err)); }); } } @@ -545,7 +547,8 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ const folderName = selectedFolderId ? folders.find(f => f.id === selectedFolderId)?.path : null; // `AI:category`, never the slug: a custom category's slug is made from the // name the user typed. Built-in views (virtual folders, snoozed) are ours. - const view = viewingAICategory ? 'AI:category' : selectedVirtualFolder || (viewingSnoozed ? 'snoozed' : folderName || 'unknown'); + // A folder the user named is written as its label (folderLogLabel). + const view = viewingAICategory ? 'AI:category' : selectedVirtualFolder || (viewingSnoozed ? 'snoozed' : folderName ? folderLogLabel(folderName) : 'unknown'); // `search=set`, never the query: it is what the user typed, and this line // repeats on every email opened while a search is active. log.info(`[View] selectEmail id=${emailId ? emailId.substring(0, 12) + '...' : 'null'}, view=${view}${searchQuery ? ', search=set' : ''}, pool=${get().emails.length} emails`); @@ -722,7 +725,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // (`maxMessages: localTotal + PAGE_SIZE` grew every scroll). The backfill // scheduler also runs continuously, so most scrolls are already covered — // this just nudges it — and it yields to any in-flight foreground sync. - console.log(`[Store] loadMoreEmails: local exhausted (${localTotal}), server has ${serverTotal} — nudging backfill for ${selectedFolder.path}`); + console.log(`[Store] loadMoreEmails: local exhausted (${localTotal}), server has ${serverTotal} — nudging backfill for ${folderLogLabel(selectedFolder.path)}`); const res = await window.electronAPI.imap.backfillChunk(selectedFolder.path); const inserted = res?.success ? (res.data?.inserted ?? 0) : 0; @@ -1403,19 +1406,19 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ if (targets.length === 0) return; bgSyncRunning = true; - console.log('[TierB] cycle start — targets:', targets.map((a) => `${a.email}@${a.imapConfig?.host}`)); + console.log('[TierB] cycle start — targets:', targets.map((a) => accountLogLabel(a.id))); try { // Serial: one account at a time to avoid a connection storm (up to 10 // accounts). Each is isolated so one failure never stops the rest. for (const acct of targets) { try { const res = await window.electronAPI.accounts.backgroundSync({ accountId: acct.id, config: acct.imapConfig }); - console.log('[TierB] backgroundSync result for', acct.email, '@', acct.imapConfig?.host, '→', res); + console.log('[TierB] backgroundSync result for', accountLogLabel(acct.id), '→', res); if (res?.success && res.data) { set({ accountUnread: { ...get().accountUnread, [acct.id]: res.data.unread } }); } } catch (e) { - console.warn('[TierB] backgroundSync failed for', acct.id, (e as Error)?.message); + console.warn('[TierB] backgroundSync failed for', accountLogLabel(acct.id), (e as Error)?.message); } } // If the merged view is open, refresh it so newly-synced mail appears. @@ -1611,7 +1614,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // (5/10/25/50; default 25). Clicking the count opens the full paginated page. const section = get().inboxSections.find((s) => s.id === sectionId); const pageSize = section?.maxItems && section.maxItems > 0 ? section.maxItems : 25; - console.log(`[View] loadSectionEmails section=${sectionId}, filter=${filter}, folderPath=${folderPath || 'all'}, pageSize=${pageSize}`); + console.log(`[View] loadSectionEmails section=${sectionId}, filter=${filter}, folderPath=${folderPath ? folderLogLabel(folderPath) : 'all'}, pageSize=${pageSize}`); // Mark section loading const newLoading = new Set(get().sectionLoading); diff --git a/apps/desktop/src/store/slices/sync-slice.ts b/apps/desktop/src/store/slices/sync-slice.ts index 1073a9c9..265e8c8d 100644 --- a/apps/desktop/src/store/slices/sync-slice.ts +++ b/apps/desktop/src/store/slices/sync-slice.ts @@ -1,6 +1,8 @@ import type { RealtimeEvent } from '@sarvinbox/core'; import { sentFolderPathsOf } from '@sarvinbox/core/conversation-membership'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; import { isSentMailFolder } from '@sarvinbox/core/folder-mapping'; +import { folderLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import pLimit from 'p-limit'; @@ -178,7 +180,7 @@ export async function refreshVisibleViewForFolder( // AI-categorized view (Needs Response, Reminders, etc.). Never the // slug: a custom category's slug is made from the name the user typed, // and this branch only runs with one set. - log.info(`[Store] refreshView: re-fetching AI category (aiCategory=set) after ${folderPath} sync`); + log.info(`[Store] refreshView: re-fetching AI category (aiCategory=set) after ${folderLogLabel(folderPath)} sync`); await state.loadAICategoryEmails?.(state.viewingAICategory); } else if ( isCurrentFolder && @@ -189,7 +191,7 @@ export async function refreshVisibleViewForFolder( // SECTIONED INBOX. Visible data lives in `sectionData`, not // `emails` — a plain mergeNewEmails would update the wrong // store slot and look like a no-op to the user. - console.log(`[Store] refreshView: reloading sections for ${folderPath}`); + console.log(`[Store] refreshView: reloading sections for ${folderLogLabel(folderPath)}`); await state.loadAllSections?.(folderPath); } else if (isCurrentFolder) { // Flat folder view — diff against `emails` and prepend new rows. @@ -203,7 +205,7 @@ export async function refreshVisibleViewForFolder( // view not matching the folder): leave the list alone, only the // sidebar badge updates via loadFolders elsewhere. } catch (err) { - console.warn(`[Store] refreshVisibleViewForFolder failed for ${folderPath}:`, err); + console.warn(`[Store] refreshVisibleViewForFolder failed for ${folderLogLabel(folderPath)}:`, errorDiagnostic(err)); } } @@ -720,11 +722,11 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ syncSingleFolder: async (folderPath) => { // Only allow one sync operation at a time — avoids connection pool exhaustion if (get().syncing || get().syncingFolders.size > 0) { - console.log(`[Store] syncSingleFolder: Skipping ${folderPath} — another sync in progress`); + console.log(`[Store] syncSingleFolder: Skipping ${folderLogLabel(folderPath)} — another sync in progress`); return; } - console.log(`[Store] syncSingleFolder: Starting sync for ${folderPath}`); + console.log(`[Store] syncSingleFolder: Starting sync for ${folderLogLabel(folderPath)}`); const newSyncingFolders = new Map(get().syncingFolders); newSyncingFolders.set(folderPath, Date.now()); @@ -740,7 +742,8 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ skipUnchanged: false, }); - console.log(`[Store] syncSingleFolder: ${folderPath} sync result:`, result.success ? 'success' : result.error); + // Not the error text: a server's message can quote the folder's name. + console.log(`[Store] syncSingleFolder: ${folderLogLabel(folderPath)} sync result:`, result.success ? 'success' : 'failed'); if (result.success) { get().noteSyncOk(); @@ -751,14 +754,14 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ get().noteSyncFailure(result.error); } } catch (error) { - console.error(`[Store] syncSingleFolder: Failed to sync ${folderPath}:`, error); + console.error(`[Store] syncSingleFolder: Failed to sync ${folderLogLabel(folderPath)}:`, errorDiagnostic(error)); get().noteSyncFailure(error); } finally { const currentSyncingFolders = get().syncingFolders; const updatedSyncingFolders = new Map(currentSyncingFolders); updatedSyncingFolders.delete(folderPath); set({ syncingFolders: updatedSyncingFolders }); - console.log(`[Store] syncSingleFolder: ${folderPath} sync complete`); + console.log(`[Store] syncSingleFolder: ${folderLogLabel(folderPath)} sync complete`); } }, @@ -843,7 +846,7 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ // Remove any existing listener first to prevent accumulation window.electronAPI.imap.removeRealtimeEventListener(); - console.log('[Store] Setting up IDLE event listener for folder:', folderPath); + console.log('[Store] Setting up IDLE event listener for folder:', folderLogLabel(folderPath)); // No logging in this callback: it fires once per message, so a flag // reconcile would emit hundreds of console writes on the UI thread. // The coalescer logs one aggregate line per flush instead. diff --git a/apps/desktop/src/utils/account-scoped-cache.ts b/apps/desktop/src/utils/account-scoped-cache.ts index 1fb180f3..d2cfd95a 100644 --- a/apps/desktop/src/utils/account-scoped-cache.ts +++ b/apps/desktop/src/utils/account-scoped-cache.ts @@ -24,6 +24,7 @@ // * OPTIMISTIC WRITES THAT CAN FAIL. A write shows immediately, survives a load // that races it, and is rolled back if the main process refuses it. +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; const log = createLogger('AccountScopedCache'); @@ -148,7 +149,8 @@ export function createAccountScopedCache(options: AccountScopedCacheOptions accountId || activeAccount || UNKNOWN_ACTIVE; const argFor = (key: string): string | undefined => (key === UNKNOWN_ACTIVE ? undefined : key); - const label = (key: string) => (key === UNKNOWN_ACTIVE ? 'the active account' : key); + // An account id spells out the address it was built from: written as its label. + const label = (key: string) => (key === UNKNOWN_ACTIVE ? 'the active account' : accountLogLabel(key)); const entryFor = (key: string): Entry => { let entry = entries.get(key); diff --git a/apps/desktop/test/helpers/core-log-helpers.ts b/apps/desktop/test/helpers/core-log-helpers.ts new file mode 100644 index 00000000..e0cbbfdb --- /dev/null +++ b/apps/desktop/test/helpers/core-log-helpers.ts @@ -0,0 +1,15 @@ +/** + * The REAL log helpers from core, for a test that mocks `@sarvinbox/core` + * with only the pieces it needs. Product code routes account ids, folder and + * label names, paths and errors through these before they reach a log line, + * so a mock without them fails at the first log line — and a stand-in would + * hide what the line really says. Spread it first in the mock factory: + * + * vi.mock('@sarvinbox/core', async () => ({ + * ...(await import('../../../helpers/core-log-helpers')), + * createLogger: () => quietLogger, + * })); + */ +export * from '../../../../packages/core/src/utils/error-diagnostic'; +export * from '../../../../packages/core/src/utils/log-labels'; +export * from '../../../../packages/core/src/utils/log-paths'; diff --git a/apps/desktop/test/unit/electron/ipc/accounts-unified-search-log.test.ts b/apps/desktop/test/unit/electron/ipc/accounts-unified-search-log.test.ts index 732cc5cc..f5f41ff4 100644 --- a/apps/desktop/test/unit/electron/ipc/accounts-unified-search-log.test.ts +++ b/apps/desktop/test/unit/electron/ipc/accounts-unified-search-log.test.ts @@ -1,4 +1,4 @@ -import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import { accountLogLabel, getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; /** @@ -69,6 +69,8 @@ afterEach(() => { logs.stop(); }); describe('accounts:unifiedSearch — what reaches the log', () => { // Breaks: 'unifiedSearch: skipping account ' quotes the // search words; or one failing account fails the whole search. + // Changed deliberately (log privacy): the id is written as its label (an + // account id spells out its owner's address). it('skips a failing account, logging its id and the error class and code only', async () => { const result = await search(['ok', 'broken']); @@ -76,7 +78,7 @@ describe('accounts:unifiedSearch — what reaches the log', () => { expect(result.data?.map((row) => row.id)).toEqual(['m1']); expect(logs.containing(SENTINEL)).toEqual([]); expect(logs.containing('unifiedSearch: skipping account')).toEqual([ - "[WARN] [accounts-handlers] [Accounts] unifiedSearch: skipping account broken { name: 'Error', code: 'SQLITE_ERROR' }", + `[WARN] [accounts-handlers] [Accounts] unifiedSearch: skipping account ${accountLogLabel('broken')} { name: 'Error', code: 'SQLITE_ERROR' }`, ]); }); 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 3619bda5..98529cc6 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 @@ -25,6 +25,8 @@ vi.mock('electron', () => ({ ipcMain: { handle: (name: string, fn: (...a: any[]) => any) => h.handlers.set(name, fn) }, })); vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(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')), withTimeout: (p: Promise) => p, 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 a9e49b38..c75949eb 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 @@ -40,6 +40,8 @@ vi.mock('electron', () => ({ }, })); vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(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')), withTimeout: (p: Promise) => p, diff --git a/apps/desktop/test/unit/electron/sentry-privacy.test.ts b/apps/desktop/test/unit/electron/sentry-privacy.test.ts index 0bb2e046..06fe5837 100644 --- a/apps/desktop/test/unit/electron/sentry-privacy.test.ts +++ b/apps/desktop/test/unit/electron/sentry-privacy.test.ts @@ -19,6 +19,7 @@ const h = vi.hoisted(() => ({ baseSend: vi.fn(async () => ({ statusCode: 200 })), baseFlush: vi.fn(async () => true), offlineWrapped: [] as unknown[], + setUser: vi.fn(), })); vi.mock('electron', () => ({ @@ -37,7 +38,7 @@ vi.mock('@sentry/electron/main', () => ({ flush: vi.fn(async () => true), setTag: vi.fn(), setContext: vi.fn(), - setUser: vi.fn(), + setUser: h.setUser, // The real base transport posts over the network: a recorder stands in. makeElectronTransport: () => ({ send: h.baseSend, flush: h.baseFlush }), // The real offline wrapper queues on disk around the base it is given; this @@ -55,6 +56,7 @@ h.userData = dir; afterAll(() => rmSync(dir, { recursive: true, force: true })); const PREF = join(dir, 'crash-reports.json'); +const ID_FILE = join(dir, 'crash-report-id'); type SentryModule = typeof import('../../../electron/sentry'); let sentry: SentryModule; @@ -78,6 +80,8 @@ const configuredTransport = () => beforeEach(async () => { rmSync(PREF, { recursive: true, force: true }); + rmSync(ID_FILE, { recursive: true, force: true }); + h.setUser.mockClear(); h.baseSend.mockClear(); h.baseFlush.mockClear(); h.offlineWrapped.length = 0; @@ -202,6 +206,60 @@ describe('Sentry privacy filters (main)', () => { }); }); +describe('which installation a report came from', () => { + const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + + // Breaks if the report's user id is derived from the address again: a + // truncated SHA-256 of it is confirmed by anyone holding a guess at it. + it('sets the user to a random id kept in userData, the same across restarts', async () => { + const first = h.setUser.mock.calls.at(-1)?.[0] as { id: string }; + expect(first.id).toMatch(UUID); + expect(readFileSync(ID_FILE, 'utf8').trim()).toBe(first.id); + + h.setUser.mockClear(); + await freshInit(); + expect(h.setUser).toHaveBeenCalledWith({ id: first.id }); + }); + + // Breaks if connecting an account puts anything about its address on the + // report (the old code set the user to a hash of it on every connect). + it('identifyClient tags the server and never sets a user', () => { + h.setUser.mockClear(); + sentry.identifyClient({ provider: 'gmail', host: 'imap.gmail.com', port: 993 }); + expect(h.setUser).not.toHaveBeenCalled(); + }); + + // Breaks if a malformed or planted file is trusted as the id, or the app + // fails to start reporting when the id cannot be saved. + it('replaces a malformed id file, and makes a per-run id when it cannot save one', async () => { + writeFileSync(ID_FILE, 'jane.doe@example.com\n'); + await freshInit(); + const replaced = (h.setUser.mock.calls.at(-1)?.[0] as { id: string }).id; + expect(replaced).toMatch(UUID); + expect(readFileSync(ID_FILE, 'utf8')).not.toContain('jane'); + + // A directory squatting on the name: unreadable as a file and unwritable. + rmSync(ID_FILE, { force: true }); + mkdirSync(ID_FILE); + h.setUser.mockClear(); + await freshInit(); + const perRun = (h.setUser.mock.calls.at(-1)?.[0] as { id: string }).id; + expect(perRun).toMatch(UUID); + expect(perRun).not.toBe(replaced); + }); + + // Breaks if a fetch breadcrumb's `http.query` (Sentry keeps the query + // beside the URL it cut) reaches Sentry through main's real filter. + it('drops http.query and http.fragment from a breadcrumb main lets through', () => { + sentry.setCrashReportsEnabled(true); + const crumb = sentry.filterBreadcrumb({ + category: 'fetch', + data: { url: 'https://api.example.test/v1/models', 'http.query': '?key=AIzaSECRET', 'http.fragment': '#t=1', status_code: 200 }, + }); + expect(crumb).toEqual({ category: 'fetch', data: { url: 'https://api.example.test/v1/models', status_code: 200 } }); + }); +}); + describe('no native crash dumps (CASA L-8)', () => { // Breaks if a minidump integration runs: a minidump is raw process memory // (message text, tokens) that beforeSend cannot scrub — and ElectronMinidump diff --git a/apps/desktop/test/unit/electron/services/accounts-runtime-attachments.test.ts b/apps/desktop/test/unit/electron/services/accounts-runtime-attachments.test.ts index 91a04bf9..31000d6d 100644 --- a/apps/desktop/test/unit/electron/services/accounts-runtime-attachments.test.ts +++ b/apps/desktop/test/unit/electron/services/accounts-runtime-attachments.test.ts @@ -26,7 +26,9 @@ const h = vi.hoisted(() => ({ vi.mock('electron', () => ({ app: { getPath: () => h.userData, getName: () => 'Sarv Inbox Test', isPackaged: false }, })); -vi.mock('@sarvinbox/core', () => ({ +vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, trace: () => {} }), SyncEngine: class {}, })); 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 181a145b..4f4d5309 100644 --- a/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts +++ b/apps/desktop/test/unit/electron/services/accounts-runtime.test.ts @@ -46,13 +46,17 @@ vi.mock('electron', () => ({ app: { getPath: () => h.userData, getName: () => 'Sarv Inbox Test', isPackaged: false }, })); +const logLines = vi.hoisted(() => [] as string[]); vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), // The real reader of the blocklist settings: pure, and what decides whether // the stage below is built at all. readBlocklistPrefs: (await import('../../../../../../packages/core/src/utils/blocklist-prefs')).readBlocklistPrefs, - createLogger: () => ({ - info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, trace: () => {}, - }), + createLogger: () => { + const record = (...args: unknown[]) => { logLines.push(args.map(String).join(' ')); }; + return { info: record, warn: record, error: record, debug: record, trace: record }; + }, SyncEngine: class { storage: unknown; // Recorded, not ignored: every account's engine must be handed the shared @@ -816,6 +820,32 @@ describe('cleanupOrphanedAccountDbs', () => { expect(existsSync(join(h.userData, kept))).toBe(true); }); + // Regression: '[Accounts] removed legacy … DB: ' wrote the file name, + // and a legacy name IS the account id (the owner's address, normalised). + it('logs a removed legacy DB by its account label, never its name', async () => { + const { accountLogLabel } = await import('../../../helpers/core-log-helpers'); + logLines.length = 0; + touch('sarvinbox-acct-owner-sentinel-example-com.db'); + touch('acct-other-sentinel-example-com', SQLITE_MAGIC); + + expect(cleanupOrphanedAccountDbs()).toEqual( + expect.arrayContaining(['sarvinbox-acct-owner-sentinel-example-com.db', 'acct-other-sentinel-example-com']), + ); + + expect(logLines.filter((l) => l.includes('sentinel'))).toEqual([]); + expect(logLines).toContain(`[Accounts] removed orphaned legacy DB: sarvinbox-${accountLogLabel('acct-owner-sentinel-example-com')}.db`); + expect(logLines).toContain(`[Accounts] removed legacy plaintext account DB: ${accountLogLabel('acct-other-sentinel-example-com')}`); + }); + + // Regression: '[Accounts] Created runtime -> ' wrote the absolute DB + // path, which names the user through their home folder. + it('logs a new runtime\'s database relative to userData', async () => { + logLines.length = 0; + await createAccountRuntime('sarvinbox-abc.db'); + expect(logLines).toContain('[Accounts] Created runtime -> /sarvinbox-abc.db'); + expect(logLines.filter((l) => l.includes(h.userData))).toEqual([]); + }); + it('removes an oldest-scheme plaintext `acct-*` DB only when it really is SQLite', () => { touch('acct-advik-d-sarv-com', SQLITE_MAGIC); touch('acct-not-a-database', 'just some text'); diff --git a/apps/desktop/test/unit/electron/services/ai-categorization-log.test.ts b/apps/desktop/test/unit/electron/services/ai-categorization-log.test.ts index 33faf524..a4c8fd36 100644 --- a/apps/desktop/test/unit/electron/services/ai-categorization-log.test.ts +++ b/apps/desktop/test/unit/electron/services/ai-categorization-log.test.ts @@ -16,7 +16,11 @@ import { emailRecord } from '../../../helpers/email-fixtures'; * app.log or the renderer relay, or a recoverable answer stops being used. */ -const h = vi.hoisted(() => ({ fetch: vi.fn(), send: vi.fn(), answer: '', saved: [] as unknown[], eligibleFails: null as Error | null })); +const SYSTEM_DEFS = [{ slug: 'needs_response', name: 'Needs Response', prompt: 'a request', isSystem: true }]; +const h = vi.hoisted(() => ({ + fetch: vi.fn(), send: vi.fn(), answer: '', saved: [] as unknown[], eligibleFails: null as Error | null, + defs: [] as Array<{ slug: string; name: string; prompt: string; isSystem: boolean }>, +})); const email = () => emailRecord({ id: 'm1', fromAddress: 'vendor@example.com', toAddress: 'buyer@sarv.com', subject: 'Quote', tags: '|INBOX|', rawBody: '

Prices attached.

', @@ -28,7 +32,7 @@ vi.mock('../../../../electron/shared', () => ({ getEligibleEmailsForAI: () => { if (h.eligibleFails) throw h.eligibleFails; return [email()]; }, getFolders: async () => [{ path: 'INBOX' }], getFolder: async () => ({ path: 'INBOX' }), - getEnabledCategoryDefinitions: () => [{ slug: 'needs_response', name: 'Needs Response', prompt: 'a request' }], + getEnabledCategoryDefinitions: () => h.defs, getSenderContextBatch: () => ({}), getSenderRepetitionStats: () => ({ sameSubject: {}, totalEmails: 1 }), getThreadDepths: () => ({}), @@ -54,6 +58,7 @@ beforeEach(() => { h.send.mockReset(); h.saved = []; h.eligibleFails = null; + h.defs = [...SYSTEM_DEFS]; logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); }); afterEach(() => { logs.stop(); }); @@ -148,6 +153,24 @@ describe('standalone categorizer — what reaches the log', () => { // prompt, which is the user's mail. Both the per-email line (bulk) and the // whole-run line (realtime) used to carry it: 300 characters of it, and the // whole error with its stack. +describe('standalone categorizer — category names in the log', () => { + // Breaks: 'Saved N categorizations (: …)' wrote a custom category's + // slug, which is made from the name the user typed ('acme-sentinel-invoices'); + // or a built-in one turned into a code nobody can read. + it('writes a built-in category by its slug and the user\'s own by its label', async () => { + const { categoryLogLabel } = await import('@sarvinbox/core'); + h.defs = [...SYSTEM_DEFS, { slug: 'acme-sentinel-invoices', name: 'Acme Sentinel Invoices', prompt: 'invoices from Acme', isSystem: false }]; + h.answer = JSON.stringify([{ emailId: 'm1', categories: ['needs_response', 'acme-sentinel-invoices'], is_spam: false, confidence: 0.9, reasoning: 'ok' }]); + + await run(); + + expect(h.saved).toHaveLength(1); + expect(logs.containing('acme-sentinel')).toEqual([]); + expect(relayed().filter((line) => line.includes('acme-sentinel'))).toEqual([]); + expect(logs.containing(`Saved 1 categorizations (needs_response:1 ${categoryLogLabel('acme-sentinel-invoices', false)}:1)`)).toHaveLength(1); + }); +}); + describe('standalone categorizer — a provider error in the log', () => { const refuse = () => h.fetch.mockImplementation(async () => new Response(`{"error":{"message":"Invalid prompt near: ${SENTINEL} wrote about the payslip"}}`, { status: 400 })); diff --git a/apps/desktop/test/unit/electron/services/body-reheal-scheduler.test.ts b/apps/desktop/test/unit/electron/services/body-reheal-scheduler.test.ts index e19b2e0a..2e7063bf 100644 --- a/apps/desktop/test/unit/electron/services/body-reheal-scheduler.test.ts +++ b/apps/desktop/test/unit/electron/services/body-reheal-scheduler.test.ts @@ -1,4 +1,4 @@ -import { createDeferredFetchError, FIRST_SPLIT_VERSION } from '@sarvinbox/core'; +import { accountLogLabel, createDeferredFetchError, FIRST_SPLIT_VERSION } from '@sarvinbox/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; /** @@ -583,7 +583,7 @@ describe('the drain', () => { svc.startBodyRehealScheduler(); await advance(FIRST_TICK_MS); expect(acct.fetched).toEqual(['e1', 'e2']); - expect(h.logs.filter((line) => line.startsWith('Body re-heal acct-a:'))).toEqual([ + expect(h.logs.filter((line) => line.startsWith(`Body re-heal ${accountLogLabel('acct-a')}:`))).toEqual([ expect.stringContaining('repaired 2, failed 0'), ]); svc.stopBodyRehealScheduler(); @@ -599,7 +599,7 @@ describe('the drain', () => { await advance(FIRST_TICK_MS); expect(acct.fetched).toEqual(['e1', 'e2']); expect(acct.deletedSplits).toEqual([]); - expect(h.logs.filter((line) => line.startsWith('Body re-heal acct-a:'))).toEqual([ + expect(h.logs.filter((line) => line.startsWith(`Body re-heal ${accountLogLabel('acct-a')}:`))).toEqual([ expect.stringContaining('repaired 2, failed 0'), ]); svc.stopBodyRehealScheduler(); diff --git a/apps/desktop/test/unit/electron/services/contact-enrichment-scheduler.test.ts b/apps/desktop/test/unit/electron/services/contact-enrichment-scheduler.test.ts index a7fa9c64..93685ba9 100644 --- a/apps/desktop/test/unit/electron/services/contact-enrichment-scheduler.test.ts +++ b/apps/desktop/test/unit/electron/services/contact-enrichment-scheduler.test.ts @@ -41,10 +41,14 @@ vi.mock('../../../../electron/shared', () => ({ : null, })); -vi.mock('@sarvinbox/core', () => ({ - createLogger: () => ({ - info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, trace: () => {}, - }), +const logLines = vi.hoisted(() => [] as string[]); +vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), + createLogger: () => { + const record = (...args: unknown[]) => { logLines.push(args.map(String).join(' ')); }; + return { info: record, warn: record, error: record, debug: record, trace: record }; + }, getEventBus: () => ({ on: (event: string, cb: (e: unknown) => void) => { if (h.busThrows) throw new Error('bus unavailable'); @@ -304,6 +308,24 @@ describe('the single-batch lock', () => { expect(dispatched()[0].payload).toMatchObject({ accountId: 'acct-ok' }); }); + // Regression: '(acct=)' on the dispatch and failure lines wrote the + // account id, which spells out the owner's address, every six hours. + it('names each account by its label in the log, while the batch keeps the real id', async () => { + const { accountLogLabel } = await import('../../../helpers/core-log-helpers'); + const brokenId = 'acct-owner-sentinel-example-com--imap-example-com'; + const okId = 'acct-other-sentinel-example-org--imap-example-org'; + h.runtimes = [[brokenId, runtime(makeAccount(['x'], { throws: true }).storage)], [okId, runtime(makeAccount(['c1']).storage)]]; + logLines.length = 0; + const svc = await load(); + + await expect(svc.triggerEnrichmentNow()).resolves.toBe(1); + + expect(dispatched()[0].payload).toMatchObject({ accountId: okId }); + expect(logLines.filter((l) => l.includes('sentinel'))).toEqual([]); + expect(logLines.some((l) => l.includes(`list candidates failed (acct=${accountLogLabel(brokenId)})`))).toBe(true); + expect(logLines.some((l) => l.includes(`dispatching batch of 1 contacts (acct=${accountLogLabel(okId)})`))).toBe(true); + }); + it('skips a runtime with no storage', async () => { const ok = makeAccount(['c1']); h.runtimes = [['acct-empty', runtime(null)], ['acct-ok', runtime(ok.storage)]]; diff --git a/apps/desktop/test/unit/electron/services/extension-mail-backend.test.ts b/apps/desktop/test/unit/electron/services/extension-mail-backend.test.ts index 34e06a7d..9cd92363 100644 --- a/apps/desktop/test/unit/electron/services/extension-mail-backend.test.ts +++ b/apps/desktop/test/unit/electron/services/extension-mail-backend.test.ts @@ -33,6 +33,8 @@ vi.mock('@sarvinbox/core', async () => { '../../../../../../packages/core/src/extensions/workflow-effects' ); return { + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), planWorkflowEffects: effects.planWorkflowEffects, createLogger: () => ({ info: (...args: unknown[]) => h.logs.push(args.join(' ')), @@ -232,6 +234,19 @@ describe('applyLabels', () => { ); }); + // Regression: ' changed : +[]' wrote the tags an + // extension chose, which it names from the mail it read ('invoice-acme-q3'). + it('logs the tags it changed as label codes, never their names', async () => { + const { labelLogLabel } = await import('../../../helpers/core-log-helpers'); + const storage = makeStorage({ 'e1': makeEmail('e1') }); + install(storage, ['e1'], ['email:label']); + + await createExtensionMailBackend().applyLabels('tagger', 'e1', { add: ['acme-sentinel-invoice'] }); + + expect(h.logs.join('\n')).not.toContain('acme-sentinel'); + expect(h.logs.join('\n')).toContain(`tagger changed e1: +[${labelLogLabel('acme-sentinel-invoice')}] -[]`); + }); + // Regression: a server push that fails must not abandon the local change or // the remaining flags — the queue retries the server side on reconnect. it('keeps the local change when the server push fails', async () => { diff --git a/apps/desktop/test/unit/electron/services/follow-up-checker.test.ts b/apps/desktop/test/unit/electron/services/follow-up-checker.test.ts index 4cb5b5f6..8a4c7547 100644 --- a/apps/desktop/test/unit/electron/services/follow-up-checker.test.ts +++ b/apps/desktop/test/unit/electron/services/follow-up-checker.test.ts @@ -35,7 +35,9 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/notification-service', () => ({ notifyFollowUpDue: (notice: Record) => h.notified.push(notice), })); -vi.mock('@sarvinbox/core', () => ({ +vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }), })); diff --git a/apps/desktop/test/unit/electron/services/gmail-label-api.test.ts b/apps/desktop/test/unit/electron/services/gmail-label-api.test.ts index 3f612052..56df26b0 100644 --- a/apps/desktop/test/unit/electron/services/gmail-label-api.test.ts +++ b/apps/desktop/test/unit/electron/services/gmail-label-api.test.ts @@ -8,11 +8,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; * provisioning PATCH storm) and names match case-insensitively. */ -vi.mock('@sarvinbox/core', () => ({ - createLogger: () => ({ - info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, trace: () => {}, - }), -})); +const logLines = vi.hoisted(() => [] as string[]); +vi.mock('@sarvinbox/core', async () => { + const record = (...args: unknown[]) => { logLines.push(args.map(String).join(' ')); }; + return { + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), + createLogger: () => ({ info: record, warn: record, error: record, debug: record, trace: record }), + }; +}); import { deleteGmailLabelsUnder, @@ -42,6 +46,7 @@ const jsonResponse = (body: unknown, status = 200): Response => }) as unknown as Response; beforeEach(() => { + logLines.length = 0; calls = []; labels = []; failures = []; @@ -265,3 +270,25 @@ describe('deleteGmailLabelsUnder', () => { await expect(deleteGmailLabelsUnder('tok', 'P')).resolves.toBe(0); }); }); + +describe('what reaches the log', () => { + const NAME = 'Sarv Inbox/Acme Sentinel Invoices'; + + // Breaks: '[GmailLabels] created ""' and every failure line wrote the + // label's name (a category or label the user named), and a failure wrote + // Gmail's error body, which can quote it again. + it('names a label by its label code and a failure by its kind', async () => { + const { labelLogLabel } = await import('../../../helpers/core-log-helpers'); + failures = [{ match: (c) => c.method === 'POST' && !!c.body?.color, status: 400, text: `Invalid color for ${NAME}` }]; + + await expect(ensureGmailLabelColor('tok', NAME, 'blue')).resolves.toBe(true); + failures = [{ match: () => true, throws: true }]; + await renameGmailLabel('tok', NAME, `${NAME} 2`); + await deleteGmailLabelsUnder('tok', NAME); + + expect(logLines.filter((l) => l.includes('Sentinel'))).toEqual([]); + expect(logLines).toContain(`[GmailLabels] create ${labelLogLabel(NAME)} with color failed: Error`); + expect(logLines).toContain(`[GmailLabels] created ${labelLogLabel(NAME)} (plain — color rejected)`); + expect(logLines).toContain('[GmailLabels] rename best-effort failed: Error'); + }); +}); diff --git a/apps/desktop/test/unit/electron/services/oauth-loopback.test.ts b/apps/desktop/test/unit/electron/services/oauth-loopback.test.ts index 2faf56aa..1878f16e 100644 --- a/apps/desktop/test/unit/electron/services/oauth-loopback.test.ts +++ b/apps/desktop/test/unit/electron/services/oauth-loopback.test.ts @@ -390,6 +390,22 @@ describe('loopback callback listener', () => { expect(h.saved).toEqual([{ provider: 'sarv', email: 'user@sarv.com' }]); }); + // Regression: the user-info request carries the new access token, and a + // redirect from the provider's endpoint would have sent it on to wherever + // the Location pointed. It must refuse redirects (Node: redirect: 'error'). + it('fetches the signed-in user\'s profile without following redirects', async () => { + stubUserInfo('user@sarv.com'); + const flow = start(); + const { redirectUri, state } = await nextAuthUrl(); + + await get(`${redirectUri}?code=auth-code&state=${state}`); + await flow; + + const fetchMock = vi.mocked(globalThis.fetch); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]![1]).toMatchObject({ redirect: 'error' }); + }); + // CSRF: a callback for a state we never issued completes nothing, and must // not settle (or close the listener under) the sign-in that is really waiting. it('completes nothing for a state it never issued, and leaves the real sign-in waiting', async () => { diff --git a/apps/desktop/test/unit/electron/services/outbox-service.test.ts b/apps/desktop/test/unit/electron/services/outbox-service.test.ts index 61e7331c..d3165cbf 100644 --- a/apps/desktop/test/unit/electron/services/outbox-service.test.ts +++ b/apps/desktop/test/unit/electron/services/outbox-service.test.ts @@ -73,6 +73,8 @@ const h = vi.hoisted(() => { }); vi.mock('@sarvinbox/core', async () => ({ + // The real log helpers (see the helper): product log lines go through them. + ...(await import('../../../helpers/core-log-helpers')), SendQueue: h.FakeSendQueue, // The REAL due-time helper: the wake-up timer's whole job is to honour it, so // a stub here would make these tests agree with themselves and nothing else. diff --git a/apps/desktop/test/unit/electron/services/sender-identity-service.test.ts b/apps/desktop/test/unit/electron/services/sender-identity-service.test.ts index 476260b7..4231b6a2 100644 --- a/apps/desktop/test/unit/electron/services/sender-identity-service.test.ts +++ b/apps/desktop/test/unit/electron/services/sender-identity-service.test.ts @@ -7,6 +7,7 @@ const h = vi.hoisted(() => ({ blobs: new Map(), runtimes: [] as Array<[string, { storage: unknown; syncEngine: null; smtpClient: null }]>, sent: [] as Array<{ channel: string; payload: unknown }>, + setBlobError: null as Error | null, })); vi.mock('../../../../electron/shared', () => ({ @@ -17,7 +18,10 @@ vi.mock('../../../../electron/shared', () => ({ vi.mock('../../../../electron/services/core-db', () => ({ getCoreDb: () => { throw new Error('the core DB is not opened in tests'); }, getBlob: (k: string) => h.blobs.get(k) ?? null, - setBlob: (k: string, v: Buffer) => { h.blobs.set(k, v); }, + setBlob: (k: string, v: Buffer) => { + if (h.setBlobError) throw h.setBlobError; + h.blobs.set(k, v); + }, })); vi.mock('../../../../electron/services/net-fetch', () => ({ chromiumFetch: vi.fn() })); // Only the startup probe is faked, so the scheduler's report can be watched; @@ -419,6 +423,36 @@ describe('sender identity — what reaches the log', () => { expect(logs.containing('sentinel-')).toEqual([]); expect(logs.containing('SENTINEL')).toEqual([]); }); + + // Breaks: '[SenderIdentity] could not list sender domains: ' and + // 'tick failed: ' wrote the error text, which names a sender's host + // (a refused destination's message does) — now the failure's kind only. + it('logs a failed account and a failed tick by their kind, naming no host', async () => { + const { svc } = harness(); + const refused = Object.assign(new Error('refused https://sentinel-host.example:8443/logo.svg (not a public address)'), { code: 'EREFUSED' }); + h.runtimes = [ + ['acct-1', { storage: { getRecentSenderDomains: async () => { throw refused; } }, syncEngine: null, smtpClient: null }], + ]; + vi.spyOn(svc, 'refreshStale').mockRejectedValueOnce(new Error('lookup of sentinel-shop.example failed')); + + expect(await senderIdentityTick(svc)).toBe(0); + + expect(logs.containing('sentinel-')).toEqual([]); + expect(logs.containing('[SenderIdentity] could not list sender domains: EREFUSED')).toHaveLength(1); + expect(logs.containing('[SenderIdentity] tick failed: Error')).toHaveLength(1); + }); + + // Breaks: a policy that could not be saved logged the store's error text. + it('logs an unsaved policy by the failure kind only', () => { + h.setBlobError = new Error('SQLITE_FULL: database or disk is full writing sentinel-key'); + try { + setSenderIdentityPolicy({ logos: true, favicons: false, gravatar: false }); + } finally { + h.setBlobError = null; + } + expect(logs.containing('sentinel-')).toEqual([]); + expect(logs.containing('[SenderIdentity] policy not persisted: Error')).toHaveLength(1); + }); }); /** diff --git a/apps/desktop/test/unit/electron/services/startup-thread-repair.test.ts b/apps/desktop/test/unit/electron/services/startup-thread-repair.test.ts index 2984d475..1d802d6a 100644 --- a/apps/desktop/test/unit/electron/services/startup-thread-repair.test.ts +++ b/apps/desktop/test/unit/electron/services/startup-thread-repair.test.ts @@ -51,9 +51,17 @@ vi.mock('../../../../electron/shared', () => ({ getAllAccountRuntimes: () => h.runtimes, })); -vi.mock('@sarvinbox/core', () => ({ - createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, trace: () => {} }), -})); +const logLines = vi.hoisted(() => [] as string[]); +vi.mock('@sarvinbox/core', async () => { + const record = (...args: unknown[]) => { logLines.push(args.map(String).join(' ')); }; + return { + createLogger: () => ({ info: record, warn: record, error: record, debug: record, trace: record }), + // The real labels: what a line says about the account is under test. + ...(await vi.importActual( + '../../../../../../packages/core/src/utils/log-labels', + )), + }; +}); vi.mock('../../../../electron/services/core-db', () => ({ getMeta: (k: string) => h.meta.get(k) ?? null, @@ -70,6 +78,7 @@ const advance = (ms: number) => vi.advanceTimersByTimeAsync(ms); beforeEach(() => { vi.useFakeTimers(); + logLines.length = 0; const storage = freshStorage(); h = { storage, engine: { isConnected: () => true }, accountId: 'acct-1', @@ -251,6 +260,28 @@ describe('startup-thread-repair', () => { // // `h.meta` stands in for `registry_meta` in the core DB, so it persists across a // `load()` exactly as the real table persists across a relaunch. +describe('startup-thread-repair — what reaches the log', () => { + // Breaks: '[ThreadRepair] : …' wrote the id, which spells out the + // owner's address (acct----), on every pass and + // every failure, in a release app.log. + it('names the account by its label on success and on failure', async () => { + const { accountIdFor, accountLogLabel } = await import('../../../../../../packages/core/src/utils/log-labels').then( + async (labels) => ({ ...labels, ...(await import('../../../../../../packages/core/src/utils/id')) }), + ); + h.accountId = accountIdFor('owner.sentinel@example.com', 'imap.example.com'); + const svc = await load(); + h.repairThrows = true; + svc.startStartupThreadRepair(); + await advance(45_000); + h.repairThrows = false; + await advance(60_000); + + expect(logLines.filter((l) => l.includes('sentinel'))).toEqual([]); + expect(logLines.some((l) => l.includes(`[ThreadRepair] ${accountLogLabel(h.accountId)} failed (will retry)`))).toBe(true); + expect(logLines.some((l) => l.startsWith(`[ThreadRepair] ${accountLogLabel(h.accountId)}: `))).toBe(true); + }); +}); + describe('startup-thread-repair — the window survives a relaunch', () => { /** One app run: fresh module registry, same meta store, repair fires once. */ async function runOnce(): Promise { diff --git a/apps/desktop/test/unit/electron/services/unified-pipeline-auto-send-log.test.ts b/apps/desktop/test/unit/electron/services/unified-pipeline-auto-send-log.test.ts index 8a5c3c61..144e1bbd 100644 --- a/apps/desktop/test/unit/electron/services/unified-pipeline-auto-send-log.test.ts +++ b/apps/desktop/test/unit/electron/services/unified-pipeline-auto-send-log.test.ts @@ -353,6 +353,37 @@ describe('auto-draft and auto-send — the sender stays out of the log', () => { }); }); +describe('autoDraftReply — failures, as logged', () => { + // Breaks: "IMAP draft save error for :" logged the whole error, whose + // message quotes the server's APPEND answer (the Drafts folder's name, the + // draft text) — the error's kind is all that may reach app.log. + it('logs a Drafts save that throws by its kind and code, never its text', async () => { + await replyWorthy('e4'); + h.draftAnswer = JSON.stringify({ subject: 'Re: Budget', body: 'Approved.', suggestedCc: [], reasoning: 'Direct ask' }); + h.saveError = Object.assign(new Error(`APPEND "Clients/${SENTINEL}" refused: ${SENTINEL}`), { code: 'EAPPEND' }); + + await autoDraftReply('e4', account.storage); + + expect(logs.containing(SENTINEL)).toEqual([]); + const line = logs.containing('IMAP draft save error for e4:'); + expect(line).toHaveLength(1); + expect(line[0]).toContain("code: 'EAPPEND'"); + }); + + // Breaks: a failed save's returned error text (which can carry the + // encryption library's message) is written after our own words. + it('logs a refused Drafts save by the words before its detail only', async () => { + await replyWorthy('e5'); + h.draftAnswer = JSON.stringify({ subject: 'Re: Budget', body: 'Approved.', suggestedCc: [], reasoning: 'Direct ask' }); + h.saveResult = { success: false, error: `The draft could not be encrypted, so it was not saved: key for ${SENTINEL} expired` }; + + await autoDraftReply('e5', account.storage); + + expect(logs.containing(SENTINEL)).toEqual([]); + expect(logs.containing('IMAP draft save failed for e5: The draft could not be encrypted, so it was not saved')).toHaveLength(1); + }); +}); + describe('drafterFallbackLabel', () => { // Breaks: the gate stops recognising either fallback ReplyDrafter writes, or // starts flagging an ordinary reasoning as one. diff --git a/apps/desktop/test/unit/electron/services/unified-pipeline-service-gmail-token.test.ts b/apps/desktop/test/unit/electron/services/unified-pipeline-service-gmail-token.test.ts index b0303d6a..92c1285e 100644 --- a/apps/desktop/test/unit/electron/services/unified-pipeline-service-gmail-token.test.ts +++ b/apps/desktop/test/unit/electron/services/unified-pipeline-service-gmail-token.test.ts @@ -1,4 +1,4 @@ -import { addTag, GMAIL_CLASSIFICATION_CATEGORY_SLUGS, SARV_LABEL_PARENT } from '@sarvinbox/core'; +import { accountLogLabel, addTag, GMAIL_CLASSIFICATION_CATEGORY_SLUGS, SARV_LABEL_PARENT } from '@sarvinbox/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; /** @@ -557,7 +557,8 @@ describe('token trace logging', () => { expect(h.log.trace).toEqual(expect.arrayContaining([ expect.stringContaining('token=yes (a@gmail.com)'), expect.stringContaining('no gmail OAuth grant for b@gmail.com'), - expect.stringContaining('no address for acct=acct-c'), + // Changed deliberately (log privacy): the account id is written as its label. + expect.stringContaining(`no address for acct=${accountLogLabel('acct-c')}`), expect.stringContaining('token=no (d@gmail.com)'), expect.stringContaining('no address for acct=default'), ])); @@ -614,7 +615,9 @@ describe('mirrorCategoryLabels (a freshly categorized mail)', () => { // Transient: a failed refresh labels plain for now; the next mirror after // the refresh recovers colours the label with B's own grant. The refresh // here rejects with a bare string, not an Error, and the warning must still - // say whose token failed and why. + // say whose token failed. Changed deliberately (log privacy): it says why by + // the failure's kind only (failureCause), and a bare string's kind is + // `string` — its text could be anything, so it is not written. it('falls back to plain labels while the refresh fails, then colours on recovery', async () => { const a = addAccount({ id: 'acct-a', email: 'a@gmail.com', auth: 'oauth' }); const b = addAccount({ id: 'acct-b', email: 'b@gmail.com', auth: 'oauth', mail: [[201, 'travel']] }); @@ -622,7 +625,7 @@ describe('mirrorCategoryLabels (a freshly categorized mail)', () => { await mirrorCategoryLabels(b.storage, b.emails[0], ['travel']); expect(names(b)).toEqual([PARENT, label('Travel')]); expect(coloured(b)).toEqual([]); - expect(h.log.warn.some((l) => l.includes('token fetch failed for b@gmail.com') && l.includes('ETIMEDOUT'))).toBe(true); + expect(h.log.warn.some((l) => l.includes('token fetch failed for b@gmail.com') && l.includes('string'))).toBe(true); h.refreshFailing.clear(); await mirrorCategoryLabels(b.storage, b.emails[0], ['travel']); diff --git a/apps/desktop/test/unit/electron/services/update-service.test.ts b/apps/desktop/test/unit/electron/services/update-service.test.ts index 1e97eab6..d55d3a65 100644 --- a/apps/desktop/test/unit/electron/services/update-service.test.ts +++ b/apps/desktop/test/unit/electron/services/update-service.test.ts @@ -105,6 +105,10 @@ vi.mock('@sarvinbox/core', async () => { }, withTimeout: timeout.withTimeout, isTimeoutError: timeout.isTimeoutError, + // The real path helpers: the updater's own log goes through them. + ...(await vi.importActual( + '../../../../../../packages/core/src/utils/log-paths', + )), }; }); @@ -1539,3 +1543,21 @@ describe('signed update manifest (CASA M-3)', () => { service.stopUpdateService(); }); }); + +describe("electron-updater's own log", () => { + // Breaks if the updater's lines ("downloaded to /Users//Library/ + // Caches/…", an error's stack) write the user's home folder, and with it + // their name, into app.log. + it('writes the home folder as ~ in a message and in an error stack', async () => { + const { homedir } = await import('os'); + const home = homedir(); + const { describeUpdaterMessage } = await load(); + const cache = join(home, 'Library', 'Caches', 'sarv-inbox-updater', 'pending', 'Sarv-Inbox.zip'); + + expect(describeUpdaterMessage(`Update downloaded to ${cache}`)).not.toContain(home); + expect(describeUpdaterMessage(`Update downloaded to ${cache}`)).toContain('downloaded to ~'); + const error = new Error(`ENOENT: no such file, open '${cache}'`); + error.stack = `Error: ENOENT: no such file, open '${cache}'\n at ${join(home, 'app', 'main.js')}:1:1`; + expect(describeUpdaterMessage(error)).not.toContain(home); + }); +}); diff --git a/apps/desktop/test/unit/electron/utils/file-logger.test.ts b/apps/desktop/test/unit/electron/utils/file-logger.test.ts index bb975e52..86fcc089 100644 --- a/apps/desktop/test/unit/electron/utils/file-logger.test.ts +++ b/apps/desktop/test/unit/electron/utils/file-logger.test.ts @@ -1,6 +1,6 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, truncateSync, writeFileSync } from 'fs'; import { tmpdir } from 'os'; -import { join } from 'path'; +import { join, sep } from 'path'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -336,6 +336,61 @@ describe('email addresses (CASA L-7)', () => { }); }); +describe('account ids and the home folder', () => { + const ACCOUNT_ID = 'acct-jane-doe-example-com--imap-example-com'; + + // Breaks if a RELEASE app.log spells out the owner's address through an + // account id (acct----), which every per-account + // scheduler line used to carry, in the text or in a legacy DB-named logger. + it('replaces account ids with their label in a release, in main and renderer lines', async () => { + const { accountLogLabel } = await import('@sarvinbox/core'); + const logger = await load(); + logger.muteTerminalOutput(); + logger.initFileLogger({ redactAddresses: true }); + stream().lines.length = 0; + + console.log(`[2026-06-15 12:00:00.000] [INFO] [backfill:sarvinbox-${ACCOUNT_ID}.db] skipping ${ACCOUNT_ID} — churning`); + logger.appendExternalLog('renderer', 'info', `split:${ACCOUNT_ID}`, `split acct=${ACCOUNT_ID} thread=t1`); + + const written = stream().lines.join(''); + expect(written).not.toContain('jane-doe'); + expect(stream().lines[0]).toContain(`skipping ${accountLogLabel(ACCOUNT_ID)} — churning`); + expect(stream().lines[0]).toContain(`[backfill:sarvinbox-${accountLogLabel(ACCOUNT_ID)}.db]`); + expect(stream().lines[1]).toContain(`split acct=${accountLogLabel(ACCOUNT_ID)} thread=t1`); + }); + + // Breaks if the DEV log loses the account ids the developer debugs with. + it('keeps account ids in a dev run', async () => { + const logger = await load(); + logger.muteTerminalOutput(); + logger.initFileLogger(); + stream().lines.length = 0; + + console.log(`skipping ${ACCOUNT_ID}`); + + expect(stream().lines[0]).toContain(ACCOUNT_ID); + }); + + // Breaks if an absolute path (an updater cache, a stack frame, a DB path) + // names the user through their home folder — in dev and release alike. + it('writes the home folder as ~ in every line, and the start line names no path', async () => { + const { homedir } = await import('os'); + const home = homedir(); + const logger = await load(); + logger.muteTerminalOutput(); + logger.initFileLogger(); + + expect(stream().lines.find((l) => l.includes('[file-logger]'))).toContain('writing local logs to /app.log'); + stream().lines.length = 0; + console.log(`downloaded to ${join(home, 'Library', 'Caches', 'u.zip')}`); + logger.appendExternalLog('renderer', 'warn', '', `at ${join(home, 'x.js')}`); + + expect(stream().lines.join('')).not.toContain(home); + expect(stream().lines[0]).toContain(`downloaded to ~${sep}${join('Library', 'Caches', 'u.zip')}`); + expect(stream().lines[1]).toContain(`at ~${sep}x.js`); + }); +}); + describe('the console tee', () => { const initMuted = async (): Promise => { const logger = await load(); diff --git a/apps/desktop/test/unit/electron/utils/log-path.test.ts b/apps/desktop/test/unit/electron/utils/log-path.test.ts new file mode 100644 index 00000000..657d67cb --- /dev/null +++ b/apps/desktop/test/unit/electron/utils/log-path.test.ts @@ -0,0 +1,47 @@ +import { homedir } from 'os'; +import { join } from 'path'; + +import { describe, expect, it, vi } from 'vitest'; + +const h = vi.hoisted(() => ({ userData: '' as string, throws: false })); + +vi.mock('electron', () => ({ + app: { + getPath: () => { + if (h.throws) throw new Error('app not ready'); + return h.userData; + }, + }, +})); + +import { logPath, withoutHomeDir } from '../../../../electron/utils/log-path'; + +const HOME = homedir(); + +describe('logPath', () => { + // Breaks if a main-process line ("[CoreDB] opened …", "Created runtime -> + // …") writes an absolute path, which names the user through their home. + it('writes a data-folder path relative to and others relative to ~', () => { + h.userData = join(HOME, 'Library', 'Application Support', 'Sarv Inbox'); + h.throws = false; + expect(logPath(join(h.userData, 'sarvinbox-core.db'))).toBe('/sarvinbox-core.db'); + expect(logPath(join(HOME, 'Documents', 'extensions.json'))).toBe('~/Documents/extensions.json'); + }); + + // Breaks if a line logged before the app is ready (no userData yet) throws + // inside a catch instead of writing a safe path. + it('falls back to home when userData cannot be read', () => { + h.throws = true; + expect(logPath(join(HOME, 'x', 'y.db'))).toBe('~/x/y.db'); + h.throws = false; + }); +}); + +describe('withoutHomeDir', () => { + // Breaks if a library's message passes its absolute path straight through. + it('writes the home folder as ~', () => { + const out = withoutHomeDir(`open '${join(HOME, 'a.txt')}' failed`); + expect(out).not.toContain(HOME); + expect(out).toMatch(/^open '~[\\/]a\.txt' failed$/); + }); +}); diff --git a/apps/desktop/test/unit/src/components/email-detail/useFirstEmailSplit.test.tsx b/apps/desktop/test/unit/src/components/email-detail/useFirstEmailSplit.test.tsx index a1609b80..a5d89d4b 100644 --- a/apps/desktop/test/unit/src/components/email-detail/useFirstEmailSplit.test.tsx +++ b/apps/desktop/test/unit/src/components/email-detail/useFirstEmailSplit.test.tsx @@ -5,6 +5,7 @@ import { type FirstSplitGetResult, type FirstSplitRow, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { @@ -214,12 +215,15 @@ describe('useFirstEmailSplit — reading the cache', () => { await mount(AUTO, depsFor(bridge)); expect(latest!.state).toBe('unknown'); expect(run).not.toHaveBeenCalled(); - expect(warn.mock.calls.some((call) => String(call[0]).includes('get acct=acct-b thread=t1 failed'))).toBe(true); + // Changed deliberately (log privacy): the account id is its label, and an + // error is logged by its kind, never its text. + expect(warn.mock.calls.some((call) => String(call[0]).includes(`get acct=${accountLogLabel('acct-b')} thread=t1 failed`))).toBe(true); const threw: FirstSplitBridge = { ...bridge, get: vi.fn(async () => { throw new Error('ipc down'); }) }; await rerender({ ...AUTO, first: OTHER }, depsFor(threw)); expect(latest!.state).toBe('unknown'); - expect(warn.mock.calls.some((call) => String(call[0]).includes('threw: ipc down'))).toBe(true); + expect(warn.mock.calls.some((call) => String(call[0]).includes('threw: Error'))).toBe(true); + expect(warn.mock.calls.some((call) => String(call[0]).includes('ipc down'))).toBe(false); }); // THE race: the reader moved to another thread before the first read came diff --git a/apps/desktop/test/unit/src/services/first-split/job.test.ts b/apps/desktop/test/unit/src/services/first-split/job.test.ts index 75ab90b9..16b77957 100644 --- a/apps/desktop/test/unit/src/services/first-split/job.test.ts +++ b/apps/desktop/test/unit/src/services/first-split/job.test.ts @@ -1,5 +1,6 @@ // @vitest-environment happy-dom // The job reads first-email facts (a DOM split) and the settings in localStorage. +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { setLogLevel } from '@sarvinbox/core/logger'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -361,7 +362,8 @@ describe('the job queue', () => { bridge.seed('acct-a', 't4', singleQuote()); job.enqueue([ref('t4')]); await job.idle(); - expect(debug.mock.calls.some((call) => String(call[0]).includes('[TRACE] [FirstSplitJob] thread acct=acct-a thread=t4 -> skipped'))).toBe(true); + // Changed deliberately (log privacy): the account id is written as its label. + expect(debug.mock.calls.some((call) => String(call[0]).includes(`[TRACE] [FirstSplitJob] thread acct=${accountLogLabel('acct-a')} thread=t4 -> skipped`))).toBe(true); }); it('counts a thread whose processing threw as an error and carries on', async () => { diff --git a/apps/desktop/test/unit/src/services/first-split/store.test.ts b/apps/desktop/test/unit/src/services/first-split/store.test.ts index bea4c36b..a73382ca 100644 --- a/apps/desktop/test/unit/src/services/first-split/store.test.ts +++ b/apps/desktop/test/unit/src/services/first-split/store.test.ts @@ -1,6 +1,7 @@ // @vitest-environment happy-dom // The run splits real bodies (regions, cleaning) with the DOM. import { isUsableSplit, parseFirstSplitParts } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core/logger'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -390,11 +391,14 @@ describe('runFirstSplit — the log line of a run that threw', () => { expect(await runFirstSplit(B, { trigger: 'manual' }, flaky)).toMatchObject({ state: 'error' }); expect(logs.containing(SENTINEL)).toEqual([]); - expect(logs.containing('split acct=acct-a thread=t1 threw')).toEqual([ - "[WARN] [FirstSplit] split acct=acct-a thread=t1 threw { name: 'Error' }", + // Changed deliberately (log privacy): the account id is written as its label. + const a = accountLogLabel('acct-a'); + const b = accountLogLabel('acct-b'); + expect(logs.containing(`split acct=${a} thread=t1 threw`)).toEqual([ + `[WARN] [FirstSplit] split acct=${a} thread=t1 threw { name: 'Error' }`, ]); - expect(logs.containing('split acct=acct-b thread=t1 threw')).toEqual([ - "[WARN] [FirstSplit] split acct=acct-b thread=t1 threw { name: 'Error', code: 'ETIMEDOUT', status: 503 }", + expect(logs.containing(`split acct=${b} thread=t1 threw`)).toEqual([ + `[WARN] [FirstSplit] split acct=${b} thread=t1 threw { name: 'Error', code: 'ETIMEDOUT', status: 503 }`, ]); } finally { logs.stop(); diff --git a/apps/desktop/test/unit/src/store/slices/emails-slice.test.ts b/apps/desktop/test/unit/src/store/slices/emails-slice.test.ts index 99908cd3..a348e0ff 100644 --- a/apps/desktop/test/unit/src/store/slices/emails-slice.test.ts +++ b/apps/desktop/test/unit/src/store/slices/emails-slice.test.ts @@ -1,3 +1,4 @@ +import { folderLogLabel } from '@sarvinbox/core/log-labels'; import { getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core/logger'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { createStore } from 'zustand/vanilla'; @@ -1379,4 +1380,13 @@ describe('selectEmail — the view log line', () => { const { lines } = open('', 'e1', view); expect(lines.find((text) => text.includes('[View] selectEmail'))).toContain(`${expected}, pool=1 emails`); }); + + // Breaks: `view=` wrote a folder the user named (a client's or + // person's name) on every email opened in it; system folders stay readable. + it('logs a user-named folder as its folder label', () => { + const path = 'Clients/Sentinel Acme'; + const { lines } = open('', 'e1', { folders: [{ id: 'f1', path }] }); + expect(lines.find((text) => text.includes('[View] selectEmail'))).toContain(`view=${folderLogLabel(path)}, pool=1 emails`); + for (const text of lines) expect(text).not.toContain('Sentinel'); + }); }); diff --git a/apps/desktop/test/unit/src/store/slices/sync-slice.test.ts b/apps/desktop/test/unit/src/store/slices/sync-slice.test.ts index 44c184fc..cc4a7adf 100644 --- a/apps/desktop/test/unit/src/store/slices/sync-slice.test.ts +++ b/apps/desktop/test/unit/src/store/slices/sync-slice.test.ts @@ -1103,3 +1103,36 @@ describe('refreshVisibleViewForFolder — the AI category view in the log', () = for (const line of lines) expect(line.toLowerCase()).not.toContain('sentinel'); }); }); + +describe('syncSingleFolder — the folder in the log', () => { + const PATH = 'Clients/Sentinel Acme'; + + // Breaks: '[Store] syncSingleFolder: ……' wrote a folder the user + // named on every line of a sync, and the failure line wrote the server's + // error text, which can quote the name again. The folder is its label. + it('names the folder by its label, and a failure by its kind', async () => { + const { folderLogLabel } = await import('@sarvinbox/core/log-labels'); + const state: Record = { + syncing: false, syncingFolders: new Map(), noteSyncOk: vi.fn(), noteSyncFailure: vi.fn(), + loadFolders: vi.fn(async () => {}), folders: [], selectedFolderId: null, + }; + const set = (patch: Record) => { Object.assign(state, patch); }; + vi.resetModules(); + (globalThis as any).window = { electronAPI: { imap: { sync: vi.fn(async () => { throw new Error(`SELECT "${PATH}" failed: ${PATH} does not exist`); }) } } }; + (globalThis as any).localStorage = { getItem: () => null, setItem: () => {} }; + const mod = await import('../../../../../src/store/slices/sync-slice'); + const slice: any = mod.createSyncSlice(set as any, () => ({ ...slice, ...state }), {} as any); + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + await slice.syncSingleFolder(PATH); + } finally { + logs.stop(); + delete (globalThis as any).localStorage; + } + + expect(state.noteSyncFailure).toHaveBeenCalled(); + for (const line of logs.lines) expect(line).not.toContain('Sentinel'); + expect(logs.lines.some((line) => line.includes(`syncSingleFolder: Starting sync for ${folderLogLabel(PATH)}`))).toBe(true); + expect(logs.lines.some((line) => line.includes(`Failed to sync ${folderLogLabel(PATH)}:`) && line.includes("name: 'Error'"))).toBe(true); + }); +}); diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json index 296cf2d6..5ddd023a 100644 --- a/apps/desktop/tsconfig.json +++ b/apps/desktop/tsconfig.json @@ -97,7 +97,9 @@ // Same: where a Sarv token may be sent (the Blocklists tab's reputation warning). "@sarvinbox/core/token-destinations": ["../../packages/core/src/oauth/token-destinations.ts"], // Same: what a log line may say about text that is not ours (field names, sizes, a URL's scheme). - "@sarvinbox/core/log-text": ["../../packages/core/src/utils/log-text.ts"] + "@sarvinbox/core/log-text": ["../../packages/core/src/utils/log-text.ts"], + // Same: the stand-ins for the account, a user-named folder, label or AI category in a log line. + "@sarvinbox/core/log-labels": ["../../packages/core/src/utils/log-labels.ts"] } }, "include": ["src", "electron", "test", "../../packages/core/src/contact-enrichment"], diff --git a/apps/desktop/vite/renderer-aliases.ts b/apps/desktop/vite/renderer-aliases.ts index bbe7d803..c9d3f332 100644 --- a/apps/desktop/vite/renderer-aliases.ts +++ b/apps/desktop/vite/renderer-aliases.ts @@ -40,7 +40,7 @@ function coreSubpathAliases(desktopDir: string): Record { desktopDir, '../../packages/core/src/contact-enrichment/index.ts', ), - // Pure (zero imports) — same reasoning. + // Pure (only log-labels, itself pure) — same reasoning. '@sarvinbox/core/folder-mapping': resolve( desktopDir, '../../packages/core/src/config/folder-mapping.ts', @@ -135,7 +135,7 @@ function coreSubpathAliases(desktopDir: string): Record { desktopDir, '../../packages/core/src/utils/sender-identity-policy.ts', ), - // Pure (folder-mapping + message-id, both zero-import) — which rows of a + // Pure (folder-mapping + message-id, and log-labels/fnv1a under them) — which rows of a // thread ARE the conversation, and in what order. The thread view, the // message list and the AI view must answer with the SAME predicate main // counts, drafts and schedules by, or a draft renders as a sent message in @@ -203,6 +203,9 @@ function coreSubpathAliases(desktopDir: string): Record { // ours (field names, sizes, a URL's scheme), so renderer lines describe a // search or a model's answer by the same rules as main's. '@sarvinbox/core/log-text': resolve(desktopDir, '../../packages/core/src/utils/log-text.ts'), + // Pure (fnv1a only) — the stand-ins a log line uses for the account, a + // user-named folder, label or AI category, the same hash main writes. + '@sarvinbox/core/log-labels': resolve(desktopDir, '../../packages/core/src/utils/log-labels.ts'), }; } diff --git a/docs/legal/privacy-policy.md b/docs/legal/privacy-policy.md index 0788adfa..70c9ee10 100644 --- a/docs/legal/privacy-policy.md +++ b/docs/legal/privacy-policy.md @@ -70,9 +70,11 @@ password. unencrypted copy for that program and deletes it shortly after. The app also keeps a diagnostic log file there, readable only by your user account. It records what the app did (counts, sizes, the kind of a failure), not the - text of your mail, and in released versions email addresses are removed from - it. Neither the cache nor the log leaves your device unless you send it to - us; if you turn on crash reports, each report carries a trail of recent app + text of your mail. It names your accounts, and the folders, labels and AI + categories you created, only by short codes, and file locations without your + user folder; in released versions email addresses are removed from it too. + Neither the cache nor the log leaves your device unless you send it to us; + if you turn on crash reports, each report carries a trail of recent app activity (see 4.2). - **With your email provider.** Your mail stays on your provider's servers as usual. Changes you make in the app (reading, moving, deleting, sending, @@ -169,14 +171,16 @@ answering, the app asks again the next time it starts. A report can contain: - the error and where it happened; - your app version, operating system and language; - your mail server's host name; -- a shortened one-way hash of your email address, to group reports from the - same installation; -- a trail of recent app activity, such as connection and sync steps, which can - include the names of your mail folders. +- a random identifier created by the app on your computer, to group reports + from the same installation (it is not derived from your email address or + anything else about you); +- a trail of recent app activity, such as connection and sync steps. Folders, + labels and AI categories you created appear in it only as short codes, not + by name. Email addresses are removed from reports before they leave your device, and so -are passwords and access tokens wherever the app can recognise them; web -addresses are sent without their query strings. Reports do not include message +are passwords, access tokens, sign-in codes and keys wherever the app can +recognise them; web addresses are sent without their query strings. Reports do not include message bodies, attachments or memory dumps (snapshots of the app's memory). You can change your answer at any time in Settings → General → Send crash diff --git a/packages/core/src/config/folder-mapping.ts b/packages/core/src/config/folder-mapping.ts index b12415ad..f81b5a27 100644 --- a/packages/core/src/config/folder-mapping.ts +++ b/packages/core/src/config/folder-mapping.ts @@ -1,6 +1,8 @@ // Folder Mapping Configuration // Maps provider folders to virtual folders and controls visibility +import { folderLogLabel } from '../utils/log-labels'; + /** * Provider folder patterns to hide from UI * These folders are synced but not shown in sidebar @@ -535,7 +537,8 @@ export function describeFolderSyncState(folder: ClassifiableFolder): string { `server=${folder.serverMessageCount ?? 'unknown'}`, ]; if (folder.specialUse) parts.push(`specialUse=${folder.specialUse}`); - return `${folder.path} (${parts.join(', ')})`; + // A log line: a folder the user named is written as its label. + return `${folderLogLabel(folder.path)} (${parts.join(', ')})`; } /** @@ -555,7 +558,7 @@ export function describeDuplicateRoles(folders: ClassifiableFolder[]): string | const chosen = findFolderByType(folders, type); return ( `${type}: ${candidates.map(describeFolderSyncState).join(' | ')}` + - ` -> ${chosen ? chosen.path : 'none'}` + ` -> ${chosen ? folderLogLabel(chosen.path) : 'none'}` ); }) .join('; '); diff --git a/packages/core/src/imap/connection-pool.ts b/packages/core/src/imap/connection-pool.ts index b61fecb9..4756a05c 100644 --- a/packages/core/src/imap/connection-pool.ts +++ b/packages/core/src/imap/connection-pool.ts @@ -1,6 +1,7 @@ // IMAP Connection Pool for parallel folder sync import type { IMAPConfig, IIMAPClient } from '../types/imap'; +import { errorDiagnostic } from '../utils/error-diagnostic'; import { logger } from '../utils/logger'; import { isTimeoutError, withTimeout } from '../utils/timeout'; @@ -623,7 +624,7 @@ export class IMAPConnectionPool { taskQueue.length = 0; // cancel the rest of this run return; } - logger.error(`Pool: parallel task ${index} failed:`, error); + logger.error(`Pool: parallel task ${index} failed:`, errorDiagnostic(error)); errors.push(error as Error); // Don't throw - continue with other tasks } diff --git a/packages/core/src/imap/folder-syncer.ts b/packages/core/src/imap/folder-syncer.ts index 0282f2b0..174b0444 100644 --- a/packages/core/src/imap/folder-syncer.ts +++ b/packages/core/src/imap/folder-syncer.ts @@ -4,7 +4,9 @@ import { BACKFILL_UID_SPAN } from '../config/sync'; import type { IIMAPClient, IMAPFolder, FolderStatus } from '../types/imap'; import type { FolderRecord } from '../types/models'; import type { IEmailStorage } from '../types/storage'; +import { errorDiagnostic, failureCause } from '../utils/error-diagnostic'; import { generateFolderId } from '../utils/id'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { isWatermarkImpossible } from '../utils/sync-watermark'; @@ -273,7 +275,7 @@ export class FolderSyncer { const storedFolder = await storage.getFolderByPath(folder.path); if (!storedFolder) { - logger.warn(`Folder ${folder.path} not found in storage`); + logger.warn(`Folder ${folderLogLabel(folder.path)} not found in storage`); result.error = new Error(`Folder not found: ${folder.path}`); return result; } @@ -316,7 +318,7 @@ export class FolderSyncer { }); if (watermarkImpossible) { logger.warn( - `[watermark] ${folder.path}: stored lastSyncUid ${storedFolder.lastSyncUid} is above server UIDNEXT ` + `[watermark] ${folderLogLabel(folder.path)}: stored lastSyncUid ${storedFolder.lastSyncUid} is above server UIDNEXT ` + `${boxStatus.uidNext} (server holds ${serverCount}) — impossible, so incremental sync has been a no-op. ` + `Discarding it and forcing a full re-sync.`, ); @@ -325,7 +327,7 @@ export class FolderSyncer { } if (needsRecoverySync) { - logger.info(`Recovery sync needed for ${folder.path}: local=${localCount}, expected at least ${expectedMinCount}, server=${serverCount}`); + logger.info(`Recovery sync needed for ${folderLogLabel(folder.path)}: local=${localCount}, expected at least ${expectedMinCount}, server=${serverCount}`); // Reset lastSyncUid to force full sync await storage.updateFolder(storedFolder.id, { lastSyncUid: null, @@ -394,7 +396,7 @@ export class FolderSyncer { result.success = true; return result; } catch (error) { - logger.error(`Failed to sync folder ${folder.path}:`, error); + logger.error(`Failed to sync folder ${folderLogLabel(folder.path)}:`, errorDiagnostic(error)); result.error = error as Error; return result; } @@ -418,7 +420,7 @@ export class FolderSyncer { folder.uidValidity !== null && folder.uidValidity !== serverV; if (uidValidityChanged) { - logger.warn(`UIDVALIDITY changed for ${folder.path}: ${folder.uidValidity} -> ${serverV}`); + logger.warn(`UIDVALIDITY changed for ${folderLogLabel(folder.path)}: ${folder.uidValidity} -> ${serverV}`); // Re-key the folder NON-DESTRUCTIVELY. Every local uid here is now stale, but // a blind `deleteEmailsByFolder` (DELETE by tag) also destroyed multi-folder @@ -428,7 +430,7 @@ export class FolderSyncer { // folder. The folder then re-syncs from scratch and re-links with fresh uids. if (typeof storage.invalidateFolderMembership === 'function') { const r = await storage.invalidateFolderMembership(folder.id); - logger.info(`UIDVALIDITY re-key for ${folder.path}: ${r.unlinked} unlinked (kept in other folders), ${r.deleted} deleted`); + logger.info(`UIDVALIDITY re-key for ${folderLogLabel(folder.path)}: ${r.unlinked} unlinked (kept in other folders), ${r.deleted} deleted`); } else { await storage.deleteEmailsByFolder(folder.id); } @@ -487,7 +489,7 @@ export class FolderSyncer { const fetchCount = Math.min(options.maxMessages, boxStatus.messages); const startSeq = Math.max(1, boxStatus.messages - fetchCount + 1); - logger.info(`Full sync ${folder.path}: fetching ${startSeq}:${boxStatus.messages} (${fetchCount} messages) in batches of ${FULL_SYNC_BATCH}`); + logger.info(`Full sync ${folderLogLabel(folder.path)}: fetching ${startSeq}:${boxStatus.messages} (${fetchCount} messages) in batches of ${FULL_SYNC_BATCH}`); let inserted = 0; let updated = 0; @@ -518,7 +520,7 @@ export class FolderSyncer { // A single batch failing (timeout on a heavy chunk) must not abort the // whole sync — log it and keep going so the rest of the inbox still lands. failedBatches++; - logger.warn(`Full sync ${folder.path}: batch ${range} failed: ${(err as Error)?.message ?? err}; continuing`); + logger.warn(`Full sync ${folderLogLabel(folder.path)}: batch ${range} failed: ${failureCause(err)}; continuing`); continue; } @@ -548,7 +550,7 @@ export class FolderSyncer { } if (failedBatches > 0) { - logger.warn(`Full sync ${folder.path}: ${failedBatches} batch(es) failed; stored ${inserted + updated} of ${fetchCount}`); + logger.warn(`Full sync ${folderLogLabel(folder.path)}: ${failedBatches} batch(es) failed; stored ${inserted + updated} of ${fetchCount}`); } return { @@ -581,7 +583,7 @@ export class FolderSyncer { // (Observed: a Gmail INBOX pinned at "from UID 59804" for nine days while the // server's own EXISTS climbed by 144 — every sync reported "No new messages".) logger.info( - `Incremental sync ${folder.path}: from UID ${lastUID} ` + `Incremental sync ${folderLogLabel(folder.path)}: from UID ${lastUID} ` + `(server uidNext ${boxStatus.uidNext}, exists ${boxStatus.messages})`, ); @@ -607,7 +609,7 @@ export class FolderSyncer { // Check for new messages if (boxStatus.uidNext <= lastUID + 1) { - logger.info(`No new messages in ${folder.path}`); + logger.info(`No new messages in ${folderLogLabel(folder.path)}`); return { success: true, messagesProcessed: 0, @@ -750,7 +752,7 @@ export class FolderSyncer { if (typeof client.fetchMessagesByUidRange !== 'function') { // Client can't page by UID range — don't spin; mark done so the scheduler // stops selecting this folder (search still works over whatever synced). - logger.warn(`Backfill ${folder.path}: client lacks fetchMessagesByUidRange — skipping backfill`); + logger.warn(`Backfill ${folderLogLabel(folder.path)}: client lacks fetchMessagesByUidRange — skipping backfill`); await storage.updateFolder(folder.id, { backfillComplete: true }); return { ...noop, loUid, hiUid, done: true }; } @@ -779,7 +781,7 @@ export class FolderSyncer { }); logger.info( - `Backfill ${folder.path}: UID ${loUid}:${hiUid} → ${messages.length} fetched, ${inserted} new` + `Backfill ${folderLogLabel(folder.path)}: UID ${loUid}:${hiUid} → ${messages.length} fetched, ${inserted} new` + `${done ? ' — COMPLETE (reached bottom)' : ` (next floor ${loUid})`}`, ); diff --git a/packages/core/src/imap/imapflow-client.ts b/packages/core/src/imap/imapflow-client.ts index 9bcb8064..83111970 100644 --- a/packages/core/src/imap/imapflow-client.ts +++ b/packages/core/src/imap/imapflow-client.ts @@ -47,7 +47,9 @@ import { headerValueFromText, } from '../utils/bulk-mail'; import { resolveConnectionSecurity, starttlsUnavailableMessage } from '../utils/connection-security'; +import { failureCause } from '../utils/error-diagnostic'; import { GMAIL_CLASSIFICATION_CATEGORY_SLUGS } from '../utils/gmail-labels'; +import { folderLogLabel, labelLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { messageIdKey } from '../utils/message-id'; import { createMutex, type Mutex } from '../utils/mutex'; @@ -89,6 +91,13 @@ const DEFAULT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024; const ATTACHMENT_WIRE_ALLOWANCE = 1024 * 1024; const MAX_ATTACHMENT_WIRE_BYTES = DEFAULT_ATTACHMENT_MAX_BYTES * 4 + ATTACHMENT_WIRE_ALLOWANCE; +/** + * A message flag for a log line: a system flag (`\Seen`, `\Flagged`) as written, + * any keyword as a `label#` hash. Keywords are how categories and tags reach the + * server, so a custom one is a name the user chose. + */ +const flagLogText = (flag: string): string => (flag.startsWith('\\') ? flag : labelLogLabel(flag)); + interface IdleHandlers { exists: (data: ExistsEvent) => void; flags: (data: FlagsEvent) => void; @@ -571,7 +580,7 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { if (logger.isLevelEnabled('trace')) { void wrapped.then( () => logger.trace(`IMAP ${label} (${Date.now() - started}ms)`), - (e) => logger.trace(`IMAP ${label} FAILED (${Date.now() - started}ms): ${(e as Error)?.message ?? e}`), + (e) => logger.trace(`IMAP ${label} FAILED (${Date.now() - started}ms): ${failureCause(e)}`), ); } return wrapped; @@ -684,7 +693,7 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { // returns highestModseq — no separate code path needed. const status = await this.openFolder(folderPath); if (status.highestModseq) { - logger.debug(`CONDSTORE: ${folderPath} highestModseq=${status.highestModseq}`); + logger.debug(`CONDSTORE: ${folderLogLabel(folderPath)} highestModseq=${status.highestModseq}`); } return status; } @@ -875,7 +884,7 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { if (limit <= 0) return null; // unlimited / not meaningful — nothing to show return { used, limit }; } catch (err) { - logger.debug(`getQuota failed (ignored): ${(err as Error)?.message ?? err}`); // low-frequency call + logger.debug(`getQuota failed (ignored): ${failureCause(err)}`); // low-frequency call return null; } } @@ -1509,7 +1518,7 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { if (failedBatches > 0) { logger.warn( - `Batched FLAGS fetch on ${this.currentFolder}: ${failedBatches} batch(es) failed; ` + `Batched FLAGS fetch on ${folderLogLabel(this.currentFolder)}: ${failedBatches} batch(es) failed; ` + `got flags for ${out.length}/${uids.length} uids`, ); } @@ -1851,12 +1860,12 @@ export class ImapFlowClient extends EventEmitter implements IIMAPClient { // webmail simply doesn't render. const keywords = flags.filter((f) => !f.startsWith('\\')); if (keywords.length > 0) { - const folder = (this.client as any)?.mailbox?.path ?? '?'; - logger.info(`[IMAP] UID STORE ${uids.join(',')} +FLAGS (${keywords.join(' ')}) in "${folder}" → matched=${matched}`); + const folder = (this.client as any)?.mailbox?.path; + logger.info(`[IMAP] UID STORE ${uids.join(',')} +FLAGS (${keywords.map(flagLogText).join(' ')}) in "${folder ? folderLogLabel(folder) : '?'}" → matched=${matched}`); if (process.env.SARV_DEBUG_KEYWORDS === '1') { try { const list = await this.client!.fetchAll(uids.join(','), { uid: true, flags: true, ...(this.supportsGmailLabels() ? { labels: true } : {}) }, { uid: true }); - const back = list.map((m: any) => `uid ${m.uid}: [${[...(m.flags ?? [])].join(' ')}]`); + const back = list.map((m: any) => `uid ${m.uid}: [${[...(m.flags ?? [])].map(flagLogText).join(' ')}]`); logger.info(`[IMAP] server FLAGS after STORE → ${back.join('; ') || '(no messages returned)'}`); } catch (e) { logger.warn(`[IMAP] keyword verify FETCH failed: ${(e as Error).message}`); diff --git a/packages/core/src/imap/incremental-fetch.ts b/packages/core/src/imap/incremental-fetch.ts index e4b4b8be..1e70b3d5 100644 --- a/packages/core/src/imap/incremental-fetch.ts +++ b/packages/core/src/imap/incremental-fetch.ts @@ -15,6 +15,7 @@ // incremental path — never duplicate the windowing. import type { FetchOptions, IIMAPClient, IMAPMessage } from '../types/imap'; +import { failureCause } from '../utils/error-diagnostic'; import { logger } from '../utils/logger'; // ── Pacing ────────────────────────────────────────────────────────────────── @@ -144,7 +145,7 @@ function createWindowRun(windowOptions: WindowedFetchOptions | undefined) { * how a slow server became "no new mail at all". */ function keepPartial(collected: number, error: unknown): void { - logger.warn(`New-mail fetch stopped early with ${collected} message(s) kept: ${(error as Error)?.message ?? error}`); + logger.warn(`New-mail fetch stopped early with ${collected} message(s) kept: ${failureCause(error)}`); } /** diff --git a/packages/core/src/imap/label-strategy.ts b/packages/core/src/imap/label-strategy.ts index 5cfcf09e..72803962 100644 --- a/packages/core/src/imap/label-strategy.ts +++ b/packages/core/src/imap/label-strategy.ts @@ -30,6 +30,7 @@ // the caller additionally guards re-runs with a local "mirrored" marker. import { IMAPError, type IIMAPClient } from '../types/imap'; import { mapGmailLabels } from '../utils/gmail-labels'; +import { categoryLogLabel, folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { detectProvider } from '../utils/provider'; import { trimChars } from '../utils/trim-chars'; @@ -202,7 +203,7 @@ class KeywordStrategy implements LabelStrategy { if (this.delimiter === undefined) this.delimiter = (await this.client.getHierarchyDelimiter?.()) ?? '/'; const nested = folderPathForCategory(cat, this.delimiter); if (await deleteIfEmpty(this.client, nested)) { - logger.info(`[LabelStrategy] removed nested label "${nested}" (keyword labels need no folder)`); + logger.info(`[LabelStrategy] removed nested label "${folderLogLabel(nested)}" (keyword labels need no folder)`); } // The parent goes only once nothing is left under it — CHECKED, not assumed. // Plenty of servers will happily DELETE a mailbox that still has inferiors @@ -330,7 +331,7 @@ class FolderStrategy implements LabelStrategy { const dest = await this.path(cat); // Provisioning path (once per category per account per session) — log the // exact CREATE commands we send so the Sarv/IMAP label setup is visible. - logger.info(`[LabelStrategy] Sarv IMAP ensure — CREATE "${SARV_LABEL_PARENT}"; CREATE "${dest}" (category "${cat.slug}")`); + logger.info(`[LabelStrategy] Sarv IMAP ensure — CREATE "${SARV_LABEL_PARENT}"; CREATE "${folderLogLabel(dest)}" (category ${categoryLogLabel(cat.slug, false)})`); await this.client.createMailbox(SARV_LABEL_PARENT); await this.client.createMailbox(dest); } diff --git a/packages/core/src/imap/message-processor.ts b/packages/core/src/imap/message-processor.ts index 66af7dbd..cb743db8 100644 --- a/packages/core/src/imap/message-processor.ts +++ b/packages/core/src/imap/message-processor.ts @@ -23,12 +23,13 @@ import type { IEmailStorage } from '../types/storage'; import { hasCalendarMimePart, sanitizeIcsText } from '../utils/calendar'; import { hasCidRefs, resolveCidImages, type CidImagePart } from '../utils/cid-images'; import { createDeferredFetchError } from '../utils/deferred-fetch-error'; -import { errorDiagnostic } from '../utils/error-diagnostic'; +import { errorDiagnostic, failureCause } from '../utils/error-diagnostic'; import { collectFilterActions, computeFilterActionResult } from '../utils/filters'; import { refreshCountsForFolders } from '../utils/folder-counts'; import { mapGmailLabels, matchKnownCategory, type GmailFolderRole, type KnownCategory } from '../utils/gmail-labels'; import { htmlToPlainText } from '../utils/html-text'; import { emailContentHash, generateId, generateThreadId, synthesizedMessageId } from '../utils/id'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { SIMPLE_PARSER_OPTIONS } from '../utils/mail-parse'; import { @@ -368,7 +369,7 @@ export class MessageProcessor { const fn = this.serverActions[action] as ((...a: Parameters) => Promise) | undefined; if (!fn || !(uid > 0)) return false; fn(...args).catch((err: unknown) => { - logger.warn(`[Ingest] Server-side ${action} failed for uid ${uid} in ${String(args[0])}: ${(err as Error)?.message ?? err}`); + logger.warn(`[Ingest] Server-side ${action} failed for uid ${uid} in ${folderLogLabel(args[0])}: ${failureCause(err)}`); }); return true; } @@ -464,7 +465,7 @@ export class MessageProcessor { // past it, or the sync re-fetches the same broken message forever. const usable = batch.filter((message) => { if (message.envelope) return true; - logger.error(`Skipping message UID ${message.uid} in ${folderPath}: no ENVELOPE`); + logger.error(`Skipping message UID ${message.uid} in ${folderLogLabel(folderPath)}: no ENVELOPE`); result.maxUid = Math.max(result.maxUid, message.uid); result.errors++; return false; @@ -962,7 +963,7 @@ export class MessageProcessor { } const changed = new Set([...updates.map((update) => update.id), ...classificationUpdates.map((update) => update.id)]); logger.info( - `[GmailLabels] ${folder.path}: repaired folder membership for ${updates.length} of ${labelRows.length} message(s)`, + `[GmailLabels] ${folderLogLabel(folder.path)}: repaired folder membership for ${updates.length} of ${labelRows.length} message(s)`, ); return { scanned: labelRows.length, updated: changed.size }; } @@ -1600,8 +1601,8 @@ export class MessageProcessor { if ((!message || wrongMessage) && target?.messageId) { logger.trace( wrongMessage - ? `Body fetch identity mismatch for ${emailId} (UID ${uid} in ${folderPath}): expected ${target.messageId}, server returned ${message?.envelope?.messageId}` - : `Body fetch: no message at UID ${uid || '(none)'} for ${emailId} in ${folderPath} — resolving by message-id`, + ? `Body fetch identity mismatch for ${emailId} (UID ${uid} in ${folderLogLabel(folderPath)}): expected ${target.messageId}, server returned ${message?.envelope?.messageId}` + : `Body fetch: no message at UID ${uid || '(none)'} for ${emailId} in ${folderLogLabel(folderPath)} — resolving by message-id`, ); // HEADER search is matched without angle brackets because servers // substring-match the raw header value; a bracketed query misses on some. @@ -1618,7 +1619,7 @@ export class MessageProcessor { // is evidence about the CONNECTION, not about the message — returning // null here made the prefetcher read "server has no such message" and // retire perfectly live mail. Defer instead; the next tick asks again. - logger.warn(`HEADER Message-ID search failed in ${folderPath}: ${(err as Error).message}`); + logger.warn(`HEADER Message-ID search failed in ${folderLogLabel(folderPath)}: ${failureCause(err)}`); throw createDeferredFetchError(`message-id search failed in "${folderPath}"`); } if (correctedUid === undefined) { @@ -1629,7 +1630,7 @@ export class MessageProcessor { if (hitCount > 0) { throw createDeferredFetchError(`UID ${uid} disagrees with the message-id search in "${folderPath}"`); } - logger.trace(`Could not re-resolve ${emailId} by message-id in ${folderPath} — leaving body empty`); + logger.trace(`Could not re-resolve ${emailId} by message-id in ${folderLogLabel(folderPath)} — leaving body empty`); return null; } const corrected = await fetchOne(correctedUid); @@ -1640,7 +1641,7 @@ export class MessageProcessor { logger.warn(`Re-resolved UID ${correctedUid} for ${emailId} still does not match — will retry`); throw createDeferredFetchError(`re-resolved UID ${correctedUid} did not match in "${folderPath}"`); } - logger.info(`Repaired ${uid ? 'stale' : 'missing'} UID for ${emailId} in ${folderPath}: ${uid || '(none)'} -> ${correctedUid}`); + logger.info(`Repaired ${uid ? 'stale' : 'missing'} UID for ${emailId} in ${folderLogLabel(folderPath)}: ${uid || '(none)'} -> ${correctedUid}`); await storage.updateEmail(emailId, { uid: correctedUid }); message = corrected; } @@ -1649,7 +1650,7 @@ export class MessageProcessor { // No uid AND no message-id to resolve by (or an expunged slot). Return a // VERDICT: body-prefetch counts a null as "unavailable" and, after a few // strikes, tags the row so it stops being re-seeded every tick. - logger.trace(`No message found for ${emailId} (UID ${uid || '(none)'} in ${folderPath})`); + logger.trace(`No message found for ${emailId} (UID ${uid || '(none)'} in ${folderLogLabel(folderPath)})`); return null; } @@ -1657,7 +1658,7 @@ export class MessageProcessor { // Identified the message, and the server handed back no source for it. A // verdict (there is nothing to download), but log it: this path was silent, // so an email stuck here looked identical in the log to one never tried. - logger.warn(`Body fetch: message for ${emailId} (UID ${message.uid || uid} in ${folderPath}) carries no source`); + logger.warn(`Body fetch: message for ${emailId} (UID ${message.uid || uid} in ${folderLogLabel(folderPath)}) carries no source`); return null; } @@ -1889,7 +1890,7 @@ export class MessageProcessor { try { serverFlags = await client.fetchAllFlags(folder.path); } catch (err) { - logger.warn(`Failed to fetch flags from server for ${folder.path}, skipping flag sync: ${(err as Error)?.message ?? err}`); + logger.warn(`Failed to fetch flags from server for ${folderLogLabel(folder.path)}, skipping flag sync: ${failureCause(err)}`); return false; } for (const sf of serverFlags) { @@ -1954,17 +1955,17 @@ export class MessageProcessor { const flags = await client.fetchFlagsOnly(allUids, touch, folder.path); for (const f of flags) setServerFlags(f); } catch (err) { - logger.warn(`Batched flag fetch failed for ${folder.path}: ${(err as Error).message}`); + logger.warn(`Batched flag fetch failed for ${folderLogLabel(folder.path)}: ${failureCause(err)}`); } } logger.info( - `syncFlags ${folder.path}: ${reason} — reconciling via SEARCH ALL ` + `syncFlags ${folderLogLabel(folder.path)}: ${reason} — reconciling via SEARCH ALL ` + `(${allUids.length} server uids, flags for ${serverFlagsMap.size})`, ); return true; } catch (err) { - logger.warn(`fetchAllUIDs deletion fallback failed for ${folder.path}: ${(err as Error).message}`); + logger.warn(`fetchAllUIDs deletion fallback failed for ${folderLogLabel(folder.path)}: ${failureCause(err)}`); return false; } }; @@ -2002,17 +2003,17 @@ export class MessageProcessor { const flags = await client.fetchFlagsOnly(windowUids, touch, folder.path); for (const f of flags) setServerFlags(f); } catch (err) { - logger.warn(`Windowed flag fetch failed for ${folder.path}: ${(err as Error).message}`); + logger.warn(`Windowed flag fetch failed for ${folderLogLabel(folder.path)}: ${failureCause(err)}`); } } logger.info( - `syncFlags ${folder.path}: ${reason} — WINDOWED reconcile ` + `syncFlags ${folderLogLabel(folder.path)}: ${reason} — WINDOWED reconcile ` + `(${windowUids.length} uids in last ${SYNC_RECENT_WINDOW_DAYS}d, flags for ${serverFlagsMap.size}); ` + `whole-folder deletion deferred to background backfill`, ); return true; } catch (err) { - logger.warn(`Windowed UID search failed for ${folder.path}: ${(err as Error).message}`); + logger.warn(`Windowed UID search failed for ${folderLogLabel(folder.path)}: ${failureCause(err)}`); return false; } }; @@ -2029,7 +2030,7 @@ export class MessageProcessor { // against the wrong mailbox. Refuse to reconcile on a mismatch. if (currentState?.path && currentState.path !== folder.path) { logger.warn( - `[syncFlags] ${folder.path}: ABORTED — connection has "${currentState.path}" selected, not "${folder.path}" (folder-selection race). Skipping to avoid cross-folder flag/deletion corruption.`, + `[syncFlags] ${folderLogLabel(folder.path)}: ABORTED — connection has "${folderLogLabel(currentState.path)}" selected, not "${folderLogLabel(folder.path)}" (folder-selection race). Skipping to avoid cross-folder flag/deletion corruption.`, ); return result; } @@ -2049,7 +2050,7 @@ export class MessageProcessor { Number.isFinite(currentUidValidity) && currentUidValidity > 0 && folder.uidValidity !== currentUidValidity) { logger.warn( - `[syncFlags] ${folder.path}: UIDVALIDITY changed (${folder.uidValidity} -> ${currentUidValidity}) — ` + `[syncFlags] ${folderLogLabel(folder.path)}: UIDVALIDITY changed (${folder.uidValidity} -> ${currentUidValidity}) — ` + `skipping flag/deletion reconcile; folder-sync will re-key and re-sync`, ); return result; @@ -2070,7 +2071,7 @@ export class MessageProcessor { // even on a large mailbox (acceptable off the hot path, in the background). const windowed = isLargeMailbox && options?.fullReconcile !== true; logger.info( - `[syncFlags] ${folder.path}: entering — server EXISTS=${serverExists ?? '?'}${windowed ? ' (LARGE — windowed reconcile)' : isLargeMailbox ? ' (LARGE — FULL background reconcile)' : ''}, condstore=${client.supportsCondstore()}, storedModseq=${folder.highestModseq ?? 0}, currentModseq=${currentModseq ?? '?'}`, + `[syncFlags] ${folderLogLabel(folder.path)}: entering — server EXISTS=${serverExists ?? '?'}${windowed ? ' (LARGE — windowed reconcile)' : isLargeMailbox ? ' (LARGE — FULL background reconcile)' : ''}, condstore=${client.supportsCondstore()}, storedModseq=${folder.highestModseq ?? 0}, currentModseq=${currentModseq ?? '?'}`, ); const storedModseq = folder.highestModseq ?? 0; @@ -2121,7 +2122,7 @@ export class MessageProcessor { await loadWindowedFlags(`CONDSTORE large-mailbox reconcile (${changed.length} delta changes)`); } else { logger.debug( - `syncFlags delta ${folder.path}: ${changed.length} changed since modseq ${storedModseq} (large mailbox — windowed flag re-read throttled, whole-folder deletion deferred)`, + `syncFlags delta ${folderLogLabel(folder.path)}: ${changed.length} changed since modseq ${storedModseq} (large mailbox — windowed flag re-read throttled, whole-folder deletion deferred)`, ); } } else if (dueForDeletion) { @@ -2178,26 +2179,26 @@ export class MessageProcessor { const allFlags = await client.fetchFlagsOnly(allUids, touch, folder.path); for (const f of allFlags) setServerFlags(f); } catch (err) { - logger.warn(`Full flag reconcile failed for ${folder.path}: ${(err as Error).message}`); + logger.warn(`Full flag reconcile failed for ${folderLogLabel(folder.path)}: ${failureCause(err)}`); } } } logger.info( - `syncFlags ${folder.path}: reconcile — ${changed.length} changed since modseq ${storedModseq}, ` + `syncFlags ${folderLogLabel(folder.path)}: reconcile — ${changed.length} changed since modseq ${storedModseq}, ` + `${allUids.length} server uids, flags for ${serverFlagsMap.size}` + `${dueForFlagReconcile ? ' (full flag re-read)' : ''}`, ); } else { logger.debug( - `syncFlags delta ${folder.path}: ${changed.length} changed since modseq ${storedModseq} (deletion reconcile throttled)`, + `syncFlags delta ${folderLogLabel(folder.path)}: ${changed.length} changed since modseq ${storedModseq} (deletion reconcile throttled)`, ); } } catch (err) { // HARD FALLBACK: any delta error → discard partial maps and take the // proven full path. Correctness must never depend on the delta working. logger.warn( - `CONDSTORE delta flag sync failed for ${folder.path}, falling back to full fetch: ${(err as Error).message}`, + `CONDSTORE delta flag sync failed for ${folderLogLabel(folder.path)}, falling back to full fetch: ${failureCause(err)}`, ); serverUidsSet.clear(); serverFlagsMap.clear(); @@ -2324,7 +2325,7 @@ export class MessageProcessor { // at the head of a newest-first rotation and re-request it forever. for (const uid of selection.uids) checked.add(uid); logger.info( - `[syncFlags] ${folder.path}: stale-flag sweep — re-read ${staleFlags.length}/${selection.uids.length} ` + `[syncFlags] ${folderLogLabel(folder.path)}: stale-flag sweep — re-read ${staleFlags.length}/${selection.uids.length} ` + `old unread/starred uid(s) outside the ${SYNC_RECENT_WINDOW_DAYS}d window` + `${selection.remaining > 0 ? ` (${selection.remaining} more next sweep)` : ''}` + `${selection.wrapped ? ' [rotation restarted]' : ''}`, @@ -2332,7 +2333,7 @@ export class MessageProcessor { } catch (err) { // TRANSIENT: mark nothing, so the same UIDs are retried next sweep // rather than suppressed for the session on one flaky response. - logger.warn(`[syncFlags] ${folder.path}: stale-flag sweep failed: ${(err as Error).message}`); + logger.warn(`[syncFlags] ${folderLogLabel(folder.path)}: stale-flag sweep failed: ${failureCause(err)}`); } } // Same bound as the addition reconcile's tried-set: clearing only costs a @@ -2353,7 +2354,7 @@ export class MessageProcessor { // source (serverUidsSet) and is unaffected by this skip. const shouldRunPhase1 = serverFlagsMap.size > 0; if (!shouldRunPhase1) { - logger.debug(`[syncFlags] ${folder.path}: Phase-1 skipped — server reported no flags this cycle`); + logger.debug(`[syncFlags] ${folderLogLabel(folder.path)}: Phase-1 skipped — server reported no flags this cycle`); } // Collected per page and written with one chunked, yielding bulk statement // instead of an awaited updateEmail per row (each of which re-SELECTs the @@ -2501,7 +2502,7 @@ export class MessageProcessor { try { await storage.updateFolder(folder.id, folderUpdate); } catch (err) { - logger.warn(`Failed to persist highestModseq for ${folder.path}: ${(err as Error).message}`); + logger.warn(`Failed to persist highestModseq for ${folderLogLabel(folder.path)}: ${(err as Error).message}`); } } @@ -2530,7 +2531,7 @@ export class MessageProcessor { const additionOnly = !deletionSetReady && windowSetReady && options?.skipDeletion !== true; if (options?.skipDeletion || (!deletionSetReady && !additionOnly)) { logger.info( - `[syncFlags] ${folder.path}: Phase-2 deletion SKIPPED — skipDeletion=${options?.skipDeletion === true}, deletionSetReady=${deletionSetReady}, condstore=${client.supportsCondstore()}, force=${options?.forceDeletion === true}, serverUids=${serverUidsSet.size}`, + `[syncFlags] ${folderLogLabel(folder.path)}: Phase-2 deletion SKIPPED — skipDeletion=${options?.skipDeletion === true}, deletionSetReady=${deletionSetReady}, condstore=${client.supportsCondstore()}, force=${options?.forceDeletion === true}, serverUids=${serverUidsSet.size}`, ); return result; } @@ -2564,7 +2565,7 @@ export class MessageProcessor { // the deletion diff below simply finds nothing to delete, which is correct: // there is nothing in this folder's uid space to delete. if (localUids.length === 0) { - logger.debug(`[syncFlags] ${folder.path}: no rows in this folder's own UID space — deletion diff is a no-op, addition reconcile still runs`); + logger.debug(`[syncFlags] ${folderLogLabel(folder.path)}: no rows in this folder's own UID space — deletion diff is a no-op, addition reconcile still runs`); } // Completeness guard for whole-folder detection: a `1:* FLAGS` fetch / SEARCH @@ -2606,14 +2607,14 @@ export class MessageProcessor { const serverUidNext = typeof currentState?.uidNext === 'number' ? currentState.uidNext : null; if (serverUidNext != null && serverMaxUid >= serverUidNext) { logger.error( - `[syncFlags] ${folder.path}: ABORTED — server UID list contains UID ${serverMaxUid} at/above this folder's UIDNEXT ${serverUidNext}; the list is not this mailbox's. Skipping flag/deletion reconcile.`, + `[syncFlags] ${folderLogLabel(folder.path)}: ABORTED — server UID list contains UID ${serverMaxUid} at/above this folder's UIDNEXT ${serverUidNext}; the list is not this mailbox's. Skipping flag/deletion reconcile.`, ); return result; } const EXISTS_OVERSHOOT_SLACK = 100; if (serverExists != null && serverUidsSet.size > serverExists * 2 + EXISTS_OVERSHOOT_SLACK) { logger.error( - `[syncFlags] ${folder.path}: ABORTED — server UID list has ${serverUidsSet.size} UIDs but the mailbox reports EXISTS=${serverExists}; the list is not this mailbox's. Skipping flag/deletion reconcile.`, + `[syncFlags] ${folderLogLabel(folder.path)}: ABORTED — server UID list has ${serverUidsSet.size} UIDs but the mailbox reports EXISTS=${serverExists}; the list is not this mailbox's. Skipping flag/deletion reconcile.`, ); return result; } @@ -2634,11 +2635,11 @@ export class MessageProcessor { // number is the tag count, which the addition reconcile below logs as // `tagged` — the two are different questions and must not look alike. logger.info( - `[syncFlags] ${folder.path}: Phase-2 running — localUidSpace=${localUids.length} (max ${localMaxUid}; rows primary to this folder — NOT comparable to server total), server=${serverUidsSet.size} (max ${serverMaxUid}, exists ${serverExists ?? '?'}), complete=${serverListComplete}` + `[syncFlags] ${folderLogLabel(folder.path)}: Phase-2 running — localUidSpace=${localUids.length} (max ${localMaxUid}; rows primary to this folder — NOT comparable to server total), server=${serverUidsSet.size} (max ${serverMaxUid}, exists ${serverExists ?? '?'}), complete=${serverListComplete}` + `${additionOnly ? `, ADDITION-ONLY from ${windowedUidsSet.size}-uid recent window${additionFromWindow ? '' : ' (skipped — no rows in this folder\'s own UID space)'}` : ''}`, ); if (serverMaxUid > 0 && localMaxUid > serverMaxUid && !serverListComplete) { - logger.warn(`Deletion detection for ${folder.path}: local max UID ${localMaxUid} > server max ${serverMaxUid} (server has ${serverUidsSet.size}, exists ${serverExists ?? '?'}), server list may be partial — skipping`); + logger.warn(`Deletion detection for ${folderLogLabel(folder.path)}: local max UID ${localMaxUid} > server max ${serverMaxUid} (server has ${serverUidsSet.size}, exists ${serverExists ?? '?'}), server list may be partial — skipping`); return result; } @@ -2700,13 +2701,13 @@ export class MessageProcessor { // the drain, which clears on convergence) so it doesn't hold UIDs for the // session after the gap is closed. this.reconcileTriedUids.delete(folder.path); - logger.debug(`[syncFlags] ${folder.path}: ${missingFromLocal.length} UID(s) outside folder_id space already present by tag (${tagCount}/${serverExists}) — nothing to reconcile`); + logger.debug(`[syncFlags] ${folderLogLabel(folder.path)}: ${missingFromLocal.length} UID(s) outside folder_id space already present by tag (${tagCount}/${serverExists}) — nothing to reconcile`); } else if (genuinelyMissing > 0 && drainable.length === 0) { // Every candidate has been fetched once already this session; the residual // gap is messages this pass can't resolve (present-elsewhere, or a count // artefact). Re-fetching them would just re-loop — wait for a restart / // the downward backfill instead of hammering the same no-ops. - logger.debug(`[syncFlags] ${folder.path}: ${genuinelyMissing} still unaccounted but all ${missingFromLocal.length} candidate UID(s) already tried this session — not re-fetching`); + logger.debug(`[syncFlags] ${folderLogLabel(folder.path)}: ${genuinelyMissing} still unaccounted but all ${missingFromLocal.length} candidate UID(s) already tried this session — not re-fetching`); } else if (genuinelyMissing > 0) { // DRAIN, don't defer: fetch up to ADDITION_RECONCILE_MAX of the missing UIDs // THIS sync; a larger gap fills across successive syncs. (Previously a gap > @@ -2718,7 +2719,7 @@ export class MessageProcessor { const ordered = drainable.slice().sort((a, b) => b - a); const toFetch = ordered.slice(0, ADDITION_RECONCILE_MAX); const remaining = ordered.length - toFetch.length; - logger.info(`[syncFlags] ${folder.path}: addition reconcile — ${genuinelyMissing} genuinely missing (server ${serverExists ?? '?'}, tagged ${tagCount ?? '?'}); fetching ${toFetch.length} of ${drainable.length} untried this sync${remaining > 0 ? ` (${remaining} remaining next sync)` : ''}`); + logger.info(`[syncFlags] ${folderLogLabel(folder.path)}: addition reconcile — ${genuinelyMissing} genuinely missing (server ${serverExists ?? '?'}, tagged ${tagCount ?? '?'}); fetching ${toFetch.length} of ${drainable.length} untried this sync${remaining > 0 ? ` (${remaining} remaining next sync)` : ''}`); // Fetch in small sub-batches: one giant UID FETCH times out on a slow server and // inserts nothing (all-or-nothing). Sub-batching keeps each FETCH under the op // timeout and makes partial progress durable — if a later sub-batch fails, the @@ -2762,7 +2763,7 @@ export class MessageProcessor { // keeps its connection. touch?.(); } catch (e) { - logger.warn(`[syncFlags] ${folder.path}: addition reconcile sub-batch failed (${inserted} inserted so far, rest next sync): ${(e as Error).message}`); + logger.warn(`[syncFlags] ${folderLogLabel(folder.path)}: addition reconcile sub-batch failed (${inserted} inserted so far, rest next sync): ${failureCause(e)}`); break; // keep what stuck; the remainder drains on the next sync } } @@ -2777,7 +2778,7 @@ export class MessageProcessor { // read as progress. `unchanged` is that case, named. if (attempted > 0) { logger.info( - `[syncFlags] ${folder.path}: addition reconcile inserted ${inserted}, linked ${linked}, ` + `[syncFlags] ${folderLogLabel(folder.path)}: addition reconcile inserted ${inserted}, linked ${linked}, ` + `unchanged ${unchanged}, of ${attempted} attempted` + `${inserted + linked === 0 ? ' — NO PROGRESS: every message was already present' : ''}`, ); @@ -2842,7 +2843,7 @@ export class MessageProcessor { if (serverUidsSet.size === 0 && localUids.length > 5) { if (!this.foldersSeenEmpty.has(folder.id)) { this.foldersSeenEmpty.add(folder.id); - logger.warn(`Server returned 0 UIDs but we have ${localUids.length} local emails in ${folder.path} — deferring deletion until a second confirming empty read (possible transient)`); + logger.warn(`Server returned 0 UIDs but we have ${localUids.length} local emails in ${folderLogLabel(folder.path)} — deferring deletion until a second confirming empty read (possible transient)`); return result; } // Only claim we're applying when we actually will: a truly-empty folder has @@ -2850,7 +2851,7 @@ export class MessageProcessor { // it through. If serverExists is unknown (null), serverListComplete is false // and Safety check 2 defers anyway, so don't log a misleading "applying". if (serverListComplete) { - logger.info(`${folder.path}: server empty on two consecutive reads — applying deletion of ${localUids.length} local row(s)`); + logger.info(`${folderLogLabel(folder.path)}: server empty on two consecutive reads — applying deletion of ${localUids.length} local row(s)`); } } @@ -2868,10 +2869,10 @@ export class MessageProcessor { return result; } if (missingRatio > 0.5 && missingUids.length > 5) { - logger.info(`[syncFlags] ${folder.path}: applying large deletion — ${missingUids.length}/${localUids.length} missing but server list is COMPLETE (${serverUidsSet.size}>=${serverExists}), so these are genuine expiries`); + logger.info(`[syncFlags] ${folderLogLabel(folder.path)}: applying large deletion — ${missingUids.length}/${localUids.length} missing but server list is COMPLETE (${serverUidsSet.size}>=${serverExists}), so these are genuine expiries`); } - logger.info(`Syncing ${missingUids.length} deleted emails in ${folder.path} (server has ${serverUidsSet.size}, local has ${localUids.length})`); + logger.info(`Syncing ${missingUids.length} deleted emails in ${folderLogLabel(folder.path)} (server has ${serverUidsSet.size}, local has ${localUids.length})`); // Unlink-or-delete rather than a blind bulk delete: a message that VANISHED // from THIS folder but still carries another folder's tag (a webmail move @@ -2897,7 +2898,7 @@ export class MessageProcessor { } result.deleted = doomed.length; if (!emitPerRow) { - logger.info(`[syncFlags] ${folder.path}: ${doomed.length} rows reconciled (bulk — per-row UI events skipped; folder reloads fresh on open)`); + logger.info(`[syncFlags] ${folderLogLabel(folder.path)}: ${doomed.length} rows reconciled (bulk — per-row UI events skipped; folder reloads fresh on open)`); } } @@ -2920,7 +2921,7 @@ export class MessageProcessor { } catch (err) { // A failed sweep leaves stale tags in place until the next sync — a // cosmetic lag, never worth failing the flag sync over. - logger.warn(`[syncFlags] ${folder.path}: stale-membership sweep failed: ${(err as Error).message}`); + logger.warn(`[syncFlags] ${folderLogLabel(folder.path)}: stale-membership sweep failed: ${failureCause(err)}`); } } @@ -3012,7 +3013,7 @@ export class MessageProcessor { } catch (err) { // The SEARCH failed: evidence about the CONNECTION, not the message. Stop // the sweep here (nothing unlinked on a guess); the next sync asks again. - logger.warn(`[syncFlags] ${folder.path}: stale-membership HEADER search failed after ${searched - 1} check(s): ${(err as Error).message}`); + logger.warn(`[syncFlags] ${folderLogLabel(folder.path)}: stale-membership HEADER search failed after ${searched - 1} check(s): ${failureCause(err)}`); stoppedEarly = true; break; } @@ -3035,7 +3036,7 @@ export class MessageProcessor { // sweep exists to fix, reintroduced by its own rate limit. if (!stoppedEarly) this.staleSweepLastRun.set(folder.path, Date.now()); if (unlinked > 0) { - logger.info(`[syncFlags] ${folder.path}: stale-membership sweep unlinked ${unlinked} tag-only member(s) no longer on the server (${searched} searched, ${members.length} tag-only, ${unaccounted} unaccounted)`); + logger.info(`[syncFlags] ${folderLogLabel(folder.path)}: stale-membership sweep unlinked ${unlinked} tag-only member(s) no longer on the server (${searched} searched, ${members.length} tag-only, ${unaccounted} unaccounted)`); } return unlinked; } diff --git a/packages/core/src/imap/operation-queue.ts b/packages/core/src/imap/operation-queue.ts index 67c31ba4..20b92029 100644 --- a/packages/core/src/imap/operation-queue.ts +++ b/packages/core/src/imap/operation-queue.ts @@ -3,7 +3,9 @@ import { IMAPError, type IIMAPClient, type IMAPFolder } from '../types/imap'; import type { IEmailStorage } from '../types/storage'; import { existingCategoryClassification } from '../utils/category-authority'; +import { errorDiagnostic, failureCause } from '../utils/error-diagnostic'; import { categorySlugFromLabel, GMAIL_CLASSIFICATION_CATEGORY_SLUGS, type KnownCategory } from '../utils/gmail-labels'; +import { categoryLogLabel, folderLogLabel, labelLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { isSpamProtectedEmail } from '../utils/spam-protection'; @@ -207,7 +209,7 @@ export class OperationQueue { } catch (error) { // Never fail reconciliation because the backstop query errored — the // in-memory set is still a valid (if narrower) guard. - logger.warn(`getPendingUids: durable backstop query failed for ${folderPath}`, error); + logger.warn(`getPendingUids: durable backstop query failed for ${folderLogLabel(folderPath)}`, error); } } return uids; @@ -359,7 +361,7 @@ export class OperationQueue { await strategy.rename(oldCat, newCat); return true; } catch (e) { - logger.debug(`rename label failed: ${(e as Error).message}`); + logger.debug(`rename label failed: ${failureCause(e)}`); return false; } } @@ -378,7 +380,7 @@ export class OperationQueue { targets.sort((a, b) => b.length - a.length); let n = 0; for (const p of targets) { - try { await this.client.deleteMailbox(p); n++; } catch (e) { logger.debug(`delete ${p} failed: ${(e as Error).message}`); } + try { await this.client.deleteMailbox(p); n++; } catch (e) { logger.debug(`delete ${folderLogLabel(p)} failed: ${failureCause(e)}`); } } return n; } @@ -407,12 +409,12 @@ export class OperationQueue { await strategy.ensure({ slug: c.slug, name: c.name }); n++; } catch (e) { - logger.warn(`ensure label failed for ${c.slug}: ${(e as Error).message}`); + logger.warn(`ensure label failed for ${categoryLogLabel(c.slug, false)}: ${failureCause(e)}`); } try { await strategy.migrate?.({ slug: c.slug, name: c.name }); } catch (e) { - logger.debug(`migrate label failed for ${c.slug}: ${(e as Error).message}`); + logger.debug(`migrate label failed for ${categoryLogLabel(c.slug, false)}: ${failureCause(e)}`); } } return n; @@ -432,15 +434,15 @@ export class OperationQueue { if (!path) return false; try { await this.client.createMailbox(path); - logger.info(`[labels] user label synced to server — CREATE "${path}"`); + logger.info(`[labels] user label synced to server — CREATE "${labelLogLabel(path)}"`); return true; } catch (e) { const msg = ((e as Error).message || '').toLowerCase(); if (msg.includes('exist')) { - logger.info(`[labels] user label "${path}" already exists on server`); + logger.info(`[labels] user label "${labelLogLabel(path)}" already exists on server`); return true; // already there is success } - logger.warn(`[labels] createServerLabel "${path}" failed: ${(e as Error).message}`); + logger.warn(`[labels] createServerLabel "${labelLogLabel(path)}" failed: ${failureCause(e)}`); return false; } } @@ -547,7 +549,7 @@ export class OperationQueue { } const detail = extractOpFailureDetail(error); await this.storage!.markPendingOperationFailed(id, detail.message, detail); - logger.error(`Operation ${type} on UID ${uid}: failed (dead-lettered)`, error); + logger.error(`Operation ${type} on UID ${uid}: failed (dead-lettered)`, errorDiagnostic(error)); throw error; } lease.release(); @@ -577,7 +579,7 @@ export class OperationQueue { // command we sent + the server's reply so the Outbox can show both. const detail = extractOpFailureDetail(error); await this.storage!.markPendingOperationFailed(id, detail.message, detail); - logger.error(`Operation ${type} on UID ${uid}: failed (dead-lettered)`, error); + logger.error(`Operation ${type} on UID ${uid}: failed (dead-lettered)`, errorDiagnostic(error)); throw error; } await this.cleanupAcceptedOperations([id], false); @@ -640,11 +642,11 @@ export class OperationQueue { for (const failedId of ids) { await this.storage!.markPendingOperationFailed(failedId, detail.message, detail); } - logger.error(`Bulk ${type} failed (dead-lettered ${ids.length})`, error); + logger.error(`Bulk ${type} failed (dead-lettered ${ids.length})`, errorDiagnostic(error)); throw error; } await this.cleanupAcceptedOperations(ids, true); - logger.info(`Bulk ${type} on ${uids.length} UIDs in ${folderPath}: success`); + logger.info(`Bulk ${type} on ${uids.length} UIDs in ${folderLogLabel(folderPath)}: success`); return 'success'; } @@ -747,7 +749,7 @@ export class OperationQueue { // op, or a just-read email loses its \Seen and springs back to unread // when syncFlags reconciles. Re-queue for the next cycle instead. const transient = isConnectionError(error) || isRateLimited(error) || isQuotaError(error); - logger.warn(`Batch op ${batch.type} (${batch.ops.length} uid(s)) failed${transient ? ' [transient — will retry]' : ''}: ${msg}`); + logger.warn(`Batch op ${batch.type} (${batch.ops.length} uid(s)) failed${transient ? ' [transient — will retry]' : ''}: ${failureCause(error)}`); for (const op of batch.ops) { if (transient) { @@ -765,7 +767,7 @@ export class OperationQueue { await this.storage!.updatePendingOperationRetry(op.id, op.retryCount); } catch { /* ignore */ } } else { - logger.warn(`Dead-lettering operation ${op.type} for UID ${op.uid} after ${this.config.maxRetries} retries: ${msg}`); + logger.warn(`Dead-lettering operation ${op.type} for UID ${op.uid} after ${this.config.maxRetries} retries: ${failureCause(error)}`); try { await this.storage!.markPendingOperationFailed(op.id, msg); } catch { /* ignore */ } @@ -880,7 +882,7 @@ export class OperationQueue { // Explicit IMAP-command log so the mail server / IMAP team can confirm we // ALWAYS issue a STORE for reads. Single read = INFO (visible by default); // bulk = DEBUG (a select-all mark-read would otherwise flood INFO). - const seenDetail = `folder="${folderPath}" ${uids.length === 1 ? `UID ${uids[0]}` : `${uids.length} UIDs [${uids.slice(0, 20).join(',')}${uids.length > 20 ? ',…' : ''}]`}`; + const seenDetail = `folder="${folderLogLabel(folderPath)}" ${uids.length === 1 ? `UID ${uids[0]}` : `${uids.length} UIDs [${uids.slice(0, 20).join(',')}${uids.length > 20 ? ',…' : ''}]`}`; if (uids.length > 1) logger.debug(`IMAP STORE +FLAGS (\\Seen) — bulk mark-read ${seenDetail}`); else logger.info(`IMAP STORE +FLAGS (\\Seen) — mark-read ${seenDetail}`); await withFolderSelected(this.client!, folderPath, () => this.client!.addFlags(uids, ['\\Seen'])); @@ -1127,7 +1129,7 @@ export class OperationQueue { try { const destFolder = await this.storage.getFolderByPath(destPath); if (!destFolder) { - logger.warn(`remapMovedUids: destination folder not found for "${destPath}"; skipping uid writeback`); + logger.warn(`remapMovedUids: destination folder not found for "${folderLogLabel(destPath)}"; skipping uid writeback`); return; } @@ -1143,7 +1145,7 @@ export class OperationQueue { // destination folder. We're here right after a successful move, so the // client is connected; guard anyway to avoid throwing if it dropped. if (!this.isConnected()) { - logger.warn(`remapMovedUids: no uidMap and client not connected for "${destPath}"; local uids left stale (will self-heal on next full sync)`); + logger.warn(`remapMovedUids: no uidMap and client not connected for "${folderLogLabel(destPath)}"; local uids left stale (will self-heal on next full sync)`); return; } for (const srcUid of sourceUids) { @@ -1167,7 +1169,7 @@ export class OperationQueue { } } catch (error) { // The move itself succeeded; never fail it because the uid writeback did. - logger.warn(`remapMovedUids: failed to persist destination uids for "${destPath}"`, error); + logger.warn(`remapMovedUids: failed to persist destination uids for "${folderLogLabel(destPath)}"`, errorDiagnostic(error)); } } diff --git a/packages/core/src/imap/qresync-reconcile.ts b/packages/core/src/imap/qresync-reconcile.ts index 38b21ec3..1bd1b926 100644 --- a/packages/core/src/imap/qresync-reconcile.ts +++ b/packages/core/src/imap/qresync-reconcile.ts @@ -1,6 +1,8 @@ import type { IIMAPClient } from '../types/imap'; import type { FolderRecord } from '../types/models'; import type { IEmailStorage } from '../types/storage'; +import { failureCause } from '../utils/error-diagnostic'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; // Resolve/apply VANISHED in chunks so a huge backlog (e.g. a folder that drifted @@ -52,7 +54,7 @@ export async function applyQresyncVanished( folder.path, folder.uidValidity, folder.highestModseq, )); } catch (err) { - logger.warn(`QRESYNC resync SELECT failed for ${folder.path}, skipping VANISHED reconcile: ${(err as Error).message}`); + logger.warn(`QRESYNC resync SELECT failed for ${folderLogLabel(folder.path)}, skipping VANISHED reconcile: ${failureCause(err)}`); return { selected: false, removed: 0 }; } @@ -69,7 +71,7 @@ export async function applyQresyncVanished( const rawValidity = Number(status?.uidValidity); const seenValidity = Number.isFinite(rawValidity) ? rawValidity : undefined; if (seenValidity !== undefined && seenValidity !== folder.uidValidity) { - logger.warn(`QRESYNC ${folder.path}: UIDVALIDITY changed (${folder.uidValidity} -> ${seenValidity}) — skipping VANISHED, deferring to the re-key path`); + logger.warn(`QRESYNC ${folderLogLabel(folder.path)}: UIDVALIDITY changed (${folder.uidValidity} -> ${seenValidity}) — skipping VANISHED, deferring to the re-key path`); return { selected: true, removed: 0 }; } @@ -90,11 +92,11 @@ export async function applyQresyncVanished( } if (removed > 0) { - logger.info(`QRESYNC ${folder.path}: applied ${vanishedUids.length} VANISHED (${removed} local rows reconciled)`); + logger.info(`QRESYNC ${folderLogLabel(folder.path)}: applied ${vanishedUids.length} VANISHED (${removed} local rows reconciled)`); try { await storage.recalculateFolderCounts([folder.path]); } catch (err) { - logger.warn(`QRESYNC ${folder.path}: recount after VANISHED failed: ${(err as Error).message}`); + logger.warn(`QRESYNC ${folderLogLabel(folder.path)}: recount after VANISHED failed: ${(err as Error).message}`); } } return { selected: true, removed }; diff --git a/packages/core/src/imap/realtime-manager.ts b/packages/core/src/imap/realtime-manager.ts index f96aedec..61f21908 100644 --- a/packages/core/src/imap/realtime-manager.ts +++ b/packages/core/src/imap/realtime-manager.ts @@ -4,6 +4,8 @@ import { EventEmitter } from 'events'; import type { IIMAPClient, IMAPEvent } from '../types/imap'; import type { IEmailStorage } from '../types/storage'; +import { errorDiagnostic, failureCause } from '../utils/error-diagnostic'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { createMutex, type Mutex } from '../utils/mutex'; @@ -342,7 +344,7 @@ export class RealtimeManager extends EventEmitter { // this the pre-existing deletions never get noticed — the reported "mail // deleted on webmail still shows in the app INBOX". this.scheduleFlagSync(); - logger.info(`Realtime: IDLE started for ${folderPath} (rt#${this.instanceId})`); + logger.info(`Realtime: IDLE started for ${folderLogLabel(folderPath)} (rt#${this.instanceId})`); return 'idle'; } @@ -364,7 +366,7 @@ export class RealtimeManager extends EventEmitter { // backoff so the first retry is prompt. this.idleUpgradeAttempts = 0; this.scheduleIdleUpgrade(); - logger.info(`Realtime: Polling started for ${folderPath} (rt#${this.instanceId})`); + logger.info(`Realtime: Polling started for ${folderLogLabel(folderPath)} (rt#${this.instanceId})`); return 'polling'; } @@ -393,7 +395,7 @@ export class RealtimeManager extends EventEmitter { const folderPath = this.startIntent; // Someone stopped us, or a session came up by another route. if (!folderPath || this.mode !== 'none') return; - logger.info(`Realtime: retrying monitoring for ${folderPath} (rt#${this.instanceId})`); + logger.info(`Realtime: retrying monitoring for ${folderLogLabel(folderPath)} (rt#${this.instanceId})`); await this.startInternal(folderPath); }); }, delay); @@ -443,8 +445,8 @@ export class RealtimeManager extends EventEmitter { // `quiet` on the background polling->IDLE upgrade retries: a still-busy // connection is expected to fail, so log at debug to avoid spamming the // same error every retry. The initial start still logs at error (visible). - if (quiet) logger.debug('Realtime: IDLE upgrade attempt failed (still on polling):', (error as Error)?.message ?? error); - else logger.error('Realtime: Failed to start IDLE:', error); + if (quiet) logger.debug('Realtime: IDLE upgrade attempt failed (still on polling):', failureCause(error)); + else logger.error('Realtime: Failed to start IDLE:', errorDiagnostic(error)); return false; } } @@ -500,7 +502,7 @@ export class RealtimeManager extends EventEmitter { this.scheduleFlagSync(); this.clearIdleUpgradeTimer(); this.idleUpgradeAttempts = 0; - logger.info(`Realtime: upgraded polling -> IDLE for ${folderPath} (rt#${this.instanceId})`); + logger.info(`Realtime: upgraded polling -> IDLE for ${folderLogLabel(folderPath)} (rt#${this.instanceId})`); return; } // Still couldn't start IDLE (connection busy) — keep polling, try again later. @@ -574,7 +576,7 @@ export class RealtimeManager extends EventEmitter { break; } } catch (error) { - logger.error('Realtime: Error handling IDLE event:', error); + logger.error('Realtime: Error handling IDLE event:', errorDiagnostic(error)); // EventEmitter throws synchronously on 'error' with no listener if (this.listenerCount('error') > 0) this.emit('error', error as Error); } @@ -657,7 +659,7 @@ export class RealtimeManager extends EventEmitter { (status.messages > storedCount && storedCount > 0); if (hasNewMessages) { - logger.info(`Polling: New messages detected in ${this.monitoredFolder}`); + logger.info(`Polling: New messages detected in ${folderLogLabel(this.monitoredFolder)}`); await this.handleNewMessages(); } @@ -723,7 +725,7 @@ export class RealtimeManager extends EventEmitter { this.emit('disconnected'); await this.handleReconnect(); } else { - logger.error('Polling: Error:', error); + logger.error('Polling: Error:', errorDiagnostic(error)); if (this.listenerCount('error') > 0) this.emit('error', error as Error); } } finally { @@ -793,7 +795,7 @@ export class RealtimeManager extends EventEmitter { if (error instanceof Error && error.message.includes('Sync already in progress')) { logger.debug('Periodic sync: skipped (a sync is already in progress)'); } else { - logger.error('Periodic sync: Failed:', error); + logger.error('Periodic sync: Failed:', errorDiagnostic(error)); } } // The sync above can run for a minute; the session may be gone now. @@ -943,13 +945,13 @@ export class RealtimeManager extends EventEmitter { // Fire-and-forget so a slow source sync never stalls the IDLE handler. const sources = (result.relinkedFromFolders || []).filter((f) => f && f !== folderPath); if (epoch === this.epoch && this.onSyncRequest && sources.length > 0) { - logger.info(`Realtime: move-back into ${folderPath} — reconciling source folder(s): ${sources.join(', ')}`); + logger.info(`Realtime: move-back into ${folderLogLabel(folderPath)} — reconciling source folder(s): ${sources.map((s) => folderLogLabel(s)).join(', ')}`); void this.onSyncRequest(sources).catch((err) => - logger.warn(`Realtime: source-folder reconcile after move-back failed: ${(err as Error).message}`), + logger.warn(`Realtime: source-folder reconcile after move-back failed: ${failureCause(err)}`), ); } } catch (error) { - logger.error('Realtime: Error handling new messages:', error); + logger.error('Realtime: Error handling new messages:', errorDiagnostic(error)); if (this.listenerCount('error') > 0) this.emit('error', error as Error); } } @@ -1044,7 +1046,7 @@ export class RealtimeManager extends EventEmitter { this.folderRecountTimers.delete(folderPath); if (epoch !== this.epoch) return; void storage.recalculateFolderCounts([folderPath]).catch((err) => - logger.warn(`Realtime: debounced recount failed for ${folderPath}: ${(err as Error).message}`), + logger.warn(`Realtime: debounced recount failed for ${folderLogLabel(folderPath)}: ${(err as Error).message}`), ); }, RealtimeManager.FOLDER_RECOUNT_DEBOUNCE_MS)); } @@ -1120,7 +1122,7 @@ export class RealtimeManager extends EventEmitter { logger.warn('Realtime: folder unread refresh after flag change failed:', err); } } catch (error) { - logger.warn(`Realtime: coalesced flag sync failed for ${folderPath}: ${(error as Error).message}`); + logger.warn(`Realtime: coalesced flag sync failed for ${folderLogLabel(folderPath)}: ${failureCause(error)}`); } finally { this.flagSyncInProgress = false; } @@ -1165,7 +1167,7 @@ export class RealtimeManager extends EventEmitter { // Restart monitoring if it was active, or was trying to be if (previousFolder) { const what = previousMode === 'none' ? 'failed' : previousMode; - logger.info(`Realtime: Restarting ${what} monitoring on new client for ${previousFolder} (rt#${this.instanceId})`); + logger.info(`Realtime: Restarting ${what} monitoring on new client for ${folderLogLabel(previousFolder)} (rt#${this.instanceId})`); await this.startInternal(previousFolder); } }); @@ -1183,7 +1185,7 @@ export class RealtimeManager extends EventEmitter { // startPolling() does an initial poll — a floating rejection here would // surface as an unhandled rejection in the main process. void this.startPolling(this.monitoredFolder).catch((err) => { - logger.warn('Realtime: restart polling after setConfig failed:', err); + logger.warn('Realtime: restart polling after setConfig failed:', errorDiagnostic(err)); }); } } diff --git a/packages/core/src/imap/sync-engine.ts b/packages/core/src/imap/sync-engine.ts index 5a2ef27d..92ffce62 100644 --- a/packages/core/src/imap/sync-engine.ts +++ b/packages/core/src/imap/sync-engine.ts @@ -9,13 +9,14 @@ import { IMAPError, type IMAPConfig, type IIMAPClient, type IMAPFolder, type IMA import type { EmailRecord, FolderRecord } from '../types/models'; import type { IEmailStorage } from '../types/storage'; import { createDeferredFetchError } from '../utils/deferred-fetch-error'; -import { errorDiagnostic } from '../utils/error-diagnostic'; +import { errorDiagnostic, failureCause } from '../utils/error-diagnostic'; import { decideMidSyncRecount, refreshCountsForFolders, withFiledCounts, type MidSyncRecountGate, } from '../utils/folder-counts'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; import { SIMPLE_PARSER_OPTIONS } from '../utils/mail-parse'; import { detectProvider, type EmailProvider } from '../utils/provider'; @@ -396,7 +397,7 @@ export class SyncEngine { try { await this.realtimeManager.updateClient(this.connectionManager.client); } catch (error) { - logger.error('Failed to restart realtime after reconnect:', error); + logger.error('Failed to restart realtime after reconnect:', errorDiagnostic(error)); } // Process pending operations after reconnect. WRAPPED: this handler is an @@ -409,7 +410,7 @@ export class SyncEngine { try { await this.operationQueue.processQueue(); } catch (error) { - logger.warn(`Post-reconnect operation-queue drain failed (will retry): ${(error as Error)?.message ?? error}`); + logger.warn(`Post-reconnect operation-queue drain failed (will retry): ${failureCause(error)}`); } } @@ -645,7 +646,7 @@ export class SyncEngine { if (this.connectionPool?.isInitialized()) { await this.connectionPool.withConnection(run); return; } await run(this.connectionManager.client); } catch (err) { - logger.warn(`setMailboxSubscribed(${path}, ${subscribed}) failed: ${(err as Error)?.message ?? err}`); + logger.warn(`setMailboxSubscribed(${folderLogLabel(path)}, ${subscribed}) failed: ${failureCause(err)}`); } } @@ -802,7 +803,7 @@ export class SyncEngine { try { repaired += await this.repairFolderBatch(folderPath, records); } catch (error) { - logger.warn(`Repair: folder ${folderPath} failed: ${(error as Error)?.message ?? error}`); + logger.warn(`Repair: folder ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } } logger.info(`Repair: corrected ${repaired}/${incomplete.length} incomplete emails`); @@ -918,10 +919,10 @@ export class SyncEngine { this.pendingSourceReconcile.clear(); for (const src of sources) { try { - logger.info(`[SyncEngine] move-back source reconcile: ${src}`); + logger.info(`[SyncEngine] move-back source reconcile: ${folderLogLabel(src)}`); await this.refreshFolderFlags(src); } catch (err) { - logger.warn(`[SyncEngine] move-back source reconcile failed for ${src}: ${(err as Error).message}`); + logger.warn(`[SyncEngine] move-back source reconcile failed for ${folderLogLabel(src)}: ${failureCause(err)}`); } } } @@ -965,7 +966,7 @@ export class SyncEngine { this.syncDidMutateCounts = false; this.emitProgress(); - logger.info(`Syncing ${selectableFolders.length} folders: ${selectableFolders.map(f => f.path).join(', ')}`); + logger.info(`Syncing ${selectableFolders.length} folders: ${selectableFolders.map(f => folderLogLabel(f.path)).join(', ')}`); const skipRecentMs = (options.skipRecentMinutes || 0) * 60 * 1000; @@ -980,7 +981,7 @@ export class SyncEngine { // Per-folder policy: a folder the user turned OFF is skipped entirely. if (!isFolderSyncEnabled(storedFolder)) { - logger.info(`Skipping ${folder.path} — sync disabled for this folder`); + logger.info(`Skipping ${folderLogLabel(folder.path)} — sync disabled for this folder`); this.syncState.completeFolder(folder.path); continue; } @@ -989,7 +990,7 @@ export class SyncEngine { if (skipRecentMs > 0 && storedFolder?.lastSyncTime) { const timeSinceSync = Date.now() - storedFolder.lastSyncTime * 1000; if (timeSinceSync < skipRecentMs) { - logger.info(`Skipping ${folder.path} - synced ${Math.round(timeSinceSync / 60000)} min ago`); + logger.info(`Skipping ${folderLogLabel(folder.path)} - synced ${Math.round(timeSinceSync / 60000)} min ago`); this.syncState.completeFolder(folder.path); continue; } @@ -997,7 +998,7 @@ export class SyncEngine { // Skip unchanged if (options.skipUnchanged && storedFolder && !await this.folderSyncer.hasChanges(client, storedFolder)) { - logger.info(`Skipping unchanged: ${folder.path}`); + logger.info(`Skipping unchanged: ${folderLogLabel(folder.path)}`); this.syncState.completeFolder(folder.path); continue; } @@ -1128,7 +1129,7 @@ export class SyncEngine { this.syncState.setFolderError(folder.path, result.error || new Error('Sync failed')); } } catch (error) { - logger.error(`Parallel sync error for ${folder.path}:`, error); + logger.error(`Parallel sync error for ${folderLogLabel(folder.path)}:`, errorDiagnostic(error)); this.syncState.setFolderError(folder.path, error as Error); } }); @@ -1271,7 +1272,7 @@ export class SyncEngine { await this.reselectMonitoredFolder(); return r; } catch (error) { - logger.warn(`[GmailLabels] repair of ${folderPath} failed (isolated): ${(error as Error).message}`); + logger.warn(`[GmailLabels] repair of ${folderLogLabel(folderPath)} failed (isolated): ${failureCause(error)}`); return null; } } @@ -1307,9 +1308,9 @@ export class SyncEngine { return { fetched: r.fetched, inserted: r.inserted, done: r.done }; } catch (error) { if (this.connectionManager.isConnectionError(error)) { - logger.warn(`Backfill ${folderPath}: connection lost — will retry next tick`); + logger.warn(`Backfill ${folderLogLabel(folderPath)}: connection lost — will retry next tick`); } else { - logger.warn(`Backfill ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`Backfill ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return null; } @@ -1346,7 +1347,7 @@ export class SyncEngine { return r; } catch (error) { if (!this.connectionManager.isConnectionError(error)) { - logger.warn(`Background deletion reconcile ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`Background deletion reconcile ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return null; } @@ -1441,7 +1442,7 @@ export class SyncEngine { // failure (not per message): a drain that silently returned null on // every tick is how an INBOX stayed days behind with nothing logged. pace.size = fetchSizeAfterFailure(size, bounds.min); - logger.warn(`Drain ${folderPath}: a fetch of ${sub.length} header(s) failed (${(error as Error)?.message ?? error}); next batch ${pace.size}`); + logger.warn(`Drain ${folderLogLabel(folderPath)}: a fetch of ${sub.length} header(s) failed (${failureCause(error)}); next batch ${pace.size}`); // Batches already stored this call are real progress: report them // (the unfetched UIDs stay untried and count as remaining) instead of // throwing the whole call away. @@ -1488,12 +1489,12 @@ export class SyncEngine { } if (result.inserted > 0) { try { await this.storage.recalculateFolderCounts([folderPath]); } catch { /* recount best-effort */ } - logger.info(`Drain ${folderPath}: +${result.inserted} downloaded (${result.remaining} still missing)`); + logger.info(`Drain ${folderLogLabel(folderPath)}: +${result.inserted} downloaded (${result.remaining} still missing)`); } return result; } catch (error) { if (!this.connectionManager.isConnectionError(error)) { - logger.warn(`Drain ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`Drain ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return null; } @@ -1582,12 +1583,12 @@ export class SyncEngine { } if (result.inserted > 0) { try { await this.storage.recalculateFolderCounts([folderPath]); } catch { /* recount best-effort */ } - logger.info(`Server search ${folderPath}: matched ${result.matched}, +${result.inserted} downloaded`); + logger.info(`Server search ${folderLogLabel(folderPath)}: matched ${result.matched}, +${result.inserted} downloaded`); } return result; } catch (error) { if (!this.connectionManager.isConnectionError(error)) { - logger.warn(`Server search ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`Server search ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return null; } @@ -1620,7 +1621,7 @@ export class SyncEngine { return await this.connectionPool.withConnection(doFetch); } catch (error) { if (!this.connectionManager.isConnectionError(error)) { - logger.warn(`[BulkBackfill] classify ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`[BulkBackfill] classify ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return bulk; } @@ -1666,7 +1667,7 @@ export class SyncEngine { return await this.connectionPool.withConnection(doFetch); } catch (error) { if (!this.connectionManager.isConnectionError(error)) { - logger.warn(`[HeaderBackfill] fetch ${folderPath} failed: ${(error as Error).message}`); + logger.warn(`[HeaderBackfill] fetch ${folderLogLabel(folderPath)} failed: ${failureCause(error)}`); } return out; } @@ -1736,7 +1737,7 @@ export class SyncEngine { try { await this.connectionManager.client.selectFolder(folder); } catch (err) { - logger.debug('Re-select of monitored folder failed (ignored):', err); + logger.debug('Re-select of monitored folder failed (ignored):', errorDiagnostic(err)); } } @@ -2151,7 +2152,7 @@ export class SyncEngine { // than wait for the 30s poll. Best-effort; the poll is the fallback. try { getEventBus().emit(createEvent.emailBodyReady(item.emailId)); } catch { /* non-fatal */ } } else { - logger.trace(`Body fetch returned no body: ${item.emailId} (UID ${item.uid} in ${item.folderPath})`); + logger.trace(`Body fetch returned no body: ${item.emailId} (UID ${item.uid} in ${folderLogLabel(item.folderPath)})`); } this.bodyFetchFailures.delete(item.emailId); // Clear failure count on success // The FETCH round-tripped (a body, or a definitive "no body" verdict) @@ -2202,7 +2203,7 @@ export class SyncEngine { if (this.connectionManager.isRateLimited(error) || this.connectionManager.isQuotaError(error)) { const base = Math.min(getSuggestedBackoffMs(error) ?? 60_000, 5 * 60_000); const backoff = Math.round(base * (0.75 + Math.random() * 0.5)); - logger.warn(`Body fetch throttled/quota for ${item.emailId} — backing off ${backoff}ms (not counted as failure): ${(error as Error)?.message ?? error}`); + logger.warn(`Body fetch throttled/quota for ${item.emailId} — backing off ${backoff}ms (not counted as failure): ${failureCause(error)}`); this.requeueBodyFetch(item); this.scheduleBodyFetchResume(backoff); return 'rate_limited'; @@ -2234,7 +2235,7 @@ export class SyncEngine { // about throughput, not about whether the message exists — // resolving null here handed the scheduler a fake verdict and // was one of the two paths that tagged live mail `|nobody|`. - logger.warn(`Body fetch timed out ${count}x for ${item.emailId} — deferring (UID ${item.uid} in ${item.folderPath})`); + logger.warn(`Body fetch timed out ${count}x for ${item.emailId} — deferring (UID ${item.uid} in ${folderLogLabel(item.folderPath)})`); const deferred = createDeferredFetchError(`${count} consecutive timeouts`); for (const l of item.listeners) l.reject(deferred); item.listeners.length = 0; @@ -2267,7 +2268,7 @@ export class SyncEngine { if ((error as { code?: string })?.code === 'SELECT_FOLDER_ERROR') { if (!this.unselectableFolders.has(item.folderPath)) { this.unselectableFolders.set(item.folderPath, true); - logger.warn(`Body fetch: folder "${item.folderPath}" would not open — skipping its body fetches for ${UNSELECTABLE_FOLDER_TTL_MS / 60_000}m (${(error as Error)?.message ?? error})`); + logger.warn(`Body fetch: folder "${folderLogLabel(item.folderPath)}" would not open — skipping its body fetches for ${UNSELECTABLE_FOLDER_TTL_MS / 60_000}m (${failureCause(error)})`); } // Everyone waiting on this folder is told DEFERRED, not handed the // raw server error: a `NO SELECT` says nothing about any single @@ -2291,7 +2292,7 @@ export class SyncEngine { const count = (this.bodyFetchFailures.get(item.emailId) || 0) + 1; // lru-cache caps size and evicts the least-recently-used entry. this.bodyFetchFailures.set(item.emailId, count); - logger.warn(`Body fetch failed for ${item.emailId} (attempt ${count}/${this.MAX_BODY_FETCH_RETRIES}): ${(error as Error)?.message ?? error}`); + logger.warn(`Body fetch failed for ${item.emailId} (attempt ${count}/${this.MAX_BODY_FETCH_RETRIES}): ${failureCause(error)}`); for (const l of item.listeners) l.reject(error); item.listeners.length = 0; // Release listener references } @@ -2871,7 +2872,7 @@ export class SyncEngine { return uids.length > 0 ? uids[0] : null; } catch (error) { - logger.error('Failed to fetch UID by message ID:', error); + logger.error('Failed to fetch UID by message ID:', errorDiagnostic(error)); return null; } } @@ -3031,7 +3032,7 @@ export class SyncEngine { } catch (error) { // Deciding on a stale count is still better than not deciding. logger.warn( - `Could not recount folders sharing a role (${contested.join(', ')}): ${(error as Error).message}`, + `Could not recount folders sharing a role (${contested.map((p) => folderLogLabel(p)).join(', ')}): ${(error as Error).message}`, ); } } @@ -3053,7 +3054,7 @@ export class SyncEngine { const decision = aliases.size === 0 ? 'collapsing none (the server has not proven any two are one mailbox)' - : `skipping ${[...aliases.keys()].join(', ')}`; + : `skipping ${[...aliases.keys()].map((p) => folderLogLabel(p)).join(', ')}`; const summary = `${roles} — ${decision}`; if (summary !== this.lastDuplicateRoleSummary) { this.lastDuplicateRoleSummary = summary; @@ -3091,11 +3092,11 @@ export class SyncEngine { try { const moved = await this.storage.refileLocalRows(from, to); if (moved > 0) { - logger.info(`Re-filed ${moved} local-only message(s) from ${aliasPath} to ${canonicalPath}`); + logger.info(`Re-filed ${moved} local-only message(s) from ${folderLogLabel(aliasPath)} to ${folderLogLabel(canonicalPath)}`); } } catch (error) { logger.warn( - `Could not re-file local rows from ${aliasPath} to ${canonicalPath}: ${(error as Error).message}`, + `Could not re-file local rows from ${folderLogLabel(aliasPath)} to ${folderLogLabel(canonicalPath)}: ${(error as Error).message}`, ); } } diff --git a/packages/core/src/imap/sync-state.ts b/packages/core/src/imap/sync-state.ts index 4d92559c..8acbe6ef 100644 --- a/packages/core/src/imap/sync-state.ts +++ b/packages/core/src/imap/sync-state.ts @@ -2,6 +2,7 @@ import { EventEmitter } from 'events'; +import { folderLogLabel } from '../utils/log-labels'; import { logger } from '../utils/logger'; /** @@ -122,7 +123,7 @@ export class SyncStateManager extends EventEmitter { if (state.lastSyncTime) { const age = Date.now() - state.lastSyncTime; if (age > SyncStateManager.STALE_SYNC_TIMEOUT_MS) { - logger.warn(`Stale sync detected for ${folderPath}, marking as error`); + logger.warn(`Stale sync detected for ${folderLogLabel(folderPath)}, marking as error`); this.setFolderError(folderPath, new Error('Sync timeout')); return false; } diff --git a/packages/core/src/oauth/token-refresher.ts b/packages/core/src/oauth/token-refresher.ts index fee553ab..f61a0ba3 100644 --- a/packages/core/src/oauth/token-refresher.ts +++ b/packages/core/src/oauth/token-refresher.ts @@ -118,6 +118,11 @@ async function postToTokenEndpoint( headers: init.headers, body: init.body, signal, + // Never followed: a 307/308 answer would make fetch POST the same body + // (a refresh token, an authorization code and its verifier) again, to + // wherever the Location names. Node reports it as a network failure, + // classified below. + redirect: 'error', }); } catch (err) { // An abort is not a network fault, and above all not an auth fault: the @@ -143,6 +148,14 @@ async function postToTokenEndpoint( } const e = err as Error & { cause?: { code?: string; message?: string } }; + // undici's word for a redirect refused by `redirect: 'error'`. + if (e.cause?.message === 'unexpected redirect') { + logger.error('[OAuth] Token endpoint answered with a redirect, not followed:', tokenEndpoint); + throw new OAuthError( + `OAuth server at ${tokenEndpoint} answered with a redirect, which is not followed (it would resend the request's credentials)`, + codes.network, + ); + } const causeCode = e.cause?.code ? ` [${e.cause.code}]` : ''; const causeMsg = e.cause?.message ? `: ${e.cause.message}` : ''; logger.error('[OAuth] Network error reaching', tokenEndpoint, e); @@ -163,8 +176,11 @@ async function postToTokenEndpoint( * with a bare `SyntaxError`, whose `code` is `undefined`, so callers that * branch on `err.code` (see `isTerminalOAuthError` in the desktop * oauth-service) can classify it neither as terminal nor as transient. - * A snippet of the body is carried in the message/detail so the log shows - * WHAT answered instead of just "Unexpected token <". + * The message and the log say what answered by its content type and size + * only: a body that is not JSON can still be a token response in another + * encoding (`access_token=…&refresh_token=…`), so not a character of it + * is written. The whole body stays on `detail`, which is read to classify + * the error and never logged. * * 2. EMPTY / WHITESPACE access_token on a 200 — some servers report a * transient internal failure this way. Passing it through means the caller @@ -175,6 +191,16 @@ async function postToTokenEndpoint( * the source gives it its own code so the caller can tell "the server gave * us nothing usable" from "our token is dead". */ +// A media type is a token (`text/html`), not prose; anything else is not written. +const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]{1,64}\/[a-z0-9!#$&^_.+-]{1,64}$/; + +/** A body for a log line: its content type (without parameters) and its length. */ +function describeBody(res: Response, raw: string): string { + const type = (res.headers?.get?.('content-type') ?? '').split(';')[0].trim().toLowerCase(); + const kind = MEDIA_TYPE.test(type) ? type : 'unknown type'; + return raw.length === 0 ? `empty body, ${kind}` : `${raw.length} characters of ${kind}`; +} + async function parseTokenResponse( res: Response, codes: { invalidResponse: string; emptyAccessToken: string }, @@ -185,10 +211,10 @@ async function parseTokenResponse( try { parsed = JSON.parse(raw) as OAuthTokenResponse; } catch { - const snippet = raw.trim().slice(0, 200); - logger.error(`[OAuth] ${what} returned a non-JSON body:`, snippet || '(empty)'); + const shape = describeBody(res, raw); + logger.error(`[OAuth] ${what} returned a non-JSON body: ${shape}`); throw new OAuthError( - `${what} returned a non-JSON body (${res.status}): ${snippet || 'empty body'}`, + `${what} returned a non-JSON body (${res.status}): ${shape}`, codes.invalidResponse, raw, ); diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index 55f90966..877dae34 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -36,6 +36,8 @@ export * from './stale-flags'; export * from './format-bytes'; export * from './log-aggregator'; export * from './log-text'; +export * from './log-labels'; +export * from './log-paths'; export * from './tags'; export * from './tls'; export * from './connection-security'; diff --git a/packages/core/src/utils/log-labels.ts b/packages/core/src/utils/log-labels.ts new file mode 100644 index 00000000..f315df04 --- /dev/null +++ b/packages/core/src/utils/log-labels.ts @@ -0,0 +1,116 @@ +import { fnv1a32Hex } from './fnv1a'; + +/** + * Stand-ins a log line uses for names that belong to the user: the account + * (whose id spells out the address), folders and labels they created, and AI + * categories they named. Each is a short hash, so lines about the same thing + * still read as the same thing and `grep` still finds them, but the name + * itself never reaches app.log or a crash report. + * + * A hash of a guessable name can be confirmed by someone who already has the + * name (the per-account database file name, a truncated SHA-256 of the same + * id, has the same property); it can never be read back. That is the line + * drawn here: a log a user attaches to a bug report must not tell a reader + * whose mailbox it is or what its folders are called. + * + * Pure, and imports only `fnv1a` (itself import-free), so the renderer + * deep-imports it as `@sarvinbox/core/log-labels` and labels the same names + * the same way main does. + */ + +const label = (kind: string, value: string): string => `${kind}#${fnv1a32Hex(value)}`; + +/** + * An account id for a log line: `acct#` and 8 hex digits. An id is built from + * the address and the server (`acct----`, see + * accountIdFor), so writing it as is names the account's owner on every line + * that mentions it. A missing id is written as `missing` (`acct#none` unless + * the caller says what no id means there, such as `active`). + */ +export function accountLogLabel(id: unknown, missing = 'acct#none'): string { + if (typeof id !== 'string' || id.length === 0) return missing; + return label('acct', id); +} + +// What accountIdFor produces: `acct-` and the normalised address and host, +// which are lower-case letters, digits and dashes only. One character class +// with one quantifier, so the scan is linear however the text is built. +const ACCOUNT_ID = /\bacct-[a-z0-9-]+/g; + +/** + * Every account id in `text` replaced by its {@link accountLogLabel}: the + * backstop for a line that wrote an id without labelling it. A label is not + * matched again (`acct#…` is not `acct-…`), so running this twice changes + * nothing. An id followed by more dashes and letters (`${id}-backfill`) is + * labelled with them, which only makes that one label differ. + */ +export function redactAccountIds(text: string): string { + return text.replace(ACCOUNT_ID, (id) => accountLogLabel(id)); +} + +// Folder names every server or provider uses for its own folders. They name +// nothing the user typed, and a log line that says "Sent Items" or +// "[Gmail]/All Mail" is far easier to debug than a hash, so they stay as +// written. Compared case-insensitively. Anything else is a folder the user +// (or someone sharing it with them) named: a client, a person, a project. +const SYSTEM_FOLDER_NAMES = new Set( + [ + 'INBOX', 'Outbox', 'Archive', 'Archives', 'All Mail', 'Notes', 'Starred', 'Important', + 'Sent', 'Sent Items', 'Sent Messages', 'Sent Mail', + 'Drafts', 'Draft', + 'Trash', 'Deleted', 'Deleted Items', 'Deleted Messages', 'Bin', + 'Spam', 'Junk', 'Junk Email', 'Junk E-mail', 'Bulk Mail', + '[Gmail]', '[Google Mail]', + 'Conversation History', 'Scheduled', 'Snoozed', + ].map((name) => name.toLowerCase()), +); +const PROVIDER_ROOTS = ['[gmail]/', '[google mail]/']; +// The app's own views and ids: `virtual-starred`, a generated `folder-<16 hex>` +// id (already a hash of the path), `section:inbox`. Ours, so as written. +const APP_FOLDER_ID = /^(?:virtual-[a-z-]{1,32}|folder-[a-f0-9]{16}|section:[a-z0-9_-]{1,32})$/; + +function isSystemFolderName(path: string): boolean { + const lower = path.toLowerCase(); + if (SYSTEM_FOLDER_NAMES.has(lower)) return true; + // `[Gmail]/Sent Mail`, `INBOX.Sent`, `INBOX/Drafts`: a provider root or the + // inbox, then one system name. `INBOX/Acme` is the user's. + for (const root of [...PROVIDER_ROOTS, 'inbox/', 'inbox.']) { + if (lower.startsWith(root)) return SYSTEM_FOLDER_NAMES.has(lower.slice(root.length)); + } + return false; +} + +/** + * A folder path for a log line: a system folder (`INBOX`, `Sent Items`, + * `[Gmail]/All Mail`) and the app's own view ids (`virtual-starred`) as + * written, any other folder as `folder#` and 8 hex digits. Folder names are + * typed by the user (often a person's or a client's name), so they are user + * text. `folder#none` for a missing path. + */ +export function folderLogLabel(path: unknown): string { + if (typeof path !== 'string' || path.length === 0) return 'folder#none'; + if (path.length <= 64 && (isSystemFolderName(path) || APP_FOLDER_ID.test(path))) return path; + return label('folder', path); +} + +/** + * A label or tag name the user created (a Gmail label, a local tag) for a log + * line: `label#` and 8 hex digits. `label#none` for a missing name. + */ +export function labelLogLabel(name: unknown): string { + if (typeof name !== 'string' || name.length === 0) return 'label#none'; + return label('label', name); +} + +/** + * An AI category for a log line: a built-in category's slug as written (the + * app named it), a category the user created as `category#` and 8 hex digits + * (its slug is made from the name they typed). `system` is the definition's + * `is_system` flag; when the caller does not know it, pass a set of the + * built-in slugs instead. + */ +export function categoryLogLabel(slug: unknown, system: boolean | ReadonlySet): string { + if (typeof slug !== 'string' || slug.length === 0) return 'category#none'; + const builtIn = typeof system === 'boolean' ? system : system.has(slug); + return builtIn ? slug : label('category', slug); +} diff --git a/packages/core/src/utils/log-paths.ts b/packages/core/src/utils/log-paths.ts new file mode 100644 index 00000000..bb06f9b1 --- /dev/null +++ b/packages/core/src/utils/log-paths.ts @@ -0,0 +1,81 @@ +import { basename, isAbsolute, relative, sep } from 'path'; + +import { trimCharsEnd } from './trim-chars'; + +/** + * File paths for a log line. Every path the app writes is under the user's + * home folder, and the home folder is named after the user (`/Users/`, + * `C:\Users\`), so an absolute path names the person whose log it is. + * Node-only (uses `path`); the renderer never sees a real path. + */ + +export interface LogPathRoots { + /** The app's data folder (`app.getPath('userData')`). */ + userData?: string; + /** The user's home folder (`os.homedir()`). */ + home?: string; +} + +function inside(root: string | undefined, path: string): string | null { + if (!root) return null; + const rel = relative(root, path); + if (rel === '') return '.'; + return rel.startsWith('..') || isAbsolute(rel) ? null : rel; +} + +/** + * A path for a log line: `/…` for a file in the app's data folder, + * `~/…` for one elsewhere under home, and the file name alone for anything + * else (a path outside home says nothing about where it is that the log needs). + * Separators are written as `/` so lines read the same on every OS. + */ +export function pathForLog(path: unknown, roots: LogPathRoots): string { + if (typeof path !== 'string' || path.length === 0) return 'none'; + if (!isAbsolute(path)) return basename(path); + const inData = inside(roots.userData, path); + if (inData !== null) return inData === '.' ? '' : `/${inData.split(sep).join('/')}`; + const inHome = inside(roots.home, path); + if (inHome !== null) return inHome === '.' ? '~' : `~/${inHome.split(sep).join('/')}`; + return basename(path); +} + +// A character that can continue a folder name: `/Users/rc` must not match +// inside `/Users/rcsarv`. +const NAME_CHAR = /[\p{L}\p{N}._ -]/u; + +/** + * `text` with every occurrence of the home folder replaced by `~`: the + * backstop for a line (a library's message, a stack trace) that wrote an + * absolute path. Also matches the home written with forward slashes and with + * doubled backslashes (how util.inspect prints a Windows path inside an + * object). An occurrence followed by more of a folder name is left alone, so + * a home of `/Users/rc` never rewrites `/Users/rcsarv`. Linear: indexOf scans. + * A home shorter than 3 characters (`/`, a misconfigured HOME) is not used. + */ +export function redactHomeDir(text: string, home: string | undefined): string { + if (!home || home.length < 3) return text; + const trimmed = trimCharsEnd(home, '\\/'); + if (trimmed.length < 3) return text; + const forms = new Set([trimmed, trimmed.replace(/\\/g, '/'), trimmed.replace(/\\/g, '\\\\')]); + let out = text; + for (const form of forms) out = replaceWhole(out, form); + return out; +} + +function replaceWhole(text: string, needle: string): string { + let from = 0; + let at = text.indexOf(needle, from); + if (at === -1) return text; + let out = ''; + while (at !== -1) { + const next = text.charAt(at + needle.length); + if (next === '' || !NAME_CHAR.test(next)) { + out += `${text.slice(from, at)}~`; + } else { + out += text.slice(from, at + needle.length); + } + from = at + needle.length; + at = text.indexOf(needle, from); + } + return out + text.slice(from); +} diff --git a/packages/core/src/utils/telemetry-scrub.ts b/packages/core/src/utils/telemetry-scrub.ts index 0c88676b..854b6baa 100644 --- a/packages/core/src/utils/telemetry-scrub.ts +++ b/packages/core/src/utils/telemetry-scrub.ts @@ -7,8 +7,9 @@ * from a user's mailbox are mailbox data (Google's Limited Use policy covers * them for Gmail accounts), so they must not reach a crash-reporting vendor. * The shapes here are structural — no Sentry types — so both the Electron main - * process and the renderer share ONE implementation. No imports: the renderer - * deep-imports this file (`@sarvinbox/core/telemetry-scrub`). + * process and the renderer share ONE implementation. The renderer deep-imports + * this file (`@sarvinbox/core/telemetry-scrub`), so it imports only modules + * that import nothing themselves (`log-labels`, and its `fnv1a`). * * Why a regex and not a library: the job is to FIND addresses in free text, not * to parse an address header (`email-addresses` does that and can't scan @@ -18,6 +19,8 @@ * redacting a false positive loses nothing, missing an address leaks it. */ +import { redactAccountIds } from './log-labels'; + const EMAIL_RE = /[A-Za-z0-9._%+'-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})+/g; export const REDACTED_EMAIL = '[email]'; @@ -27,6 +30,14 @@ export function redactEmailAddresses(text: string): string { return text.replace(EMAIL_RE, REDACTED_EMAIL); } +// The credential names, as one alternation: config keys, OAuth fields (the PKCE +// verifier and a client assertion are as good as the secret they stand for), +// key material (`secretKey`, `privateKey`, a key's `passphrase`) and header +// names. Matched case-insensitively, `_`/`-` optional between words. +const SECRET_NAMES = + 'password|passwd|pass|passphrase|access[_-]?token|refresh[_-]?token|id[_-]?token|token|authorization|' + + 'api[_-]?key|client[_-]?secret|client[_-]?assertion|code[_-]?verifier|secret[_-]?key|private[_-]?key|secret'; + // Credential-ish key/value pairs, matched in both JSON (`"password":"x"`) and // util.inspect (`password: 'x'`) forms, so a stray console.log(config) or an // error carrying a token can never land in app.log (or a crash report) in @@ -40,8 +51,46 @@ export function redactEmailAddresses(text: string): string { // unterminated value full of backslashes (`"password":"\\a\\a…`) backtracked // exponentially — about 3 s of main-thread stall at 40 of them. What matches is // unchanged (fuzz-compared against the old pattern); only the blow-up is gone. -const SECRET_KV_RE = /(["']?(?:password|passwd|pass|access[_-]?token|refresh[_-]?token|id[_-]?token|token|authorization|api[_-]?key|client[_-]?secret|secret)["']?\s*[:=]\s*)(["'`])(?:\\.|(?!\2)[^\\\n\r\u2028\u2029]|\\(?=\2))*\2/gi; +const SECRET_KV_RE = new RegExp( + `(["']?(?:${SECRET_NAMES})["']?\\s*[:=]\\s*)(["'\`])(?:\\\\.|(?!\\2)[^\\\\\\n\\r\\u2028\\u2029]|\\\\(?=\\2))*\\2`, + 'gi', +); + +// The same pairs inside JSON that was itself put in a JSON string, so every +// quote is escaped: `"body":"{\"access_token\":\"ya29…\"}"` (a provider's +// error body logged inside an object). Up to three backslashes before each +// quote cover one or two levels of nesting. The value is every character up +// to the next escaped quote; a backslash that does not start one (`\/`, as +// some encoders write a slash) stays part of the value. Each character can +// only be read one way and every lookahead is bounded, so it is linear. +const ESCAPED_SECRET_KV_RE = new RegExp( + `(\\\\{1,3}"(?:${SECRET_NAMES})\\\\{1,3}"\\s*:\\s*\\\\{1,3}")(?:[^\\\\"\\n\\r]|\\\\(?!\\\\{0,3}"))*`, + 'gi', +); + +// The same names written without quotes: `access_token=ya29…` in a URL or a +// form body, `password: hunter2` in a library's message. The value runs to the +// next space, separator or quote. A word we write ourselves in place of a +// value (`token=yes`, `password: set`) is not a secret and is left as is. +// An Authorization scheme word (`Bearer`, `Basic`) is not the credential +// either: the rules above already replaced what follows it. +const PLACEHOLDER = '(?:yes|no|true|false|null|undefined|none|set|unset|missing|present|absent|\\[REDACTED\\])(?![^\\s&,;"\'`<>)\\]}])'; +const AUTH_SCHEME_WORD = '(?:bearer|basic|digest|ntlm|negotiate|token)\\s'; +const UNQUOTED_SECRET_RE = new RegExp( + `(\\b(?:${SECRET_NAMES})\\s*[:=]\\s*)(?![\\s"'\`]|${PLACEHOLDER}|${AUTH_SCHEME_WORD})[^\\s&,;"'\`<>)\\]}]+`, + 'gi', +); + +// Names that are only secret in a URL's query or a form body, where they hold +// an OAuth authorization `code`, an API `key` (Gemini's `?key=`), a request +// `sig`nature or a client `assertion`. Not matched elsewhere: `code` is also +// every error code we log (`code: 'ETIMEDOUT'`). +const QUERY_SECRET_RE = /([?&;](?:code|key|sig|signature|x-amz-signature|x-goog-signature|assertion|state)=)[^&\s#"'`<>]+/gi; + const BEARER_RE = /\b(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi; +// Every other way an Authorization header carries a credential: `Basic` +// (base64 user:password), `Digest`, `NTLM`, `Negotiate`, a bare `Token`. +const AUTH_SCHEME_RE = /(\bauthorization\b["']?\s*[:=]\s*["']?(?:basic|digest|ntlm|negotiate|token)\s+)[^\s"',;]+/gi; export const REDACTED_SECRET = '[REDACTED]'; @@ -54,12 +103,19 @@ export const REDACTED_SECRET = '[REDACTED]'; export function redactSecrets(s: string): string { return s .replace(SECRET_KV_RE, (_m, key: string, quote: string) => `${key}${quote}${REDACTED_SECRET}${quote}`) - .replace(BEARER_RE, `$1${REDACTED_SECRET}`); + .replace(ESCAPED_SECRET_KV_RE, `$1${REDACTED_SECRET}`) + .replace(AUTH_SCHEME_RE, `$1${REDACTED_SECRET}`) + .replace(BEARER_RE, `$1${REDACTED_SECRET}`) + .replace(UNQUOTED_SECRET_RE, `$1${REDACTED_SECRET}`) + .replace(QUERY_SECRET_RE, `$1${REDACTED_SECRET}`); } -/** Secrets, then email addresses: what every text in a crash report gets. */ +/** + * Secrets, then email addresses, then account ids (which spell out an + * address, see accountLogLabel): what every text in a crash report gets. + */ export function scrubText(text: string): string { - return redactEmailAddresses(redactSecrets(text)); + return redactAccountIds(redactEmailAddresses(redactSecrets(text))); } /** @@ -99,9 +155,19 @@ function scrubValue(key: string, value: unknown, depth: number): unknown { return scrubRecord(value as Record, depth - 1); } +// Fields that hold a URL's query string or fragment on their own, which no +// URL key above sees: Sentry's fetch and XHR breadcrumbs keep `http.query` +// (`?key=…&q=…`) and `http.fragment` beside a `url` it has already cut. They +// are dropped, as the request's `query_string` is: a query carries API keys, +// OAuth codes, search words and addresses, and triage needs the path only. +const QUERY_KEY_RE = /^(?:http\.)?(?:query|fragment)$|^query[_-]?string$/i; + function scrubRecord(record: Record, depth = MAX_DEPTH): Record { const out: Record = {}; - for (const [k, v] of Object.entries(record)) out[k] = scrubValue(k, v, depth); + for (const [k, v] of Object.entries(record)) { + if (QUERY_KEY_RE.test(k)) continue; + out[k] = scrubValue(k, v, depth); + } return out; } @@ -113,7 +179,7 @@ export interface ScrubbableBreadcrumb { /** * A copy of the breadcrumb with addresses and secrets redacted (in its message * and, by value and by field name, all through its data) and URL queries - * dropped. + * dropped — from its URL fields and as fields of their own (`http.query`). */ export function scrubBreadcrumb(crumb: T): T { const out: T = { ...crumb }; diff --git a/packages/core/test/unit/config/folder-classification.test.ts b/packages/core/test/unit/config/folder-classification.test.ts index 6be4ccdc..85739c70 100644 --- a/packages/core/test/unit/config/folder-classification.test.ts +++ b/packages/core/test/unit/config/folder-classification.test.ts @@ -407,6 +407,18 @@ describe('describeDuplicateRoles', () => { ); }); + // Breaks: a user-named candidate (a person's or client's name) reaches app.log + // through the duplicate-role line; system names stay readable. + it('writes a user-named candidate and winner as their folder label', () => { + const summary = describeDuplicateRoles([ + { path: 'Acme Outgoing', specialUse: '\\Sent' }, + { path: 'Sent' }, + ]); + expect(summary).not.toContain('Acme'); + expect(summary).toMatch(/^sent: folder#[0-9a-f]{8} \(/); + expect(summary).toContain('| Sent ('); + }); + // Breaks: the case that actually needs explaining — a duplicate that was NOT // collapsed. "uidValidity=none" in the line is the whole answer. it('shows the missing evidence when a mailbox has never been selected', () => { diff --git a/packages/core/test/unit/imap/folder-name-log-privacy.test.ts b/packages/core/test/unit/imap/folder-name-log-privacy.test.ts new file mode 100644 index 00000000..20c8411b --- /dev/null +++ b/packages/core/test/unit/imap/folder-name-log-privacy.test.ts @@ -0,0 +1,358 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ImapFlowClient } from '../../../src/imap/imapflow-client'; +import { OperationQueue } from '../../../src/imap/operation-queue'; +import { RealtimeManager } from '../../../src/imap/realtime-manager'; +import { SyncEngine } from '../../../src/imap/sync-engine'; +import { FakeEmailStorage, resetFakeStorageIds } from '../../../src/test-support/fake-email-storage'; +import { FakeImapServer, resetFakeMessageIds } from '../../../src/test-support/fake-imap-server'; +import { captureLogs, type CapturedLogs } from '../../../src/test-support/log-capture'; +import { IMAPError, type IMAPFolder } from '../../../src/types/imap'; +import type { IEmailStorage } from '../../../src/types/storage'; +import { accountIdFor } from '../../../src/utils/id'; +import { folderLogLabel, labelLogLabel } from '../../../src/utils/log-labels'; +import { getLogLevel, setLogLevel, setLogSink } from '../../../src/utils/logger'; + +// app.log ships with bug reports and crash reports carry its recent lines. A +// folder's name is text the user typed (a client, a person, a project), so the +// IMAP layer writes it as `folder#`; a custom keyword or label the same +// way as `label#`. These tests drive the real classes against the +// in-memory server with a user-named folder and fail on any line that spells +// the name, the owner's address or the account id — and on a run that stops +// writing the lines altogether, which would pass a "nothing leaked" check by +// saying nothing. + +const FOLDER = 'Clients/Acme-Sentinel-7f3'; +const OTHER = 'Clients/Beta-Acme-Sentinel-7f3'; +const OWNER = 'owner.sentinel@example.com'; +// No class under src/imap takes an account id (the desktop layer owns it), so +// it cannot be handed to them; it is still checked for, with the address it is +// built from, in case a line ever starts writing either. +const ACCOUNT_ID = accountIdFor(OWNER, 'imap.example.com'); +const SENTINELS = ['Acme-Sentinel-7f3', 'owner-sentinel', 'owner.sentinel', ACCOUNT_ID]; +const FOLDER_LABEL = folderLogLabel(FOLDER); + +const imapFolder = (path: string): IMAPFolder => ({ + name: path.split('/').pop() ?? path, + path, + delimiter: '/', + specialUse: null, + subscribed: true, + selectable: true, + children: [], +}); + +/** The lines that spell anything the user named. Empty is the pass. */ +const leaks = (logs: CapturedLogs): string[] => + logs.lines.filter((line) => SENTINELS.some((sentinel) => line.includes(sentinel))); + +/** What an ImapFlow command failure looks like once toImapError has wrapped it: + * the server's text and the command we sent, both quoting the mailbox. */ +const serverError = (code: string) => + new IMAPError( + `Command failed: NO [UNAVAILABLE] Mailbox ${FOLDER} is busy (cmd: SELECT "${FOLDER}")`, + code, + `[UNAVAILABLE] Mailbox ${FOLDER} is busy`, + `SELECT "${FOLDER}"`, + 'NO', + ); + +let logs: CapturedLogs; +beforeEach(() => { + resetFakeMessageIds(); + resetFakeStorageIds(); + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(() => { + logs.stop(); + vi.restoreAllMocks(); +}); + +function engineSetup() { + const server = new FakeImapServer({ condstore: true, host: 'imap.example.com' }); + server.addFolder('INBOX', { uidValidity: 1 }); + server.addFolder(FOLDER, { uidValidity: 7 }); + const db = new FakeEmailStorage(); + db.addFolder('INBOX', { uidValidity: 1 }); + db.addFolder(FOLDER, { uidValidity: 7 }); + const engine = new SyncEngine(db.asStorage()); + vi.spyOn(engine, 'isConnected').mockReturnValue(true); + const internals = engine as unknown as { + connectionManager: { _client: unknown; ensureConnection: () => Promise }; + reselectMonitoredFolder: () => Promise; + }; + internals.connectionManager._client = server; + internals.connectionManager.ensureConnection = async () => true; + internals.reselectMonitoredFolder = async () => {}; + vi.spyOn(server, 'listFolders').mockResolvedValue([imapFolder('INBOX'), imapFolder(FOLDER)]); + const mail = (subject: string) => ({ subject, from: 'sender@example.org', to: [OWNER] }); + return { server, db, engine, mail }; +} + +describe('SyncEngine — a user-named folder never reaches app.log', () => { + // Regression: a user-named folder's name reaches app.log on every sync line + // (full sync, incremental sync, flag reconcile, deletion reconcile). + it('labels the folder through a full sync and an incremental sync', async () => { + const { server, db, engine, mail } = engineSetup(); + const [first] = server.addMessages(FOLDER, 3, mail('Quarterly numbers')); + + await engine.syncAll(); + expect(db.rowsTaggedWith(FOLDER)).toHaveLength(3); // the sync really ran + + // Another client reads one, deletes one, and two new ones arrive. + server.setFlagsOnServer(FOLDER, first, ['\\Seen']); + server.expungeOnServer(FOLDER, first + 1); + server.addMessages(FOLDER, 2, mail('Follow-up')); + await engine.syncAll(); + expect(db.rowsTaggedWith(FOLDER)).toHaveLength(4); + + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`Full sync ${FOLDER_LABEL}`)).not.toEqual([]); + expect(logs.containing(`Incremental sync ${FOLDER_LABEL}`)).not.toEqual([]); + // System folders stay readable: the label only replaces what the user named. + expect(logs.containing('Syncing 2 folders: INBOX, ' + FOLDER_LABEL)).not.toEqual([]); + }); + + // Regression (transient): a timed-out batch logs the server's text, which + // names the mailbox, on its way to "continuing". + it('labels the folder and drops the error text when a full-sync batch fails', async () => { + const { server, engine, mail } = engineSetup(); + server.addMessages(FOLDER, 3, mail('Retainer')); + vi.spyOn(server, 'fetchMessages').mockRejectedValueOnce( + Object.assign(new Error(`IMAP FETCH timed out in ${FOLDER}`), { code: 'ETIMEDOUT' }), + ); + + await engine.syncAll(); + + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`Full sync ${FOLDER_LABEL}: batch`).join('\n')).toContain('failed: ETIMEDOUT; continuing'); + }); + + // Regression (permanent): the folder-level failure logs the whole IMAPError, + // whose message, server response and command all quote the mailbox. + it('logs a failed folder sync by label and error code only', async () => { + const { server, engine, mail } = engineSetup(); + server.addMessages(FOLDER, 2, mail('Contract')); + const select = server.selectFolder.bind(server); + vi.spyOn(server, 'selectFolder').mockImplementation(async (path: string) => { + if (path === FOLDER) throw serverError('SELECT_FOLDER_ERROR'); + return select(path); + }); + + await engine.syncAll(); + + expect(leaks(logs)).toEqual([]); + const failed = logs.containing(`Failed to sync folder ${FOLDER_LABEL}`); + expect(failed).toHaveLength(1); + expect(failed[0]).toContain("code: 'SELECT_FOLDER_ERROR'"); + }); + + // Regression (partial run + re-run): an incremental fetch that fails, then + // succeeds on the next pass, must not write the name on either pass. + it('labels the folder when an incremental fetch fails and the re-run recovers', async () => { + const { server, db, engine, mail } = engineSetup(); + server.addMessages(FOLDER, 2, mail('Invoice')); + await engine.syncAll(); + server.addMessages(FOLDER, 2, mail('Invoice, again')); + vi.spyOn(server, 'fetchMessagesByUidRange').mockRejectedValueOnce(serverError('FETCH_ERROR')); + + await engine.syncAll(); // the failing pass + // The re-run is forced (skipUnchanged off) on purpose. With the default the + // folder is skipped as "unchanged": syncFolder records the server's + // EXISTS/UIDNEXT before the fetch that failed, so nothing looks new. That is + // a separate, known sync gap (raised, not fixed here); this test is about + // what the lines say, not about when the mail lands. + await engine.syncAll({ skipUnchanged: false }); + + expect(db.rowsTaggedWith(FOLDER)).toHaveLength(4); + expect(leaks(logs)).toEqual([]); + const failed = logs.containing(`Failed to sync folder ${FOLDER_LABEL}`); + expect(failed).toHaveLength(1); + expect(failed[0]).toContain("code: 'FETCH_ERROR'"); + }); + + // Regression (multi-account): two accounts syncing side by side each write + // their own folder by label; one engine's lines never carry the other's name. + it('labels each account\'s folders when two accounts sync side by side', async () => { + const first = engineSetup(); + const second = engineSetup(); + second.server.addFolder(OTHER, { uidValidity: 9 }); + second.db.addFolder(OTHER, { uidValidity: 9 }); + vi.spyOn(second.server, 'listFolders').mockResolvedValue([imapFolder('INBOX'), imapFolder(OTHER)]); + first.server.addMessages(FOLDER, 2, first.mail('Ledger')); + second.server.addMessages(OTHER, 2, second.mail('Ledger')); + + await Promise.all([first.engine.syncAll(), second.engine.syncAll()]); + + expect(second.db.rowsTaggedWith(OTHER)).toHaveLength(2); + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`Full sync ${FOLDER_LABEL}`)).toHaveLength(1); + expect(logs.containing(`Full sync ${folderLogLabel(OTHER)}`)).toHaveLength(1); + }); +}); + +/** The pending-operation rows the queue persists before it sends a command. */ +function queueStorage(db: FakeEmailStorage): IEmailStorage { + const ops = new Map(); + let seq = 0; + const save = (op: { type: string; folderPath: string; uid: number; data?: unknown; retryCount: number }) => { + const id = ++seq; + ops.set(id, { ...op, id, status: 'pending' }); + return id; + }; + const storage = { + getFolderByPath: (path: string) => db.getFolderByPath(path), + getFolders: () => db.getFolders(), + getEmail: (id: string) => db.getEmail(id), + updateEmail: (id: string, updates: Record) => db.updateEmail(id, updates), + getEmailByFolderAndUid: async () => null, + savePendingOperation: async (op: Parameters[0]) => save(op), + savePendingOperationsBatch: async (list: Array[0]>) => list.map(save), + getPendingOperations: async () => [...ops.values()].filter((op) => op.status !== 'failed'), + getFailedOperations: async () => [...ops.values()].filter((op) => op.status === 'failed'), + getPendingOperationUidsByFolder: async () => [], + updatePendingOperationStatus: async (id: number, status: string) => { const op = ops.get(id); if (op) op.status = status; }, + updatePendingOperationRetry: async () => {}, + deletePendingOperation: async (id: number) => { ops.delete(id); }, + deletePendingOperationsBatch: async (ids: number[]) => { for (const id of ids) ops.delete(id); }, + markPendingOperationFailed: async (id: number) => { const op = ops.get(id); if (op) op.status = 'failed'; }, + }; + return storage as unknown as IEmailStorage; +} + +describe('OperationQueue — a user-named folder never reaches app.log', () => { + async function queueSetup() { + const server = new FakeImapServer({ host: 'imap.example.com' }); + await server.connect(); + server.addFolder('INBOX'); + server.addFolder(FOLDER); + server.addFolder(OTHER); + const db = new FakeEmailStorage(); + db.addFolder(FOLDER); + // OTHER is deliberately missing locally, so the move's UID writeback takes + // its "destination folder not found" line. + const queue = new OperationQueue(); + queue.initialize({ client: server, storage: queueStorage(db), isConnected: () => true, isSyncing: () => false }); + const uids = server.addMessages(FOLDER, 3, { from: 'sender@example.org', to: [OWNER] }); + return { server, queue, uids }; + } + + // Regression: a mark-read, a move between two user folders and a server + // label each write the folder or label name on their command line. + it('labels the folder on mark-read, move and server-label lines', async () => { + const { server, queue, uids } = await queueSetup(); + + await queue.markAsRead(FOLDER, uids[0]); + await queue.move(FOLDER, uids[1], OTHER); + await queue.createServerLabel('Acme-Sentinel-7f3 retainers'); + + expect(server.flagsOf(FOLDER, uids[0])).toContain('\\Seen'); // the ops really ran + expect(server.messageCount(OTHER)).toBe(1); + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`mark-read folder="${FOLDER_LABEL}"`)).toHaveLength(1); + expect(logs.containing(`remapMovedUids: destination folder not found for "${folderLogLabel(OTHER)}"`)).toHaveLength(1); + expect(logs.containing(`CREATE "${labelLogLabel('Acme-Sentinel-7f3 retainers')}"`)).toHaveLength(1); + }); + + // Regression (permanent): a dead-lettered move logs the whole IMAPError, + // whose text and command name both folders. + it('logs a dead-lettered move by error code, not by its text', async () => { + const { server, queue, uids } = await queueSetup(); + vi.spyOn(server, 'moveMessages').mockRejectedValueOnce(serverError('MOVE_ERROR')); + + await expect(queue.move(FOLDER, uids[2], OTHER)).rejects.toThrow(); + + expect(leaks(logs)).toEqual([]); + const failed = logs.containing('failed (dead-lettered)'); + expect(failed).toHaveLength(1); + expect(failed[0]).toContain("code: 'MOVE_ERROR'"); + }); +}); + +describe('RealtimeManager — a user-named folder never reaches app.log', () => { + // Regression: IDLE start, the polling fallback and its failure line write the + // monitored folder's name. + it('labels the monitored folder on IDLE start and on the polling fallback', async () => { + const server = new FakeImapServer({ idle: true, host: 'imap.example.com' }); + await server.connect(); + server.addFolder(FOLDER); + const db = new FakeEmailStorage(); + db.addFolder(FOLDER); + const realtime = new RealtimeManager({ periodicSyncIntervalMs: 0 }); + realtime.initialize({ client: server, storage: db.asStorage() }); + try { + expect(await realtime.start(FOLDER)).toBe('idle'); + await realtime.stop(); + + // IDLE refused (the server's text names the mailbox): polling takes over. + vi.spyOn(server, 'startIdle').mockRejectedValueOnce(serverError('IDLE_ERROR')); + expect(await realtime.start(FOLDER)).toBe('polling'); + } finally { + await realtime.stop(); + } + + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`IDLE started for ${FOLDER_LABEL}`)).toHaveLength(1); + expect(logs.containing(`Polling started for ${FOLDER_LABEL}`)).toHaveLength(1); + expect(logs.containing('Failed to start IDLE').join('\n')).toContain("code: 'IDLE_ERROR'"); + }); +}); + +describe('ImapFlowClient keyword STORE line', () => { + /** A client whose ImapFlow connection is a stub, selected on `mailbox`. */ + function storeClient(mailbox: string | undefined) { + const client = new ImapFlowClient(); + const inner = { + usable: true, + mailbox: mailbox === undefined ? false : { path: mailbox }, + messageFlagsAdd: vi.fn(async () => true), + fetchAll: vi.fn(async () => [{ uid: 4, flags: new Set(['\\Seen', 'Acme-Sentinel-7f3', '$Finance']) }]), + stats: () => ({ sent: 0, received: 0 }), + }; + Object.assign(client as unknown as Record, { + client: inner, connectionState: 'selected', currentFolder: mailbox ?? null, capabilities: [], connectedHost: 'imap.example.com', + }); + return { client, inner }; + } + + // Regression: the category-label STORE line writes the user's keyword and the + // folder it was stored in, as typed. + it('labels custom keywords and the folder, and still sends them as typed', async () => { + const { client, inner } = storeClient(FOLDER); + + await client.addFlags([4], ['\\Seen', 'Acme-Sentinel-7f3']); + + expect(inner.messageFlagsAdd).toHaveBeenCalledWith([4], ['\\Seen', 'Acme-Sentinel-7f3'], { uid: true }); + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`+FLAGS (${labelLogLabel('Acme-Sentinel-7f3')}) in "${FOLDER_LABEL}" → matched=true`)).toHaveLength(1); + }); + + // Regression: the SARV_DEBUG_KEYWORDS read-back writes every keyword the + // server holds; system flags must stay readable. + it('labels keywords in the SARV_DEBUG_KEYWORDS read-back but keeps system flags', async () => { + vi.stubEnv('SARV_DEBUG_KEYWORDS', '1'); + try { + const { client } = storeClient(FOLDER); + await client.addFlags([4], ['Acme-Sentinel-7f3']); + } finally { + vi.unstubAllEnvs(); + } + + expect(leaks(logs)).toEqual([]); + expect(logs.containing(`uid 4: [\\Seen ${labelLogLabel('Acme-Sentinel-7f3')} ${labelLogLabel('$Finance')}]`)).toHaveLength(1); + }); + + // A STORE with no mailbox reported still says so, as before. + it('writes "?" when the connection reports no mailbox', async () => { + const { client } = storeClient(undefined); + await client.addFlags([4], ['Acme-Sentinel-7f3']); + expect(logs.containing('in "?" → matched=true')).toHaveLength(1); + }); + + // System-flag STOREs (the sync hot path) stay silent. + it('writes no line for a system-flag STORE', async () => { + const { client } = storeClient(FOLDER); + await client.addFlags([4], ['\\Seen']); + expect(logs.containing('UID STORE')).toEqual([]); + }); +}); diff --git a/packages/core/test/unit/oauth/token-refresher-redirect.test.ts b/packages/core/test/unit/oauth/token-refresher-redirect.test.ts new file mode 100644 index 00000000..03be1604 --- /dev/null +++ b/packages/core/test/unit/oauth/token-refresher-redirect.test.ts @@ -0,0 +1,103 @@ +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { isTerminalOAuthError } from '../../../src/oauth/oauth-errors'; +import { exchangeCodeForTokens, refreshAccessToken } from '../../../src/oauth/token-refresher'; +import { OAuthError, type OAuthProviderConfig } from '../../../src/oauth/types'; + +// The real fetch against two loopback servers (no outside network): the token +// endpoint answers 307 / 308 pointing at a second server. Breaks if the +// request is followed — fetch re-POSTs the same body on a 307/308, so the +// refresh token (or the authorization code and its PKCE verifier) would reach +// whatever host the Location names. + +interface Received { method?: string; body: string } + +function listen(handler: (req: IncomingMessage, body: string) => { status: number; headers?: Record; body?: string }): Promise<{ server: Server; url: string }> { + return new Promise((resolve) => { + const server = createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', () => { + const answer = handler(req, body); + res.writeHead(answer.status, answer.headers); + res.end(answer.body ?? ''); + }); + }); + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as AddressInfo; + resolve({ server, url: `http://127.0.0.1:${port}` }); + }); + }); +} + +let servers: Server[] = []; +let elsewhere: Received[]; +let elsewhereUrl: string; + +beforeEach(async () => { + elsewhere = []; + const target = await listen((req, body) => { + elsewhere.push({ method: req.method, body }); + return { status: 200, headers: { 'content-type': 'application/json' }, body: '{"access_token":"stolen","expires_in":60}' }; + }); + servers.push(target.server); + elsewhereUrl = target.url; + // The module logs the refusal; keep the test output quiet. + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(async () => { + await Promise.all(servers.map((s) => new Promise((resolve) => s.close(resolve)))); + servers = []; + vi.restoreAllMocks(); +}); + +async function redirectingProvider(status: 307 | 308): Promise { + const endpoint = await listen(() => ({ status, headers: { location: `${elsewhereUrl}/token` } })); + servers.push(endpoint.server); + return { + id: 'gmail', + label: 'Gmail', + purpose: 'email', + clientId: 'client-abc', + clientSecret: 'secret-xyz', + authEndpoint: `${endpoint.url}/auth`, + tokenEndpoint: `${endpoint.url}/token`, + userInfoEndpoint: `${endpoint.url}/userinfo`, + scopes: ['https://mail.google.com/'], + tokenBodyFormat: 'form', + }; +} + +describe('token requests never follow a redirect', () => { + it.each([307, 308] as const)('a refresh answered %i sends the refresh token nowhere else', async (status) => { + const provider = await redirectingProvider(status); + + const err = await refreshAccessToken({ provider, refreshToken: 'RT-SENTINEL' }).catch((e) => e); + + expect(elsewhere).toEqual([]); + expect(err).toBeInstanceOf(OAuthError); + expect(err.code).toBe('TOKEN_REFRESH_NETWORK_ERROR'); + expect(err.message).not.toContain('RT-SENTINEL'); + // Transient, not "signed out": a misrouted endpoint says nothing about the token. + expect(isTerminalOAuthError(err)).toBe(false); + }); + + it('a code exchange answered 307 sends the code and verifier nowhere else', async () => { + const provider = await redirectingProvider(307); + + const err = await exchangeCodeForTokens({ + provider, + code: 'CODE-SENTINEL', + codeVerifier: 'VERIFIER-SENTINEL', + redirectUri: 'http://127.0.0.1:41234/callback', + }).catch((e) => e); + + expect(elsewhere).toEqual([]); + expect(err).toBeInstanceOf(OAuthError); + expect(err.code).toBe('TOKEN_EXCHANGE_NETWORK_ERROR'); + }); +}); diff --git a/packages/core/test/unit/oauth/token-refresher.test.ts b/packages/core/test/unit/oauth/token-refresher.test.ts index 7cd95f45..12e0f959 100644 --- a/packages/core/test/unit/oauth/token-refresher.test.ts +++ b/packages/core/test/unit/oauth/token-refresher.test.ts @@ -8,6 +8,8 @@ import { } from '../../../src/oauth/token-refresher'; import { OAuthError } from '../../../src/oauth/types'; import type { OAuthProviderConfig } from '../../../src/oauth/types'; +import { captureLogs } from '../../../src/test-support/log-capture'; +import { getLogLevel, setLogLevel, setLogSink } from '../../../src/utils/logger'; // This module is the single point every signed-in account passes through on // every token expiry. A regression here logs EVERY user out: a wrong @@ -348,7 +350,11 @@ describe('refreshAccessToken — retryable vs terminal', () => { // CLASSIFIED OAuthError, not a raw SyntaxError: callers branch on `err.code` // (isTerminalOAuthError), and an unclassified throw reads as neither terminal // nor transient — so a network-level fault got treated as a dead token. - it('a non-JSON 200 body rejects as a classified OAuthError carrying the body', async () => { + // Changed deliberately (log privacy): the body moved from the MESSAGE to + // `detail` only. The message is logged by callers, and a non-JSON body can be + // a token response in another encoding; it now names the content type and + // size. Classification reads `detail`, so it is unchanged. + it('a non-JSON 200 body rejects as a classified OAuthError carrying the body on detail only', async () => { fetchMock.mockResolvedValue({ ok: true, status: 200, @@ -362,7 +368,61 @@ describe('refreshAccessToken — retryable vs terminal', () => { expect(err).toBeInstanceOf(OAuthError); expect(err.code).toBe('TOKEN_REFRESH_INVALID_RESPONSE'); - expect(err.message).toContain('captive portal'); + expect(err.detail).toContain('captive portal'); + expect(err.message).not.toContain('captive portal'); + expect(err.message).toContain('27 characters of unknown type'); + }); + + // Regression: a token endpoint answering 200 with a form-encoded token + // (`access_token=…&refresh_token=…`) wrote 200 characters of it to app.log. + it('logs only the content type and length of a non-JSON body, never its text', async () => { + const logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + try { + fetchMock.mockResolvedValue({ + ok: true, + status: 200, + headers: new Headers({ 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' }), + json: vi.fn(), + text: vi.fn(async () => 'access_token=ya29.SENTINEL-AT&refresh_token=1//SENTINEL-RT&expires_in=3599'), + } as unknown as Response); + + const err = await refreshAccessToken({ provider: FORM_PROVIDER, refreshToken: 'rt' }).catch((e) => e); + + expect(err.code).toBe('TOKEN_REFRESH_INVALID_RESPONSE'); + expect(err.message).toBe('Token refresh returned a non-JSON body (200): 74 characters of application/x-www-form-urlencoded'); + expect(logs.containing('SENTINEL')).toEqual([]); + expect(logs.containing('74 characters of application/x-www-form-urlencoded')).toHaveLength(1); + } finally { + logs.stop(); + } + }); + + // Regression: an empty or prose content type is written as "unknown type", never echoed. + it('names an empty body, and never writes a content type that is not a media type', async () => { + fetchMock.mockResolvedValue({ + ok: true, + status: 200, + headers: new Headers({ 'content-type': 'text/html please-log-me' }), + json: vi.fn(), + text: vi.fn(async () => ''), + } as unknown as Response); + + const err = await refreshAccessToken({ provider: FORM_PROVIDER, refreshToken: 'rt' }).catch((e) => e); + + expect(err.message).toBe('Token refresh returned a non-JSON body (200): empty body, unknown type'); + }); + + // Regression: a 307/308 from the token endpoint made fetch re-POST the + // refresh token to whatever the Location named. + it('never follows a redirect, and classifies a refused one as a transient network error', async () => { + fetchMock.mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: new Error('unexpected redirect') })); + + const err = await refreshAccessToken({ provider: FORM_PROVIDER, refreshToken: 'rt' }).catch((e) => e); + + expect(lastCall(fetchMock).init.redirect).toBe('error'); + expect(err).toBeInstanceOf(OAuthError); + expect(err.code).toBe('TOKEN_REFRESH_NETWORK_ERROR'); + expect(err.message).toContain('answered with a redirect, which is not followed'); }); }); diff --git a/packages/core/test/unit/utils/log-labels.test.ts b/packages/core/test/unit/utils/log-labels.test.ts new file mode 100644 index 00000000..bfdd770c --- /dev/null +++ b/packages/core/test/unit/utils/log-labels.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest'; + +import { accountIdFor } from '../../../src/utils/id'; +import { + accountLogLabel, + categoryLogLabel, + folderLogLabel, + labelLogLabel, + redactAccountIds, +} from '../../../src/utils/log-labels'; + +const OWNER_ID = accountIdFor('ramesh.sentinel@example.com', 'imap.example.com'); + +describe('accountLogLabel', () => { + // Regression: an account id written as is spells out the owner's address on every line. + it('hides the address an account id is built from', () => { + const label = accountLogLabel(OWNER_ID); + expect(label).toMatch(/^acct#[0-9a-f]{8}$/); + expect(label).not.toContain('sentinel'); + expect(label).not.toContain('example'); + }); + + // Regression: two lines about one account stop reading as the same account (grep breaks). + it('labels the same id the same way every time, and different ids differently', () => { + expect(accountLogLabel(OWNER_ID)).toBe(accountLogLabel(OWNER_ID)); + expect(accountLogLabel(OWNER_ID)).not.toBe(accountLogLabel(accountIdFor('ramesh.sentinel@example.com', 'imap.gmail.com'))); + }); + + // Regression: a missing id throws inside a catch, or prints "undefined" as if it were an id. + it('says none for a missing or non-string id', () => { + expect(accountLogLabel(undefined)).toBe('acct#none'); + expect(accountLogLabel(null)).toBe('acct#none'); + expect(accountLogLabel('')).toBe('acct#none'); + expect(accountLogLabel(42)).toBe('acct#none'); + // A caller where no id means "the active account" says so instead. + expect(accountLogLabel(undefined, 'active')).toBe('active'); + expect(accountLogLabel(OWNER_ID, 'active')).toBe(accountLogLabel(OWNER_ID)); + }); +}); + +describe('redactAccountIds', () => { + // Regression: the release backstop misses an id a call site wrote without labelling it. + it('replaces every account id in a line with its label', () => { + const second = accountIdFor('other.person@example.org', 'mail.example.org'); + const line = `[Backfill] skipping ${OWNER_ID} — churning; next ${second}: ok (db sarvinbox-${OWNER_ID}.db)`; + const out = redactAccountIds(line); + expect(out).not.toContain('sentinel'); + expect(out).not.toContain('other-person'); + expect(out).toContain(accountLogLabel(OWNER_ID)); + expect(out).toContain(accountLogLabel(second)); + expect(out).toContain('[Backfill] skipping '); + }); + + // Regression: the backstop and a labelled call site disagree, so one account reads as two. + it('gives a delimited id the same label the call site would', () => { + expect(redactAccountIds(`acct=${OWNER_ID}, ok`)).toBe(`acct=${accountLogLabel(OWNER_ID)}, ok`); + }); + + // Regression: running the backstop over an already-labelled line mangles it. + it('is idempotent and leaves text without ids alone', () => { + const once = redactAccountIds(`for ${OWNER_ID}`); + expect(redactAccountIds(once)).toBe(once); + expect(redactAccountIds('nothing to see: account 3 of 4')).toBe('nothing to see: account 3 of 4'); + }); + + // Regression: a hostile or huge line stalls the main thread inside the logger. + it('stays linear on a long run of id characters', () => { + const huge = `acct-${'a-'.repeat(200_000)}`; + const started = performance.now(); + const out = redactAccountIds(huge); + expect(performance.now() - started).toBeLessThan(2000); + expect(out).toMatch(/^acct#[0-9a-f]{8}$/); + }); +}); + +describe('folderLogLabel', () => { + // Regression: a user-named folder (a client's or person's name) reaches app.log. + it('hides a folder the user named', () => { + for (const path of ['Clients/Acme Sentinel', 'INBOX/Acme Sentinel', 'INBOX.Acme Sentinel', '[Gmail]/Acme Sentinel', 'Ramesh']) { + const label = folderLogLabel(path); + expect(label).toMatch(/^folder#[0-9a-f]{8}$/); + expect(label).not.toContain('Acme'); + } + }); + + // Regression: system folders turn into hashes and every sync line becomes unreadable. + it('keeps system folders and the app\'s own view ids as written', () => { + for (const path of ['INBOX', 'Inbox', 'Sent Items', 'Junk E-mail', '[Gmail]/All Mail', '[Gmail]/Sent Mail', '[Google Mail]/Bin', 'INBOX.Sent', 'INBOX/Drafts', 'Deleted Items', 'virtual-starred', 'folder-0123456789abcdef', 'section:inbox']) { + expect(folderLogLabel(path)).toBe(path); + } + }); + + // Regression: a long name that happens to start like a system folder is written whole. + it('labels anything over 64 characters, and missing paths as none', () => { + expect(folderLogLabel(`virtual-${'a'.repeat(70)}`)).toMatch(/^folder#/); + expect(folderLogLabel(undefined)).toBe('folder#none'); + expect(folderLogLabel('')).toBe('folder#none'); + }); + + // Regression: two lines about one folder no longer match. + it('is stable per path', () => { + expect(folderLogLabel('Clients/Acme')).toBe(folderLogLabel('Clients/Acme')); + expect(folderLogLabel('Clients/Acme')).not.toBe(folderLogLabel('Clients/Acme2')); + }); +}); + +describe('labelLogLabel / categoryLogLabel', () => { + // Regression: a Gmail label or custom keyword the user typed reaches app.log. + it('hides a user-created label name', () => { + expect(labelLogLabel('Tax 2026 — Ramesh')).toMatch(/^label#[0-9a-f]{8}$/); + expect(labelLogLabel(undefined)).toBe('label#none'); + }); + + // Regression: a custom AI category's name (built from what the user typed) reaches app.log, + // or a built-in one turns into a hash nobody can read. + it('keeps built-in category slugs and hides the user\'s own', () => { + expect(categoryLogLabel('newsletters', true)).toBe('newsletters'); + expect(categoryLogLabel('acme-invoices', false)).toMatch(/^category#[0-9a-f]{8}$/); + const builtIn = new Set(['newsletters', 'spam']); + expect(categoryLogLabel('spam', builtIn)).toBe('spam'); + expect(categoryLogLabel('acme-invoices', builtIn)).toMatch(/^category#/); + expect(categoryLogLabel('', builtIn)).toBe('category#none'); + }); +}); diff --git a/packages/core/test/unit/utils/log-paths.test.ts b/packages/core/test/unit/utils/log-paths.test.ts new file mode 100644 index 00000000..0c25c8c0 --- /dev/null +++ b/packages/core/test/unit/utils/log-paths.test.ts @@ -0,0 +1,60 @@ +import { join, sep } from 'path'; + +import { describe, expect, it } from 'vitest'; + +import { pathForLog, redactHomeDir } from '../../../src/utils/log-paths'; + +const HOME = join(sep, 'Users', 'ramesh'); +const USER_DATA = join(HOME, 'Library', 'Application Support', 'Sarv Inbox'); + +describe('pathForLog', () => { + // Regression: a log line names the user through their home folder (/Users/). + it('writes a data-folder path relative to ', () => { + expect(pathForLog(join(USER_DATA, 'sarvinbox.db'), { userData: USER_DATA, home: HOME })).toBe('/sarvinbox.db'); + expect(pathForLog(join(USER_DATA, 'cache', 'a.bin'), { userData: USER_DATA, home: HOME })).toBe('/cache/a.bin'); + expect(pathForLog(USER_DATA, { userData: USER_DATA, home: HOME })).toBe(''); + }); + + // Regression: a path elsewhere under home still names the user. + it('writes another path under home relative to ~', () => { + expect(pathForLog(join(HOME, 'Downloads', 'x.pdf'), { userData: USER_DATA, home: HOME })).toBe('~/Downloads/x.pdf'); + expect(pathForLog(HOME, { home: HOME })).toBe('~'); + }); + + // Regression: a sibling folder that merely shares the prefix (/Users/rameshx) is treated as home. + it('writes the file name alone for anything outside both, and for relative paths', () => { + expect(pathForLog(join(sep, 'Users', 'rameshx', 'a.db'), { userData: USER_DATA, home: HOME })).toBe('a.db'); + expect(pathForLog(join(sep, 'tmp', 'x', 'y.log'), { home: HOME })).toBe('y.log'); + expect(pathForLog(join('rel', 'z.txt'), { home: HOME })).toBe('z.txt'); + expect(pathForLog(undefined, { home: HOME })).toBe('none'); + }); +}); + +describe('redactHomeDir', () => { + // Regression: the release backstop lets a library's absolute path (updater cache, stack) through. + it('replaces the home folder with ~ wherever it appears', () => { + const line = `downloaded to /Users/ramesh/Library/Caches/u.zip; at file:///Users/ramesh/app/x.js:1`; + expect(redactHomeDir(line, '/Users/ramesh')).toBe('downloaded to ~/Library/Caches/u.zip; at file://~/app/x.js:1'); + expect(redactHomeDir('home is /Users/ramesh', '/Users/ramesh/')).toBe('home is ~'); + }); + + // Regression: a short home rewrites someone else's longer folder name. + it('leaves a longer folder name that starts with home alone', () => { + expect(redactHomeDir('/Users/rameshsarv/x and /Users/ramesh.old', '/Users/ramesh')).toBe('/Users/rameshsarv/x and /Users/ramesh.old'); + }); + + // Regression: Windows paths escape the backstop when printed by util.inspect (doubled \\) or with /. + it('matches a Windows home with single, doubled and forward slashes', () => { + const home = 'C:\\Users\\Ramesh'; + expect(redactHomeDir('at C:\\Users\\Ramesh\\AppData\\x', home)).toBe('at ~\\AppData\\x'); + expect(redactHomeDir("{ path: 'C:\\\\Users\\\\Ramesh\\\\AppData' }", home)).toBe("{ path: '~\\\\AppData' }"); + expect(redactHomeDir('url C:/Users/Ramesh/AppData', home)).toBe('url ~/AppData'); + }); + + // Regression: a misconfigured HOME of "/" replaces every slash in every line. + it('does nothing without a usable home', () => { + expect(redactHomeDir('/a/b', '/')).toBe('/a/b'); + expect(redactHomeDir('/a/b', undefined)).toBe('/a/b'); + expect(redactHomeDir('/a/b', '')).toBe('/a/b'); + }); +}); diff --git a/packages/core/test/unit/utils/telemetry-scrub.test.ts b/packages/core/test/unit/utils/telemetry-scrub.test.ts index b93fc1c5..21c55cfc 100644 --- a/packages/core/test/unit/utils/telemetry-scrub.test.ts +++ b/packages/core/test/unit/utils/telemetry-scrub.test.ts @@ -103,6 +103,74 @@ describe('redactSecrets', () => { }); }); +describe('redactSecrets — the forms it used to miss', () => { + // Breaks if an OAuth token, code or key written WITHOUT quotes (a URL, a form + // body, a library's message) reaches app.log or a crash report. + it.each([ + ['https://oauth2.example.com/token?access_token=ya29.SECRET1&x=1', 'ya29.SECRET1'], + ['grant_type=refresh_token&refresh_token=1//SECRET2&client_id=abc', '1//SECRET2'], + ['client_secret=SECRET3&code_verifier=SECRET4', 'SECRET3'], + ['client_secret=SECRET3&code_verifier=SECRET4', 'SECRET4'], + ['http://127.0.0.1:53682/callback?code=4/0SECRET5&state=STATE6', '4/0SECRET5'], + ['http://127.0.0.1:53682/callback?code=4/0SECRET5&state=STATE6', 'STATE6'], + ['https://generativelanguage.googleapis.com/v1/models?key=AIzaSECRET7', 'AIzaSECRET7'], + ['login failed: password: hunter2SECRET8 rejected', 'hunter2SECRET8'], + ['Authorization: Basic dXNlcjpTRUNSRVQ5', 'dXNlcjpTRUNSRVQ5'], + ['authorization=Digest SECRET10', 'SECRET10'], + ['token=SECRET11; path=/', 'SECRET11'], + ])('redacts the unquoted value in %s', (input, secret) => { + expect(redactSecrets(input)).not.toContain(secret); + expect(redactSecrets(input)).toContain('[REDACTED]'); + }); + + // Breaks if key material or a PKCE verifier written as a config field leaks. + it.each(['code_verifier', 'codeVerifier', 'secretKey', 'secret_key', 'privateKey', 'private-key', 'passphrase', 'client_assertion'])( + 'redacts the quoted %s field', + (key) => { + expect(redactSecrets(`{"${key}":"leak-me"}`)).toBe(`{"${key}":"[REDACTED]"}`); + expect(redactSecrets(`{ ${key}: 'leak-me' }`)).toBe(`{ ${key}: '[REDACTED]' }`); + }, + ); + + // Breaks if a provider's error body logged inside an object (JSON within a + // JSON string, so every quote is escaped) carries its token out. + it('redacts credentials in escaped, nested JSON', () => { + const once = '{"body":"{\\"access_token\\":\\"ya29.NESTED1\\",\\"expires_in\\":3599}"}'; + const out = redactSecrets(once); + expect(out).not.toContain('NESTED1'); + expect(out).toContain('\\"expires_in\\":3599'); + const twice = '"{\\\\\\"refresh_token\\\\\\":\\\\\\"1//NESTED2\\\\\\"}"'; + expect(redactSecrets(twice)).not.toContain('NESTED2'); + // A slash some encoders escape stays inside the value, so the rest of it is redacted too. + expect(redactSecrets('{\\"id_token\\":\\"abc\\/NESTED3\\"}')).not.toContain('NESTED3'); + }); + + // Breaks if the wider rules eat the words our own lines write in place of a + // secret, or an error code, making app.log useless for triage. + it('keeps placeholders, error codes and ordinary words', () => { + const text = 'mirror token=yes isGmail=true; token: no; password: set; { name: \'Error\', code: \'ETIMEDOUT\' } exit code=1 bypass=2 prompt_tokens=120'; + expect(redactSecrets(text)).toBe(text); + expect(redactSecrets('Authorization: Bearer abc.def')).toBe('Authorization: Bearer [REDACTED]'); + }); + + // Breaks if a hostile line (a server's message, a long header) stalls the + // main thread in the logger: every line of the app passes through here. + it('stays linear on long adversarial input', () => { + const inputs = [ + `\\"password\\":\\"${'\\'.repeat(100_000)}`, + `password=${'a'.repeat(200_000)}`, + `${'password: '.repeat(20_000)}x`, + `?code=${'&code='.repeat(20_000)}`, + `authorization: basic ${' '.repeat(100_000)}x`, + ]; + for (const input of inputs) { + const started = performance.now(); + redactSecrets(input); + expect(performance.now() - started).toBeLessThan(2000); + } + }); +}); + describe('stripUrlQuery', () => { // Gemini puts the API key in ?key=; search URLs carry queries and addresses. it('drops the query string and fragment and redacts addresses in the path', () => { @@ -140,6 +208,31 @@ describe('scrubBreadcrumb', () => { expect(crumb.message).toBe('moveToSpam for x@y.com'); // input not mutated }); + // Breaks if a fetch/XHR breadcrumb ships the query string Sentry keeps beside + // the URL it already cut (`http.query`: API keys, OAuth codes, search words), + // which the privacy policy says is stripped. + it('drops http.query and http.fragment, which hold a URL query of their own', () => { + const crumb = { + category: 'fetch', + data: { + method: 'GET', + url: 'https://generativelanguage.googleapis.com/v1/models', + 'http.query': '?key=AIzaSECRET&q=invoice%20acme', + 'http.fragment': '#access_token=ya29.SECRET', + status_code: 200, + nested: { query: 'from:boss@example.com', query_string: 'a=b' }, + }, + }; + const out = scrubBreadcrumb(crumb); + expect(out.data).toEqual({ + method: 'GET', + url: 'https://generativelanguage.googleapis.com/v1/models', + status_code: 200, + nested: {}, + }); + expect(JSON.stringify(out)).not.toContain('SECRET'); + }); + it('passes through a breadcrumb with no message or data', () => { expect(scrubBreadcrumb({ category: 'ui' } as { category: string })).toEqual({ category: 'ui' }); }); @@ -266,6 +359,16 @@ describe('scrubEvent — the whole event, addresses AND secrets', () => { }); }); +describe('scrubText — account ids', () => { + // Breaks if a log-line breadcrumb carries an account id (acct-- + // --) to Sentry, spelling out the owner's address. + it('replaces account ids with their label', () => { + const out = scrubText('[Backfill] skipping acct-jane-doe-example-com--imap-example-com — churning'); + expect(out).not.toContain('jane-doe'); + expect(out).toMatch(/skipping acct#[0-9a-f]{8} — churning/); + }); +}); + describe('scrubText', () => { // The one text redaction a crash report gets — both policies, in one call. it('redacts secrets and addresses together', () => { diff --git a/packages/storage-node/src/repositories/ai-repository.ts b/packages/storage-node/src/repositories/ai-repository.ts index 90f4d42d..a80da804 100644 --- a/packages/storage-node/src/repositories/ai-repository.ts +++ b/packages/storage-node/src/repositories/ai-repository.ts @@ -2,7 +2,7 @@ // All category queries use instr(tags, '|slug|') — zero JOINs, no junction tables import type { EmailRecord } from '@sarvinbox/core'; -import { automaticCategorizationDeferred, GMAIL_NON_AUTHORITATIVE_CATEGORY_SLUGS, createLogger, existingCategoryClassification, independentImportance, isSpamProtectedEmail, parseCategorySelection } from '@sarvinbox/core'; +import { automaticCategorizationDeferred, categoryLogLabel, GMAIL_NON_AUTHORITATIVE_CATEGORY_SLUGS, createLogger, existingCategoryClassification, independentImportance, isSpamProtectedEmail, parseCategorySelection } from '@sarvinbox/core'; import type { EmailAICategory, @@ -444,7 +444,8 @@ export class AIRepository extends BaseRepository { ): Promise { const limit = options.limit || 50; const offset = options.offset || 0; - logger.info(`[AIRepo] getEmailsByDynamicCategory(category=${categorySlug}, limit=${limit}, offset=${offset}, folderId=${options.folderId || 'all'})`); + // A slug can be made from a name the user typed: logged as its label. + logger.info(`[AIRepo] getEmailsByDynamicCategory(category=${categoryLogLabel(categorySlug, categorySlug === 'uncategorized')}, limit=${limit}, offset=${offset}, folderId=${options.folderId || 'all'})`); if (categorySlug === 'uncategorized') { // Category membership is independent of processing state: never-attempted, diff --git a/packages/storage-node/src/repositories/folder-repository.ts b/packages/storage-node/src/repositories/folder-repository.ts index 5158edd6..f5503636 100644 --- a/packages/storage-node/src/repositories/folder-repository.ts +++ b/packages/storage-node/src/repositories/folder-repository.ts @@ -1,7 +1,7 @@ // Folder Repository - All folder-related database operations import type { FolderRecord } from '@sarvinbox/core'; -import { addTag, removeTag, parseTags, buildTags, tagsToImapFlags, imapFlagsToTags, FLAG_TAG_NAMES, createLogger } from '@sarvinbox/core'; +import { addTag, removeTag, parseTags, buildTags, tagsToImapFlags, imapFlagsToTags, FLAG_TAG_NAMES, createLogger, folderLogLabel } from '@sarvinbox/core'; import type { Statement } from 'better-sqlite3'; import { BaseRepository, type DatabaseAccessor } from './base-repository'; @@ -255,7 +255,7 @@ export class FolderRepository extends BaseRepository { }); move(rows); - logger.info(`Re-filed ${rows.length} local-only row(s) from ${from.path} to ${to.path}`); + logger.info(`Re-filed ${rows.length} local-only row(s) from ${folderLogLabel(from.path)} to ${folderLogLabel(to.path)}`); return rows.length; } diff --git a/packages/storage-node/src/repositories/thread-sql.ts b/packages/storage-node/src/repositories/thread-sql.ts index 21a95726..f389f985 100644 --- a/packages/storage-node/src/repositories/thread-sql.ts +++ b/packages/storage-node/src/repositories/thread-sql.ts @@ -11,6 +11,7 @@ import { STANDARD_DRAFT_FOLDERS, conversationFoldersOf, createLogger, + errorDiagnostic, type ConversationFolders, } from '@sarvinbox/core'; import type Database from 'better-sqlite3'; @@ -57,12 +58,12 @@ export function conversationFoldersIn(db: Database.Database): ConversationFolder rows = prepared(db, 'SELECT * FROM folders').all() as typeof rows; } catch (error) { if (NO_FOLDERS_TABLE.test(String((error as Error)?.message ?? error))) return conversationFoldersOf([]); - log.warn('conversationFoldersIn: folders table unreadable; refusing to guess the Drafts/Sent folders', error); + log.warn('conversationFoldersIn: folders table unreadable; refusing to guess the Drafts/Sent folders', errorDiagnostic(error)); throw error; } if (rows.length > 0 && typeof rows[0].path !== 'string') { const error = new Error('conversationFoldersIn: folders rows carry no path'); - log.warn('conversationFoldersIn: folders table unreadable; refusing to guess the Drafts/Sent folders', error); + log.warn('conversationFoldersIn: folders table unreadable; refusing to guess the Drafts/Sent folders', errorDiagnostic(error)); throw error; } return conversationFoldersOf(rows.map((row) => ({ diff --git a/packages/storage-node/src/shared-contacts.ts b/packages/storage-node/src/shared-contacts.ts index d0a30dc8..859a2a8e 100644 --- a/packages/storage-node/src/shared-contacts.ts +++ b/packages/storage-node/src/shared-contacts.ts @@ -31,10 +31,11 @@ * per-account adoption pass (see `migrations.ts`, `unified_contact_directory`) * only ever merges rows INTO the directory. */ +import { basename } from 'path'; + import { createLogger } from '@sarvinbox/core'; import type Database from 'better-sqlite3'; - import { encryptPlaintextDb, isExistingPlaintextDb, pinDbCipher } from './db-encryption'; const log = createLogger('SharedContacts'); @@ -258,7 +259,7 @@ export function attachSharedContacts( if (legacyPlaintext) { // WAL is restored below. encryptPlaintextDb(db, key!, SHARED_SCHEMA); - log.info(`[SharedContacts] migrated plaintext directory to encrypted: ${path}`); + log.info(`[SharedContacts] migrated plaintext directory to encrypted: ${basename(path)}`); } // Every CREATE here is schema-qualified and IF NOT EXISTS: applying the @@ -288,5 +289,5 @@ export function attachSharedContacts( // briefly instead of throwing SQLITE_BUSY at whichever account wrote second. db.pragma('busy_timeout = 5000'); - log.info(`[SharedContacts] attached ${path} (${probe.n} contacts)`); + log.info(`[SharedContacts] attached ${basename(path)} (${probe.n} contacts)`); } diff --git a/packages/storage-node/src/sqlite-storage.ts b/packages/storage-node/src/sqlite-storage.ts index 56d2beb5..9138df72 100644 --- a/packages/storage-node/src/sqlite-storage.ts +++ b/packages/storage-node/src/sqlite-storage.ts @@ -3,7 +3,6 @@ import { basename, dirname, join } from 'path'; - import type { IEmailStorage, EmailRecord, @@ -30,8 +29,10 @@ import type { } from '@sarvinbox/core'; import { bareSenderAddress, + categoryLogLabel, parseAddresses, createLogger, + errorDiagnostic, firstMemberKeyOf, isSameFirstSplitKey, isSpamScore, @@ -291,7 +292,7 @@ export class SQLiteStorage implements IEmailStorage { if (this.config.key) { if (legacyPlaintext) { encryptPlaintextDb(this.db, this.config.key); - log.info(`[SQLiteStorage] Migrated plaintext DB to encrypted: ${this.config.dbPath}`); + log.info(`[SQLiteStorage] Migrated plaintext DB to encrypted: ${basename(this.config.dbPath)}`); } else { applyDbKey(this.db, this.config.key); } @@ -2720,7 +2721,7 @@ export class SQLiteStorage implements IEmailStorage { enqueueThreadsTaggedWith(this.db, slug); this.readModel?.schedule(); } catch (error) { - log.warn(`[Storage] Failed to enqueue threads for category '${slug}':`, error); + log.warn(`[Storage] Failed to enqueue threads for category ${categoryLogLabel(slug, false)}:`, errorDiagnostic(error)); } } diff --git a/packages/storage-node/test/unit/log-privacy.test.ts b/packages/storage-node/test/unit/log-privacy.test.ts new file mode 100644 index 00000000..df113882 --- /dev/null +++ b/packages/storage-node/test/unit/log-privacy.test.ts @@ -0,0 +1,85 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { folderLogLabel, getLogLevel, setLogLevel, setLogSink } from '@sarvinbox/core'; +import type Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { captureLogs, type CapturedLogs } from '../../../core/src/test-support/log-capture'; +import { FolderRepository } from '../../src/repositories/folder-repository'; +import { conversationFoldersIn } from '../../src/repositories/thread-sql'; +import { attachSharedContacts } from '../../src/shared-contacts'; +import { openTestDb } from '../../src/test-support/test-db'; + +/** + * What the storage layer writes to app.log about the user's own names: a + * folder they named, where their data folder is. What breaks if this file + * fails: a release app.log (attached to bug reports, sampled into crash + * reports) names a client's folder or the user's home folder. + */ + +let logs: CapturedLogs; +const open: Database.Database[] = []; +let dir = ''; + +beforeEach(() => { + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); + dir = mkdtempSync(join(tmpdir(), 'storage-log-privacy-')); +}); + +afterEach(() => { + logs.stop(); + for (const db of open.splice(0)) db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe('FolderRepository.refileLocalRows', () => { + // Breaks: 'Re-filed N local-only row(s) from to ' wrote a + // user-named folder; a system one (Sent) must stay readable. + it('names a user folder by its label and a system folder as written', async () => { + const db = openTestDb(); + open.push(db); + db.exec(` + CREATE TABLE folders (id TEXT PRIMARY KEY, path TEXT UNIQUE NOT NULL); + CREATE TABLE emails (id TEXT PRIMARY KEY, folder_id TEXT NOT NULL, uid INTEGER, tags TEXT NOT NULL DEFAULT '||'); + INSERT INTO folders (id, path) VALUES ('f-user', 'Clients/Sentinel Acme Sent'), ('f-sent', 'Sent'); + INSERT INTO emails (id, folder_id, uid, tags) VALUES ('m1', 'f-user', 0, '|Clients/Sentinel Acme Sent|'); + `); + + expect(await new FolderRepository(() => db).refileLocalRows('f-user', 'f-sent')).toBe(1); + + expect(logs.containing('Sentinel')).toEqual([]); + expect(logs.containing(`Re-filed 1 local-only row(s) from ${folderLogLabel('Clients/Sentinel Acme Sent')} to Sent`)).toHaveLength(1); + }); +}); + +describe('attachSharedContacts', () => { + // Breaks: '[SharedContacts] attached ' wrote the directory's absolute + // path, which names the user through their home folder. + it('names the directory by its file name only', () => { + const db = openTestDb(); + open.push(db); + + attachSharedContacts(db, join(dir, 'sarvinbox-contacts.db')); + + expect(logs.containing(dir)).toEqual([]); + expect(logs.containing('[SharedContacts] attached sarvinbox-contacts.db (0 contacts)')).toHaveLength(1); + }); +}); + +describe('conversationFoldersIn', () => { + // Breaks: the "folders table unreadable" warning logged the whole error, + // whose message can quote the statement or a folder's name; it still throws. + it('logs an unreadable folders table by the error kind and code only', () => { + const db = { + prepare: () => { throw Object.assign(new Error('malformed near "Clients/Sentinel Acme"'), { code: 'SQLITE_CORRUPT' }); }, + } as unknown as Database.Database; + + expect(() => conversationFoldersIn(db)).toThrow(/malformed/); + + expect(logs.containing('Sentinel')).toEqual([]); + const [line] = logs.containing('folders table unreadable'); + expect(line).toContain("code: 'SQLITE_CORRUPT'"); + }); +}); From c9855650332d5184b629af6f238a7e38327bbbc3 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Mon, 23 Nov 2026 18:46:32 +0530 Subject: [PATCH 5/8] fix(sync): mark a folder caught up only after its new mail is downloaded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FolderSyncer.syncFolder saved the server's UIDNEXT before fetching anything. Later syncs read that value to skip a folder as unchanged, and the periodic background sync always does. So one failed fetch (a timeout, a dropped connection) left the folder looking up to date: every later sync skipped it, and the new mail stayed on the server until something else arrived there. - The message count is still written up front (the list counter and "load more" read it). UIDNEXT is written only after a pass that downloaded everything up to it. - A failed pass clears the saved UIDNEXT, so the next sync checks the folder again. Clearing, rather than keeping the older value, also covers a pass that failed while syncing flags or deletions. - A full sync with a failed batch counts as incomplete. - fetchNewestMessagesWindowed reports `interrupted` when a lower batch fails after newer mail arrived, and that pass counts as incomplete too. - A flags-only pass downloads no new mail, so it leaves the value alone. - A pass that stops at its message or time limit still counts as caught up: the drain job fills the rest. Marking it incomplete would re-download the same newest mail on every sync. skip-unchanged-after-failure.test.ts covers, against the fake IMAP server: - a one-off failure and a repeating one; - a recovery that inserts nothing twice; - a failed full-sync batch; - an interrupted fetch; - a flags-only pass; - two accounts; - the reset write itself failing. All 8 fail with the old folder-syncer.ts. incremental-fetch.test.ts covers the `interrupted` flag. CHANGELOG [Unreleased] → Fixed has the entry. Pre-existing test changed on purpose: folder-name-log-privacy.test.ts re-ran the sync with skipUnchanged forced off to get around this bug. It now uses the default sync, which picks the folder up again. --- CHANGELOG.md | 9 + packages/core/src/imap/folder-syncer.ts | 89 ++++++- packages/core/src/imap/incremental-fetch.ts | 11 +- .../unit/imap/folder-name-log-privacy.test.ts | 9 +- .../test/unit/imap/incremental-fetch.test.ts | 28 ++ .../imap/skip-unchanged-after-failure.test.ts | 242 ++++++++++++++++++ 6 files changed, 371 insertions(+), 17 deletions(-) create mode 100644 packages/core/test/unit/imap/skip-unchanged-after-failure.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 898d0eb2..f850dd98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **New mail no longer stops arriving in a folder after one failed sync.** If + fetching a folder's new mail failed once (a timeout, a dropped connection, a + busy server), the app still noted the folder as up to date, and the regular + background sync then skipped it as unchanged. The missed mail stayed on the + server until something else arrived in that folder or you refreshed it by + hand. A folder is now noted as up to date only once its new mail has really + been downloaded, so the next sync picks up what the failed one missed. + ### Security - **The log file no longer names your accounts, folders or user folder.** Every line about an account carried its internal id, which spells out the diff --git a/packages/core/src/imap/folder-syncer.ts b/packages/core/src/imap/folder-syncer.ts index 174b0444..5a3740a4 100644 --- a/packages/core/src/imap/folder-syncer.ts +++ b/packages/core/src/imap/folder-syncer.ts @@ -59,6 +59,14 @@ export interface FolderSyncResult { uidValidityChanged: boolean; } +/** + * What one strategy pass (full or incremental) reports to `syncFolder`. + * `complete: false` means it ran but did not fetch everything the server + * offered up to the UIDNEXT seen at the start (a full sync whose batches + * failed), so the folder must not be recorded as caught up. + */ +type PassResult = Partial & { complete?: boolean }; + /** * Folder priority for sync ordering */ @@ -269,6 +277,8 @@ export class FolderSyncer { uidValidityChanged: false, }; + // Set once the stored folder is known, so a failure can mark it unsynced. + let storedFolderId: string | null = null; try { // Select folder and get status const boxStatus = await client.selectFolder(folder.path); @@ -280,6 +290,8 @@ export class FolderSyncer { return result; } + storedFolderId = storedFolder.id; + // Check UIDVALIDITY result.uidValidityChanged = await this.handleUidValidity( storedFolder, @@ -334,13 +346,25 @@ export class FolderSyncer { }); } - // Update folder with server counts (for "load more" feature) - // Don't overwrite totalCount — it will be recalculated from local DB after sync + // How many messages the server holds, for the list counter and "load + // more" (it is the folder's serverMessageCount). Written now: it is true + // whatever this pass manages to fetch. Don't overwrite totalCount — it is + // recalculated from the local DB after the sync. + // + // NOT the UIDNEXT. That one is the skip-unchanged key (`hasChanges`): + // recording it says "everything below this has been fetched". It used to + // be written here, BEFORE the fetch, so a fetch that then failed (a + // timeout, a dropped connection) left the folder looking caught up, and + // every later sync with skipUnchanged — the periodic one included — + // skipped it as unchanged. The new mail stayed on the server until + // something else arrived. It is written below, once the pass is done. await storage.updateFolder(storedFolder.id, { lastKnownMessageCount: boxStatus.messages, - lastKnownUidnext: boxStatus.uidNext, } as any); + // Whether this pass fetched everything up to boxStatus.uidNext. + let caughtUp = true; + // Determine sync strategy if (opts.flagsOnly && storedFolder.lastSyncUid) { // Flags-only sync — force deletion reconciliation (see incrementalSync). @@ -362,6 +386,9 @@ export class FolderSyncer { result.flagsUpdated = flagsResult.updated; result.deletedCount = flagsResult.deleted; result.success = true; + // Flags only: no new mail was fetched, so the folder is not caught up + // to this UIDNEXT (and keeps whatever key the last fetching pass left). + caughtUp = false; } else if (opts.fullSync || !storedFolder.lastSyncUid || result.uidValidityChanged || needsRecoverySync) { // Full sync (also triggered when local count is too low) const fullResult = await this.fullSync( @@ -373,7 +400,7 @@ export class FolderSyncer { onProgress, touch, ); - this.mergeResults(result, fullResult); + caughtUp = this.mergePass(result, fullResult); } else { // Incremental sync const incrementalResult = await this.incrementalSync( @@ -385,23 +412,54 @@ export class FolderSyncer { onProgress, touch, ); - this.mergeResults(result, incrementalResult); + caughtUp = this.mergePass(result, incrementalResult); } - // Update sync time + // Update sync time, and record the UIDNEXT as the skip-unchanged key + // only when this pass fetched up to it. A pass that did not (failed + // batches, flags only) leaves the key alone or clears it, so the next + // sync looks at the folder again instead of skipping it. await storage.updateFolder(storedFolder.id, { lastSyncTime: Math.floor(Date.now() / 1000), - }); + ...(caughtUp ? { lastKnownUidnext: boxStatus.uidNext } : opts.flagsOnly ? {} : { lastKnownUidnext: null }), + } as any); result.success = true; return result; } catch (error) { logger.error(`Failed to sync folder ${folderLogLabel(folder.path)}:`, errorDiagnostic(error)); result.error = error as Error; + await this.markNotCaughtUp(storage, storedFolderId, folder.path); return result; } } + /** + * After a failed pass: clear the folder's recorded UIDNEXT, so the next + * sync's skip-unchanged check (`hasChanges`) treats it as changed and fetches + * what this pass did not. Leaving the key an earlier pass recorded is not + * enough: when no mail arrived since, it still matches the server, and the + * message count (written at the start of this pass) matches too, so a pass + * that failed in its flag or deletion reconcile would be skipped all the + * same. A cleared key is what a never-synced folder has. Best-effort: if + * storage is what failed, this write fails too and nothing is worse. + */ + private async markNotCaughtUp(storage: IEmailStorage, folderId: string | null, path: string): Promise { + if (!folderId) return; + try { + await storage.updateFolder(folderId, { lastKnownUidnext: null } as any); + } catch (error) { + logger.warn(`Could not mark ${folderLogLabel(path)} for a re-check after a failed sync: ${failureCause(error)}`); + } + } + + /** Merge a strategy pass into the result; answers whether it caught up. */ + private mergePass(target: FolderSyncResult, pass: PassResult): boolean { + const { complete, ...rest } = pass; + this.mergeResults(target, rest); + return complete !== false; + } + /** * Handle UIDVALIDITY changes */ @@ -468,7 +526,7 @@ export class FolderSyncer { options: FolderSyncOptions, onProgress?: (processed: number, total: number) => void, touch?: () => void, - ): Promise> { + ): Promise { if (boxStatus.messages === 0) { return { success: true, @@ -559,6 +617,9 @@ export class FolderSyncer { messagesInserted: inserted, messagesUpdated: updated, lastSyncUid: maxUid > 0 ? maxUid : null, + // A failed batch is mail the server has and we do not: the next sync + // must look again rather than skip the folder as unchanged. + complete: failedBatches === 0, }; } @@ -573,7 +634,7 @@ export class FolderSyncer { options: FolderSyncOptions, onProgress?: (processed: number, total: number) => void, touch?: () => void, - ): Promise> { + ): Promise { const lastUID = folder.lastSyncUid || 0; // Log the watermark WITH the two server numbers that decide whether the "no @@ -630,7 +691,7 @@ export class FolderSyncer { // the oldest end drained steadily. The helper also drops any UID <= lastUID // (some servers echo the boundary message for an out-of-range low bound) so // lastSyncUid can never regress into a permanent redundant refetch loop. - const { messages, scannedDownToUid } = await withFolderSelected(client, folder.path, () => + const { messages, scannedDownToUid, interrupted } = await withFolderSelected(client, folder.path, () => fetchNewestMessagesWindowed(client, lastUID, boxStatus.uidNext, { fetchHeaders: true, fetchBody: !options.headersOnly, @@ -640,6 +701,12 @@ export class FolderSyncer { // True when the cap stopped the pass before it reached the watermark, so // unfetched UIDs remain BELOW the newest message we just took. const gapRemainsBelow = scannedDownToUid > lastUID + 1; + // A window FAILED (not the cap or the time budget): the hole is a transient + // miss, so the folder is not caught up and the next sync must not skip it. + // A capped pass still counts as caught up — closing that hole is the + // drain's job (SyncEngine.drainFolderChunk), and re-running this pass every + // cycle would only re-download the same newest messages. + const complete = interrupted !== true; if (messages.length === 0) { // Handle sent folder edge case @@ -653,6 +720,7 @@ export class FolderSyncer { flagsUpdated: flagsResult.updated, deletedCount: flagsResult.deleted, lastSyncUid: lastUID, + complete, }; } @@ -698,6 +766,7 @@ export class FolderSyncer { flagsUpdated: flagsResult.updated, deletedCount: flagsResult.deleted, lastSyncUid: nextSyncUid, + complete, }; } diff --git a/packages/core/src/imap/incremental-fetch.ts b/packages/core/src/imap/incremental-fetch.ts index 1e70b3d5..2c6df216 100644 --- a/packages/core/src/imap/incremental-fetch.ts +++ b/packages/core/src/imap/incremental-fetch.ts @@ -223,6 +223,13 @@ export interface NewestFirstFetch { * forever. */ scannedDownToUid: number; + /** + * True when the pass stopped because a window FAILED (after earlier ones + * succeeded), not on its cap or time budget. The hole below is then a + * transient miss that the next pass should retry, so the caller must not + * record the folder as caught up. + */ + interrupted?: boolean; } /** @@ -267,6 +274,7 @@ export async function fetchNewestMessagesWindowed( const maxMessages = windowOptions?.maxMessages; const collected: IMAPMessage[] = []; let scannedDownToUid = hiEnd + 1; + let interrupted = false; for (let hi = hiEnd; hi > sinceUid;) { const span = run.span(); @@ -282,6 +290,7 @@ export async function fetchNewestMessagesWindowed( // `scannedDownToUid` tells the caller a hole remains below it. if (scannedDownToUid > hiEnd) throw error; keepPartial(collected.length, error); + interrupted = true; break; } for (const m of window) { @@ -295,5 +304,5 @@ export async function fetchNewestMessagesWindowed( } collected.sort((a, b) => a.uid - b.uid); - return { messages: collected, scannedDownToUid }; + return { messages: collected, scannedDownToUid, ...(interrupted ? { interrupted } : {}) }; } diff --git a/packages/core/test/unit/imap/folder-name-log-privacy.test.ts b/packages/core/test/unit/imap/folder-name-log-privacy.test.ts index 20c8411b..7e86974c 100644 --- a/packages/core/test/unit/imap/folder-name-log-privacy.test.ts +++ b/packages/core/test/unit/imap/folder-name-log-privacy.test.ts @@ -157,12 +157,9 @@ describe('SyncEngine — a user-named folder never reaches app.log', () => { vi.spyOn(server, 'fetchMessagesByUidRange').mockRejectedValueOnce(serverError('FETCH_ERROR')); await engine.syncAll(); // the failing pass - // The re-run is forced (skipUnchanged off) on purpose. With the default the - // folder is skipped as "unchanged": syncFolder records the server's - // EXISTS/UIDNEXT before the fetch that failed, so nothing looks new. That is - // a separate, known sync gap (raised, not fixed here); this test is about - // what the lines say, not about when the mail lands. - await engine.syncAll({ skipUnchanged: false }); + // The default re-run (skipUnchanged): a failed pass leaves the folder to be + // checked again (see skip-unchanged-after-failure.test.ts). + await engine.syncAll(); expect(db.rowsTaggedWith(FOLDER)).toHaveLength(4); expect(leaks(logs)).toEqual([]); diff --git a/packages/core/test/unit/imap/incremental-fetch.test.ts b/packages/core/test/unit/imap/incremental-fetch.test.ts index e0be2111..a7b2dcfc 100644 --- a/packages/core/test/unit/imap/incremental-fetch.test.ts +++ b/packages/core/test/unit/imap/incremental-fetch.test.ts @@ -182,6 +182,34 @@ describe('fetchNewestMessagesWindowed', () => { expect(out.scannedDownToUid).toBe(4); // sinceUid + 1 => nothing left behind }); + // The caller must tell a FAILED window (a transient miss the next pass should + // retry, so the folder is not caught up) from the cap or the budget stopping + // the pass (the drain's job). Without the flag both read as "a hole below", + // and the folder was recorded as caught up after a failure. + it('reports interrupted when a window fails after newer ones arrived, and not otherwise', async () => { + const { client } = rangeClient(range(1, 1200)); + let calls = 0; + const flaky = { + async fetchMessagesByUidRange(lo: number, hi: number) { + calls += 1; + if (calls === 2) throw new Error('IMAP FETCH timed out'); + return client.fetchMessagesByUidRange!(lo, hi); + }, + } as unknown as IIMAPClient; + + const failed = await fetchNewestMessagesWindowed(flaky, 0, 1201, undefined, { windowSize: 500 }); + expect(failed.interrupted).toBe(true); + expect(failed.scannedDownToUid).toBe(701); + expect(failed.messages).toHaveLength(500); + + const capped = await fetchNewestMessagesWindowed(client, 0, 1201, undefined, { windowSize: 500, maxMessages: 500 }); + expect(capped.scannedDownToUid).toBe(701); + expect(capped.interrupted).toBeUndefined(); + + const whole = await fetchNewestMessagesWindowed(client, 0, 1201, undefined, { windowSize: 500 }); + expect(whole.interrupted).toBeUndefined(); + }); + // Minimal fakes without bounded ranges still work; the unbounded fetch covers // the whole range, so it must report no hole. it('falls back to getNewMessages and reports no hole', async () => { diff --git a/packages/core/test/unit/imap/skip-unchanged-after-failure.test.ts b/packages/core/test/unit/imap/skip-unchanged-after-failure.test.ts new file mode 100644 index 00000000..4e818307 --- /dev/null +++ b/packages/core/test/unit/imap/skip-unchanged-after-failure.test.ts @@ -0,0 +1,242 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { SyncEngine } from '../../../src/imap/sync-engine'; +import { FakeEmailStorage, resetFakeStorageIds } from '../../../src/test-support/fake-email-storage'; +import { FakeImapServer, resetFakeMessageIds } from '../../../src/test-support/fake-imap-server'; +import { captureLogs, type CapturedLogs } from '../../../src/test-support/log-capture'; +import { IMAPError, type IMAPFolder } from '../../../src/types/imap'; +import { folderLogLabel } from '../../../src/utils/log-labels'; +import { getLogLevel, setLogLevel, setLogSink } from '../../../src/utils/logger'; + +/** + * A folder recorded as caught up only when it is. + * + * Every default sync (the periodic one included) runs with skipUnchanged: a + * folder whose server STATUS (UIDVALIDITY, EXISTS, UIDNEXT) matches what the + * last sync recorded is skipped. The UIDNEXT used to be recorded at the START + * of a folder's sync, before the fetch. A fetch that then failed — a timeout, a + * dropped connection, a busy server — left the folder looking caught up, so + * every later sync skipped it and the new mail stayed on the server until + * something else changed there. Nothing reported an error after the first + * pass: mail just quietly stopped arriving. + * + * What breaks if this file fails: mail that a failed or partial pass missed is + * not fetched by the next sync; or a folder that IS caught up is synced again + * on every pass (the skip stops working). + */ + +const FOLDER = 'Projects'; +const LABEL = folderLogLabel(FOLDER); + +const imapFolder = (path: string): IMAPFolder => ({ + name: path, path, delimiter: '/', specialUse: null, subscribed: true, selectable: true, children: [], +}); + +const timeout = () => Object.assign(new Error('IMAP FETCH timed out'), { code: 'ETIMEDOUT' }); +const refused = () => new IMAPError('Command failed: BAD Invalid messageset', 'FETCH_ERROR', 'Invalid messageset', 'UID FETCH', 'BAD'); + +let logs: CapturedLogs; +beforeEach(() => { + resetFakeMessageIds(); + resetFakeStorageIds(); + logs = captureLogs({ setLogSink, setLogLevel, getLogLevel }); +}); +afterEach(() => { + logs.stop(); + vi.restoreAllMocks(); +}); + +/** One account: a fake server with INBOX and FOLDER, and an engine wired to it. */ +function account(host = 'imap.example.com') { + const server = new FakeImapServer({ condstore: true, host }); + server.addFolder('INBOX', { uidValidity: 1 }); + server.addFolder(FOLDER, { uidValidity: 7 }); + const db = new FakeEmailStorage(); + db.addFolder('INBOX', { uidValidity: 1 }); + db.addFolder(FOLDER, { uidValidity: 7 }); + const engine = new SyncEngine(db.asStorage()); + vi.spyOn(engine, 'isConnected').mockReturnValue(true); + const internals = engine as unknown as { + connectionManager: { _client: unknown; ensureConnection: () => Promise }; + reselectMonitoredFolder: () => Promise; + }; + internals.connectionManager._client = server; + internals.connectionManager.ensureConnection = async () => true; + internals.reselectMonitoredFolder = async () => {}; + vi.spyOn(server, 'listFolders').mockResolvedValue([imapFolder('INBOX'), imapFolder(FOLDER)]); + const add = (count: number) => server.addMessages(FOLDER, count, { subject: 'Status', from: 'sender@example.org', to: ['me@example.com'] }); + const rows = () => db.rowsTaggedWith(FOLDER).length; + return { server, db, engine, add, rows }; +} + +/** How many of `logs` say FOLDER was skipped as unchanged. */ +const skipped = (): number => logs.containing(`Skipping unchanged: ${LABEL}`).length; + +describe('a failed incremental fetch', () => { + // THE bug: a transient failure of the incremental fetch, then the next + // default sync skipped the folder as unchanged and the mail never landed. + it('leaves the folder to be fetched by the next default sync (transient failure)', async () => { + const a = account(); + a.add(2); + await a.engine.syncAll(); + a.add(2); + vi.spyOn(a.server, 'fetchMessagesByUidRange').mockRejectedValueOnce(timeout()); + + await a.engine.syncAll(); // fails + expect(a.rows()).toBe(2); + await a.engine.syncAll(); // the default: skipUnchanged + + expect(a.rows()).toBe(4); + expect(skipped()).toBe(0); + }); + + // A failure that repeats (the server refuses the command every time) is + // retried on every sync, not skipped silently after the first; when it + // clears, the mail lands and the folder is skipped again from then on. + it('retries a repeating (permanent) failure on every sync until it clears', async () => { + const a = account(); + a.add(2); + await a.engine.syncAll(); + a.add(1); + const fetch = vi.spyOn(a.server, 'fetchMessagesByUidRange').mockRejectedValue(refused()); + + await a.engine.syncAll(); + await a.engine.syncAll(); + expect(logs.containing(`Failed to sync folder ${LABEL}`)).toHaveLength(2); + expect(skipped()).toBe(0); + + fetch.mockRestore(); + await a.engine.syncAll(); + expect(a.rows()).toBe(3); + await a.engine.syncAll(); + expect(skipped()).toBe(1); + }); + + // Idempotent re-run: the recovery pass does not insert anything twice, and + // a folder that is caught up is still skipped (the skip is what keeps a + // quiet poll cheap). + it('inserts nothing twice on recovery, and skips a caught-up folder', async () => { + const a = account(); + a.add(3); + await a.engine.syncAll(); + await a.engine.syncAll(); + expect(skipped()).toBe(1); + + a.add(2); + vi.spyOn(a.server, 'fetchMessagesByUidRange').mockRejectedValueOnce(timeout()); + await a.engine.syncAll(); + await a.engine.syncAll(); + await a.engine.syncAll(); + + expect(a.rows()).toBe(5); + expect(new Set(a.db.rowsTaggedWith(FOLDER).map((row) => row.uid)).size).toBe(5); + expect(skipped()).toBe(2); + }); +}); + +describe('a partial pass', () => { + // Partial run: a full sync whose only batch failed used to record the + // folder as caught up, so it stayed empty until new mail arrived. + it('re-checks a folder whose full-sync batch failed', async () => { + const a = account(); + a.add(3); + vi.spyOn(a.server, 'fetchMessages').mockRejectedValueOnce(timeout()); + + await a.engine.syncAll(); + expect(a.rows()).toBe(0); + expect(logs.containing(`Full sync ${LABEL}: batch`).join('\n')).toContain('failed: ETIMEDOUT; continuing'); + await a.engine.syncAll(); + + expect(a.rows()).toBe(3); + }); + + // Partial run: an incremental fetch whose lower window failed after the + // newer one arrived keeps what arrived and holds the watermark below the + // hole — and must also leave the folder for the next sync to finish. + it('finishes an incremental fetch that was interrupted between windows', async () => { + const a = account(); + a.add(2); + await a.engine.syncAll(); + // New UIDs 3..102 with a run expunged from the middle: more than one paced + // window (64 UIDs) apart, while the server still holds only 20 messages + // (more would trip the low-local-count recovery into a full sync instead). + const uids = a.add(100); + for (const uid of uids.slice(9, 91)) a.server.expungeOnServer(FOLDER, uid); + const real = a.server.fetchMessagesByUidRange.bind(a.server); + let calls = 0; + vi.spyOn(a.server, 'fetchMessagesByUidRange').mockImplementation(async (lo, hi, options) => { + calls += 1; + if (calls === 2) throw timeout(); // the newer window arrived; the older one fails + return real(lo, hi, options); + }); + + await a.engine.syncAll(); + expect(a.rows()).toBe(2 + 9); + expect(logs.containing('New-mail fetch stopped early').join('\n')).toContain('ETIMEDOUT'); + await a.engine.syncAll(); + + expect(a.rows()).toBe(20); + expect(skipped()).toBe(0); + }); + + // A flags-only pass fetches no new mail, so it must not record the folder + // as caught up to a UIDNEXT whose messages it never fetched. + it('does not let a flags-only pass hide new mail from the next sync', async () => { + const a = account(); + a.add(2); + await a.engine.syncAll(); + a.add(2); + + await a.engine.syncAll({ flagsOnly: true }); + expect(a.rows()).toBe(2); + await a.engine.syncAll(); + + expect(a.rows()).toBe(4); + }); +}); + +describe('two accounts', () => { + // Multi-account: one account's failure leaves only ITS folder for a re-check; + // the other account, caught up, keeps being skipped. + it('re-checks only the account whose fetch failed', async () => { + const a = account('imap.a.example'); + const b = account('imap.b.example'); + a.add(1); + b.add(1); + await Promise.all([a.engine.syncAll(), b.engine.syncAll()]); + a.add(2); + vi.spyOn(a.server, 'fetchMessagesByUidRange').mockRejectedValueOnce(timeout()); + + await Promise.all([a.engine.syncAll(), b.engine.syncAll()]); + await Promise.all([a.engine.syncAll(), b.engine.syncAll()]); + + expect(a.rows()).toBe(3); + expect(b.rows()).toBe(1); + // b was skipped on both later passes; a on neither. + expect(skipped()).toBe(2); + }); +}); + +describe('when the bookkeeping write itself fails', () => { + // A failed sync whose "re-check this folder" write also fails (storage is + // what broke) is logged by its kind and does not throw out of the sync. + it('logs the failed write and still reports the folder as failed', async () => { + const a = account(); + a.add(2); + await a.engine.syncAll(); + a.add(1); + vi.spyOn(a.server, 'fetchMessagesByUidRange').mockRejectedValueOnce(timeout()); + const update = a.db.updateFolder.bind(a.db); + vi.spyOn(a.db, 'updateFolder').mockImplementation(async (id, updates) => { + if ('lastKnownUidnext' in updates && (updates as { lastKnownUidnext: unknown }).lastKnownUidnext === null) { + throw Object.assign(new Error('database is locked'), { code: 'SQLITE_BUSY' }); + } + return update(id, updates); + }); + + await expect(a.engine.syncAll()).resolves.not.toThrow(); + + expect(logs.containing(`Could not mark ${LABEL} for a re-check after a failed sync: SQLITE_BUSY`)).toHaveLength(1); + expect(logs.containing(`Failed to sync folder ${LABEL}`)).toHaveLength(1); + }); +}); From 30d6d818e872bf941b0696bf4167e997c8839a96 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Tue, 24 Nov 2026 21:47:10 +0530 Subject: [PATCH 6/8] fix(search): pick the page before reading any email in full A search built the whole record of every match before ORDER BY ... LIMIT threw all but one page away. In the full-text path that meant, for every match, its body through email_bodies and the search index's own stored copy of its text: the join named emails_fts.email_id, and fts5 can only hand out a stored column by loading that row's whole stored text, decrypted page by page. A common word matches thousands of messages, so on a real mailbox one 61-row search for "meeting" froze the main process for 25 seconds, and an Inbox Agent question that ran 48 such searches hung the app for 219 seconds (2026-11-24, seen in app.log and a stack sample: sqlite3_step -> fts5ColumnMethod -> ChaCha20 page decryption). Search now chooses its page from narrow rows (rowid, date, sort key, score) and hydrates only the page's members. The index joins emails by rowid, which it already holds equal to the emails rowid (the rowid contract from migration 84); count, the doesntHave exclusion and the conversation search join the same way. The LIKE fallback shares the same page query. Ties now break on date, then rowid, so a page boundary is the same row every time. Measured on the same mailbox and question: 219 s -> 44 s for the whole answer, longest freeze 32 s -> 1.9 s. Tests: bodies read only for the page (a counting view over email_bodies, by date, relevance, exclusion, filter-only and the LIKE fallback); the join uses the rowid, not the stored email_id; paging through equal dates neither repeats nor skips; page order and relevance scores survive the split; VACUUM keeps the index's rowids on their own emails. Five of these fail on the old code; the filter-only and fallback cases already deferred their reads there and guard the shared page query. --- CHANGELOG.md | 8 + packages/storage-node/src/fts-schema.ts | 5 + .../src/repositories/search-repository.ts | 175 +++++++++--------- .../storage-node/test/unit/fts-rowid.test.ts | 23 +++ .../repositories/search-repository.test.ts | 106 +++++++++++ 5 files changed, 233 insertions(+), 84 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de28a82d..6c1722cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **Searching for a common word no longer freezes the app.** A search used to + read the full text of every email that matched before showing the first + page, so a word found in thousands of emails (such as "meeting") could stop + the whole app for half a minute, and an Inbox Agent question that ran many + searches could hang it for minutes. Search now picks the page of results + first and reads only those emails. + ## [1.4.12] - 2026-11-24 ### Fixed diff --git a/packages/storage-node/src/fts-schema.ts b/packages/storage-node/src/fts-schema.ts index c9d37327..509347c0 100644 --- a/packages/storage-node/src/fts-schema.ts +++ b/packages/storage-node/src/fts-schema.ts @@ -44,6 +44,11 @@ * * `rowid` is fts5's own primary key, so addressing by it plans as * `INDEX 0:=` — a seek. Keep every statement here keyed that way. + * + * Searches rely on it too: search-repository.ts joins matches to `emails` by + * rowid (`FTS_JOIN`), because reading the stored `email_id` loads that row's + * whole stored text. A row whose rowids disagree is a search that returns the + * wrong email, so fts-rowid.test.ts also pins that VACUUM keeps them equal. */ export const FTS_TABLE_DDL = ` CREATE VIRTUAL TABLE IF NOT EXISTS emails_fts USING fts5( diff --git a/packages/storage-node/src/repositories/search-repository.ts b/packages/storage-node/src/repositories/search-repository.ts index ea84897a..645ede02 100644 --- a/packages/storage-node/src/repositories/search-repository.ts +++ b/packages/storage-node/src/repositories/search-repository.ts @@ -21,6 +21,20 @@ const SEARCH_SORT_COLUMNS = new Set([ // Match the renderer's threadId || id grouping, including legacy empty keys. const SEARCH_THREAD_KEY = `COALESCE(NULLIF(emails.thread_id, ''), emails.id)`; +/** + * How a search index row reaches its email: by rowid, which the index holds + * equal to the `emails` rowid it mirrors (the ROWID CONTRACT in fts-schema.ts). + * + * Never through the stored `email_id` column. fts5 cannot hand out a stored + * column without loading that row's whole stored text — subject, addresses and + * the full body, decrypted page by page — so a join on it read the complete + * text of EVERY match just to learn its id. Reading the rowid reads nothing. + */ +const FTS_JOIN = 'emails.rowid = emails_fts.rowid'; + +// bm25 weights: email_id(0) > subject(10) > from_address(5) > from_name(3) > to(3) > cc(2) > attachments(2) > body(1) +const FTS_RELEVANCE = 'bm25(emails_fts, 0, 10, 5, 3, 3, 2, 2, 1)'; + /** * Repository for FTS5-powered search */ @@ -149,38 +163,55 @@ export class SearchRepository extends BaseRepository { search(query: SearchQuery): EmailRecord[] { if (query.collapseThreads) return this.searchThreads(query); const textQuery = query.query?.trim(); - const useFTS = textQuery && textQuery.length > 0; - - let sql: string; - const params: any[] = []; + const ftsQuery = textQuery ? this.escapeFTSQuery(textQuery) : ''; + // FTS query was empty after escaping, fall back to LIKE + if (textQuery && !ftsQuery) return this.searchWithLike(query); + try { + return this.searchPage(query, { ftsQuery }); + } catch (error) { + logger.error('[SearchRepo] FTS search failed, falling back to LIKE:', error); + return this.searchWithLike(query); + } + } + /** + * One page of matching messages, chosen BEFORE any of them is read in full. + * + * The page is picked from narrow rows (rowid, date, sort key, score) and only + * its members are then hydrated (bodies, calendar data, thread metadata). + * Selecting the whole record and letting `ORDER BY … LIMIT` trim it instead + * made SQLite build every column of EVERY match before sorting: a body read + * through `email_bodies`, and in the FTS path also each match's stored copy of + * its own text, decrypted page by page. A common word ("meeting") matches + * thousands of messages, so one 61-row search of a real mailbox froze the main + * process for 25 seconds (2026-11-24, an Inbox Agent question that ran 48 + * such searches). Choosing the page first reads the bodies of 61, not 6,000. + */ + private searchPage(query: SearchQuery, match: { ftsQuery?: string; likeOnly?: boolean }): EmailRecord[] { + const params: unknown[] = []; + const useFTS = !!match.ftsQuery; + let from = 'FROM emails WHERE 1=1'; if (useFTS) { - const ftsQuery = this.escapeFTSQuery(textQuery); - - if (!ftsQuery) { - // FTS query was empty after escaping, fall back to LIKE - return this.searchWithLike(query); - } - - // bm25 weights: email_id(0) > subject(10) > from_address(5) > from_name(3) > to(3) > cc(2) > attachments(2) > body(1) - sql = ` - SELECT ${this.emailSelect('emails', query.headersOnly)}, ${this.threadMeta()}, - bm25(emails_fts, 0, 10, 5, 3, 3, 2, 2, 1) as relevance_score - FROM emails_fts - JOIN emails ON emails.id = emails_fts.email_id - WHERE emails_fts MATCH ? - `; - params.push(ftsQuery); - } else { - sql = `SELECT ${this.emailSelect('emails', query.headersOnly)}, ${this.threadMeta()} FROM emails WHERE 1=1`; + from = `FROM emails_fts JOIN emails ON ${FTS_JOIN} WHERE emails_fts MATCH ?`; + params.push(match.ftsQuery); } - // All folder/category/field/date/size filters (shared with count()). - sql += this.appendFilters(query, params); + from += this.appendFilters(query, params, { likeOnly: match.likeOnly }); + const text = query.query?.trim(); + if (match.likeOnly && text) { + // Free-text search over the same fields FTS indexes (subject, body, sender, + // cc, attachment names) so a fallback result set looks like an FTS one. + from += ` AND (emails.subject LIKE ? ESCAPE '\\' OR ${cleanBodyExpression()} LIKE ? ESCAPE '\\' OR emails.from_name LIKE ? ESCAPE '\\'` + + ` OR emails.from_address LIKE ? ESCAPE '\\' OR emails.cc_address LIKE ? ESCAPE '\\' OR emails.attachment_names LIKE ? ESCAPE '\\')`; + const like = this.likeContains(text); + params.push(like, like, like, like, like, like); + } // Sorting const sortBy = query.sortBy || 'date'; - if (useFTS && (sortBy === 'relevance' || sortBy === 'date')) { + let key: string; + let direction: 'ASC' | 'DESC'; + if (useFTS && sortBy === 'relevance') { // For relevance sort, blend the field-weighted bm25 score with lightweight // importance signals — a local-client take on Gmail's LTR re-rank // (Score = relevance + importance − time-decay), minus the neural net. @@ -188,41 +219,45 @@ export class SearchRepository extends BaseRepository { // starred/important/unread matches UP without ever overriding a much stronger // keyword match. Recency is only a TIE-BREAKER (never demotes a better match, // so a "W2 2023"-style navigational search still surfaces the old mail). - if (sortBy === 'relevance') { - sql += ` - ORDER BY ( - relevance_score + key = `${FTS_RELEVANCE} - (CASE WHEN instr(emails.tags, '|starred|') > 0 THEN 4.0 ELSE 0 END) - (CASE WHEN instr(emails.tags, '|important|') > 0 THEN 2.0 ELSE 0 END) - - (CASE WHEN instr(emails.tags, '|read|') = 0 THEN 1.0 ELSE 0 END) - ) ASC, emails.date DESC`; - } else { - sql += ` ORDER BY emails.date DESC`; - } + - (CASE WHEN instr(emails.tags, '|read|') = 0 THEN 1.0 ELSE 0 END)`; + direction = 'ASC'; + } else if (useFTS && sortBy === 'date') { + key = 'emails.date'; + direction = 'DESC'; } else { - const { column, direction } = this.safeOrderBy(sortBy, query.sortOrder, SEARCH_SORT_COLUMNS, 'date'); - sql += ` ORDER BY emails.${column} ${direction}`; - } - + const safe = this.safeOrderBy(sortBy, query.sortOrder, SEARCH_SORT_COLUMNS, 'date'); + key = `emails.${safe.column}`; + direction = safe.direction; + } + // Ties break on recency, then on rowid, so the page boundary is the same + // row every time and the hydrating query can restore the exact order. On a + // date sort, (date, rowid) is the order of the date index itself. + const order = (prefix: string) => key === 'emails.date' + ? `${prefix}search_key ${direction}, ${prefix}search_rowid ${direction}` + : `${prefix}search_key ${direction}, ${prefix}search_date DESC, ${prefix}search_rowid DESC`; + + let page = `SELECT emails.rowid AS search_rowid, emails.date AS search_date, ${key} AS search_key` + + `${useFTS ? `, ${FTS_RELEVANCE} AS relevance_score` : ''} ${from} ORDER BY ${order('')}`; // OFFSET without LIMIT is a SQLite syntax error, so an offset-only query threw // instead of paging. -1 is SQLite's "no limit". if (query.limit || query.offset) { - sql += ` LIMIT ?`; + page += ` LIMIT ?`; params.push(query.limit ?? -1); } - if (query.offset) { - sql += ` OFFSET ?`; + page += ` OFFSET ?`; params.push(query.offset); } - try { - const rows = this.db.prepare(sql).all(...params) as any[]; - return rows.map(row => this.rowToRecord(row)); - } catch (error) { - logger.error('[SearchRepo] FTS search failed, falling back to LIKE:', error); - return this.searchWithLike(query); - } + const sql = `WITH search_hits AS MATERIALIZED (${page}) + SELECT ${this.emailSelect('emails', query.headersOnly)}, ${this.threadMeta()}${useFTS ? ', search_hits.relevance_score' : ''} + FROM search_hits JOIN emails ON emails.rowid = search_hits.search_rowid + ORDER BY ${order('search_hits.')}`; + const rows = this.db.prepare(sql).all(...params) as unknown[]; + return rows.map(row => this.rowToRecord(row)); } /** Select a page of matching conversation keys before hydrating its members. @@ -237,7 +272,7 @@ export class SearchRepository extends BaseRepository { const { column, direction } = this.safeOrderBy(query.sortBy, query.sortOrder, SEARCH_SORT_COLUMNS, 'date'); let from = 'FROM emails WHERE 1=1'; if (useFTS) { - from = 'FROM emails_fts JOIN emails ON emails.id = emails_fts.email_id WHERE emails_fts MATCH ?'; + from = `FROM emails_fts JOIN emails ON ${FTS_JOIN} WHERE emails_fts MATCH ?`; params.push(ftsQuery); } from += this.appendFilters(query, params, { likeOnly }); @@ -248,7 +283,7 @@ export class SearchRepository extends BaseRepository { params.push(match, match, match, match, match, match); } - const relevance = useFTS ? 'bm25(emails_fts, 0, 10, 5, 3, 3, 2, 2, 1)' : '0'; + const relevance = useFTS ? FTS_RELEVANCE : '0'; const relevanceSort = useFTS && query.sortBy === 'relevance'; const rank = relevanceSort ? `${relevance} - (CASE WHEN instr(emails.tags, '|starred|') > 0 THEN 4.0 ELSE 0 END) @@ -469,8 +504,10 @@ export class SearchRepository extends BaseRepository { } else { const negFts = this.escapeFTSQuery(query.doesntHave); if (negFts) { - sql += ` AND emails.id NOT IN ( - SELECT email_id FROM emails_fts WHERE emails_fts MATCH ? + // By rowid, as FTS_JOIN explains: naming the stored email_id here + // read the whole text of every message carrying the excluded word. + sql += ` AND emails.rowid NOT IN ( + SELECT rowid FROM emails_fts WHERE emails_fts MATCH ? )`; params.push(negFts); } @@ -513,7 +550,7 @@ export class SearchRepository extends BaseRepository { if (useFTS) { const ftsQuery = this.escapeFTSQuery(textQuery!); if (!ftsQuery) return this.countLike(query); - sql = `SELECT ${counted} as cnt FROM emails_fts JOIN emails ON emails.id = emails_fts.email_id WHERE emails_fts MATCH ?`; + sql = `SELECT ${counted} as cnt FROM emails_fts JOIN emails ON ${FTS_JOIN} WHERE emails_fts MATCH ?`; params.push(ftsQuery); } else { sql = `SELECT ${counted} as cnt FROM emails WHERE 1=1`; @@ -544,37 +581,7 @@ export class SearchRepository extends BaseRepository { */ private searchWithLike(query: SearchQuery): EmailRecord[] { if (query.collapseThreads) return this.searchThreads(query, true); - let sql = `SELECT ${this.emailSelect('emails', query.headersOnly)}, ${this.threadMeta()} FROM emails WHERE 1=1`; - const params: any[] = []; - - sql += this.appendFilters(query, params, { likeOnly: true }); - - // Free-text search over the same fields FTS indexes (subject, body, sender, - // cc, attachment names) so a fallback result set looks like an FTS one. - if (query.query?.trim()) { - sql += ` AND (emails.subject LIKE ? ESCAPE '\\' OR ${cleanBodyExpression()} LIKE ? ESCAPE '\\' OR emails.from_name LIKE ? ESCAPE '\\'` - + ` OR emails.from_address LIKE ? ESCAPE '\\' OR emails.cc_address LIKE ? ESCAPE '\\' OR emails.attachment_names LIKE ? ESCAPE '\\')`; - const q = this.likeContains(query.query.trim()); - params.push(q, q, q, q, q, q); - } - - const { column, direction } = this.safeOrderBy(query.sortBy, query.sortOrder, SEARCH_SORT_COLUMNS, 'date'); - sql += ` ORDER BY emails.${column} ${direction}`; - - // OFFSET without LIMIT is a SQLite syntax error, so an offset-only query threw - // instead of paging. -1 is SQLite's "no limit". - if (query.limit || query.offset) { - sql += ` LIMIT ?`; - params.push(query.limit ?? -1); - } - - if (query.offset) { - sql += ` OFFSET ?`; - params.push(query.offset); - } - - const rows = this.db.prepare(sql).all(...params) as any[]; - return rows.map(row => this.rowToRecord(row)); + return this.searchPage(query, { likeOnly: true }); } /** diff --git a/packages/storage-node/test/unit/fts-rowid.test.ts b/packages/storage-node/test/unit/fts-rowid.test.ts index 072acfbf..9f663d80 100644 --- a/packages/storage-node/test/unit/fts-rowid.test.ts +++ b/packages/storage-node/test/unit/fts-rowid.test.ts @@ -271,3 +271,26 @@ describe('migration v84 — fts_rowid_alignment', () => { } finally { db.close(); } }); }); + +describe('FTS rowid contract across VACUUM', () => { + // Breaks: search joins the index to `emails` by rowid, and so do the delete + // and update triggers. SQLite documents that VACUUM "may change the ROWIDs" + // of a table without an INTEGER PRIMARY KEY, which `emails` is. If the + // bundled SQLite ever did, the database compaction (db-compact.worker.ts runs + // VACUUM) would make every search return the wrong messages and every + // delete remove the wrong entry. This pins that it keeps them. + it('keeps every index row on its own email after deletes leave gaps and VACUUM runs', () => { + const db = newDb(); + try { + for (let index = 0; index < 60; index++) addEmail(db, `e${index}`, `Subject ${index}`, `body word${index}`); + db.prepare("DELETE FROM emails WHERE CAST(SUBSTR(id, 2) AS INTEGER) % 3 = 0").run(); + db.exec('VACUUM'); + const misaligned = db.prepare(`SELECT COUNT(*) AS n FROM emails JOIN emails_fts ON emails_fts.rowid = emails.rowid + WHERE emails_fts.email_id != emails.id`).get() as { n: number }; + expect(misaligned.n).toBe(0); + expect(indexSize(db)).toBe(40); + expect((db.prepare(`SELECT emails.id FROM emails_fts JOIN emails ON emails.rowid = emails_fts.rowid + WHERE emails_fts MATCH 'word7'`).all() as { id: string }[]).map(row => row.id)).toEqual(['e7']); + } finally { db.close(); } + }); +}); diff --git a/packages/storage-node/test/unit/repositories/search-repository.test.ts b/packages/storage-node/test/unit/repositories/search-repository.test.ts index 5b8b0b43..22a8104f 100644 --- a/packages/storage-node/test/unit/repositories/search-repository.test.ts +++ b/packages/storage-node/test/unit/repositories/search-repository.test.ts @@ -1074,6 +1074,112 @@ describe('SearchRepository', () => { }); }); + // ── reading only what a page needs ───────────────────────────────────────── + // A search used to build the WHOLE record of every match (body, and in the + // FTS path the index's own stored copy of each match's text) before + // `ORDER BY … LIMIT` threw all but one page away. On a real encrypted + // mailbox, a 61-row search for "meeting" froze the main process for 25 + // seconds, and an Inbox Agent question that ran 48 of them hung the app for + // over three minutes (2026-11-24). + describe('reading only what a page needs', () => { + /** Ids whose body was read, through a view that shadows email_bodies. */ + function countBodyReads(): Set { + const read = new Set(); + db.function('test_body_read', { deterministic: false }, (id: unknown, value: unknown) => { read.add(String(id)); return value; }); + db.exec(`CREATE TEMP VIEW email_bodies AS SELECT email_id, + test_body_read(email_id, clean_body) AS clean_body, test_body_read(email_id, raw_body) AS raw_body FROM main.email_bodies`); + return read; + } + + /** `count` messages that all match "meeting", with bodies in email_bodies. */ + function addMeetings(count: number, date = (index: number) => 10_000 + index): void { + for (let index = 0; index < count; index++) { + const id = `m${String(index).padStart(3, '0')}`; + addEmail(db, { id, subject: `Weekly sync ${index}`, body: '', tags: '|INBOX|', date: date(index) }); + db.prepare('INSERT INTO email_bodies (email_id, clean_body, raw_body) VALUES (?, ?, ?)') + .run(id, `Agenda for the meeting, item ${index}`, `

Agenda for the meeting, item ${index}

`); + } + } + + // Breaks: every search reads the body of every match before keeping one + // page, so a common word freezes the app for as long as the mailbox is big. + // The text searches did exactly that before. On the filter-only and LIKE + // paths SQLite already put the reads off until after the sort; those cases + // are here because the three paths now share one page query. + it.each([ + ['a text search by date', { query: 'meeting' }], + ['a text search by relevance', { query: 'meeting', sortBy: 'relevance' }], + ['a text search with an exclusion', { query: 'meeting', doesntHave: 'lunch' }], + ['a filter-only search by subject', { query: '', sortBy: 'subject', sortOrder: 'asc' }], + ['the LIKE fallback', { query: 'meeting' }, true], + ] as Array<[string, SearchQuery, boolean?]>)('reads the bodies of the page only: %s', (_name, query, withoutIndex) => { + addMeetings(40); + if (withoutIndex) breakFtsIndex(db); + const read = countBodyReads(); + const page = repo.search({ ...query, limit: 5 }); + expect(page).toHaveLength(5); + // The LIKE fallback has to read bodies to match them; it still must not + // read them a second time to build rows it then throws away. + if (!withoutIndex) expect([...read].sort()).toEqual(ids(page).filter(id => id.startsWith('m')).sort()); + }); + + // Breaks: the fallback hydrates every match, which the test above cannot + // see because matching itself reads every body. Hydrating reads raw_body, + // which matching never touches. (Guards the shared page query; the old + // fallback did not do this.) + it('builds full rows for the page only, in the LIKE fallback too', () => { + addMeetings(40); + breakFtsIndex(db); + const raw = new Set(); + db.function('test_raw_read', { deterministic: false }, (id: unknown, value: unknown) => { raw.add(String(id)); return value; }); + db.exec(`CREATE TEMP VIEW email_bodies AS SELECT email_id, clean_body, test_raw_read(email_id, raw_body) AS raw_body FROM main.email_bodies`); + const page = repo.search({ query: 'meeting', limit: 5 }); + expect([...raw].sort()).toEqual(ids(page).sort()); + }); + + // Breaks: the search reaches its email through the index's stored copy + // of the id, which fts5 can only hand out by loading that row's whole + // stored text (subject, addresses and full body). Joining on the rowid + // reads none of it. A wrong stored copy proves which one the join uses. + it('reaches each email through the index rowid, never its stored email_id', () => { + db.prepare("UPDATE emails_fts SET email_id = 'not-an-email' WHERE rowid = (SELECT rowid FROM emails WHERE id = 'e1')").run(); + expect(sortedIds(repo.search({ query: 'invoice' }))).toEqual(['e1', 'e5']); + expect(sortedIds(repo.search({ query: 'invoice', collapseThreads: true }))).toEqual(['e1', 'e5']); + expect(repo.count({ query: 'invoice' })).toBe(2); + expect(ids(repo.search({ query: '', doesntHave: 'acme' }))).not.toContain('e1'); + }); + + // Breaks: a page boundary that falls among messages with the same date + // repeats one message on two pages and never shows another. + it('pages through messages with equal dates without repeating or skipping one', () => { + addMeetings(23, () => 10_000); + for (const query of [{ query: 'meeting' }, { query: '', sortBy: 'subject' as const }, { query: 'meeting', sortBy: 'relevance' as const }]) { + const whole = ids(repo.search(query)); + const paged = [0, 1, 2, 3, 4, 5].flatMap(index => ids(repo.search({ ...query, limit: 5, offset: index * 5 }))); + expect(paged).toEqual(whole); + expect(new Set(paged).size).toBe(paged.length); + } + }); + + // Breaks: the page query and the query that builds its rows disagree on + // order, so a search shows the right messages in the wrong order. + it('returns the page in the order it was chosen in', () => { + addMeetings(12, index => 10_000 + (index % 4)); + const expected = [...Array(12).keys()].map(index => ({ id: `m${String(index).padStart(3, '0')}`, date: 10_000 + (index % 4) })) + .sort((a, b) => b.date - a.date || b.id.localeCompare(a.id)).map(item => item.id); + expect(ids(repo.search({ query: 'meeting' }))).toEqual(expected); + expect(ids(repo.search({ query: 'meeting', limit: 4, offset: 2 }))).toEqual(expected.slice(2, 6)); + }); + + // Breaks: relevance scores stop reaching the caller once rows are built + // apart from the query that ranked them. + it('still carries each match its relevance score', () => { + const rows = repo.search({ query: 'invoice' }); + expect(rows.every(row => typeof row.relevanceScore === 'number')).toBe(true); + expect(repo.search({ query: '' }).every(row => row.relevanceScore === undefined)).toBe(true); + }); + }); + it('throws Storage not initialized when the DB is not ready yet', () => { const detached = new SearchRepository(() => undefined as unknown as Database.Database, rowToRecord); expect(() => detached.search({ query: '' })).toThrow('Storage not initialized'); From 300e021efbf27086f6d1badd14967b8c28d26ad3 Mon Sep 17 00:00:00 2001 From: Ramesh Choudhary Date: Tue, 24 Nov 2026 21:49:22 +0530 Subject: [PATCH 7/8] fix(shortcuts): keep keyboard shortcuts working after a click in a mail body A mail body renders in a sandboxed iframe (the standard reader and every chat-view bubble), which is a document of its own. Clicking in it, a link above all, made that frame the focused frame, and Chromium then delivered every keydown to the frame's document. The shortcut listeners are on the app's document, so j/k, e, #, / and Escape went dead until the user clicked outside the body. Returning from the browser a link opened in did not help: the window-focus restore leaves an already-focused element alone, and the frame is that element. Keydowns in a frame that runs no script (sandboxed without allow-scripts, i.e. the mail bodies) are now replayed on the iframe element in the app's document, attached when focus enters the frame (window blur with the frame active) and re-attached when the frame loads a new document. If an app listener handles the replay, the original is prevented too. Focus stays in the frame, so copying a selection there keeps working; keys typed into a field in the mail and IME composition are not forwarded; extension panels (which run script) are left alone. No sandbox or CSP change. The shortcut hook now uses the shared, realm-agnostic typing-target check, and its go-to console.log lines move to the shared logger without the key. --- CHANGELOG.md | 9 + .../desktop/src/hooks/useKeyboardShortcuts.ts | 18 +- apps/desktop/src/main.tsx | 5 + .../desktop/src/utils/frame-key-forwarding.ts | 119 ++++++++ .../src/utils/frame-key-forwarding.test.tsx | 258 ++++++++++++++++++ 5 files changed, 398 insertions(+), 11 deletions(-) create mode 100644 apps/desktop/src/utils/frame-key-forwarding.ts create mode 100644 apps/desktop/test/unit/src/utils/frame-key-forwarding.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index de28a82d..5f5a5dd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **Keyboard shortcuts keep working after you click inside a message.** + Clicking a link in an email (or anywhere in its text) moved the keyboard into + the message, and every shortcut — next and previous mail, archive, delete, + search, Escape — stopped responding until you clicked somewhere outside it. + Shortcuts now work straight away, in the standard view and in chat view, + while copying text you selected in the message and typing into a field in it + work as before. + ## [1.4.12] - 2026-11-24 ### Fixed diff --git a/apps/desktop/src/hooks/useKeyboardShortcuts.ts b/apps/desktop/src/hooks/useKeyboardShortcuts.ts index 5cb59935..429576f1 100644 --- a/apps/desktop/src/hooks/useKeyboardShortcuts.ts +++ b/apps/desktop/src/hooks/useKeyboardShortcuts.ts @@ -1,5 +1,6 @@ import type { EmailRecord } from '@sarvinbox/core'; import { conversationFoldersOf, latestConversationMember } from '@sarvinbox/core/conversation-membership'; +import { createLogger } from '@sarvinbox/core/logger'; import { useEffect, useRef } from 'react'; import type { AppSection } from '../components/AppSidebar'; @@ -11,6 +12,7 @@ import { type GotoTarget, } from '../config/keyboard-shortcuts'; import { useEmailStore } from '../store/email-store'; +import { isTypingTarget } from '../utils/frame-key-forwarding'; import { conversationStarToggle } from '../utils/thread-utils'; interface UseKeyboardShortcutsOptions { @@ -20,6 +22,8 @@ interface UseKeyboardShortcutsOptions { allowListNavigation?: boolean; } +const log = createLogger('Shortcuts'); + // Next/prev-email navigation always opens a different thread and thus triggers // a thread load + IMAP body fetch. OS key-repeat (holding the arrow) is // swallowed for these so a held key can't flood the connection pool; discrete @@ -42,14 +46,6 @@ function isKeyboardShortcutsEnabled(): boolean { return true; } -function isTypingTarget(el: EventTarget | null): boolean { - if (!el || !(el instanceof HTMLElement)) return false; - const tag = el.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true; - if (el.isContentEditable) return true; - return false; -} - function getActiveEmailId(): string | null { const state = useEmailStore.getState(); return state.selectedEmailId || state.highlightedEmailId; @@ -147,10 +143,10 @@ export function useKeyboardShortcuts({ setActiveSection, focusSearch, enabled = waitingForGotoRef.current = true; if (gotoTimerRef.current) clearTimeout(gotoTimerRef.current); gotoTimerRef.current = setTimeout(() => { - console.log('[Shortcuts] Go-to mode timed out'); + log.debug('Go-to mode timed out'); waitingForGotoRef.current = false; }, GOTO_TIMEOUT_MS); - console.log('[Shortcuts] Go-to mode activated — press target key within 1s'); + log.debug('Go-to mode activated — press target key within 1s'); e.preventDefault(); return; } @@ -165,7 +161,7 @@ export function useKeyboardShortcuts({ setActiveSection, focusSearch, enabled = const gotoRecord = getEffectiveGotoRecord(); const target: GotoTarget | undefined = gotoRecord[e.key]; - console.log('[Shortcuts] Go-to key:', e.key, '→ target:', target || '(no match)'); + log.debug(`Go-to key resolved: ${target ? 'matched' : 'no match'}`); if (target) { e.preventDefault(); handleGoto(target); diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx index 9ebffe64..4ae57fb0 100644 --- a/apps/desktop/src/main.tsx +++ b/apps/desktop/src/main.tsx @@ -16,6 +16,7 @@ import { AttachmentTransferProvider } from './components/attachment-viewer/Attac import { SentryErrorBoundary } from './components/SentryErrorBoundary'; import { initSentryRenderer } from './sentry'; import { useEmailStore } from './store/email-store'; +import { installFrameKeyForwarding } from './utils/frame-key-forwarding'; import './index.css'; // The chat view's own stylesheet, then the bridge that repoints its `--sec-*` // tokens at this app's theme. Order matters: the bridge must win over the @@ -31,6 +32,10 @@ initSentryRenderer(); // render, or the app shows one frame of the default light theme and then flips. initAppearance(); +// Keyboard shortcuts must survive a click inside a mail body's sandboxed frame +// (which takes keyboard focus away from this document). See the module header. +installFrameKeyForwarding(); + createRoot(document.getElementById('root')!).render( diff --git a/apps/desktop/src/utils/frame-key-forwarding.ts b/apps/desktop/src/utils/frame-key-forwarding.ts new file mode 100644 index 00000000..6ca32292 --- /dev/null +++ b/apps/desktop/src/utils/frame-key-forwarding.ts @@ -0,0 +1,119 @@ +/** + * Keyboard shortcuts keep working after a click inside a mail body. + * + * A mail body renders in a sandboxed `