diff --git a/.gitignore b/.gitignore index bf3d0ce7..14d48caf 100644 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,7 @@ apps/desktop/build/* # reconstructed; see its header. !apps/desktop/build/afterPack.js !apps/desktop/build/keychain-helper.js +!apps/desktop/build/mac-helper-names.js !apps/desktop/build/beforeBuild.js !apps/desktop/build/entitlements.mac.plist !apps/desktop/build/default-apps.nsh diff --git a/CHANGELOG.md b/CHANGELOG.md index 96774ff2..003e1801 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,175 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **"Filter messages like this" works.** On an email's menu it used to say the + feature was coming; it now opens Settings → Filters with a new filter for + that sender, ready to save. +- **Filters can keep the AI away from the mail they match.** A new **Skip AI + checks** option on each filter stops the AI from sorting matching emails + into categories, scoring their priority, judging them as spam, acting on them + or drafting replies to them. It is ticked for every new filter, including + one made with "Filter messages like this", and can be unticked. Filters you + already have are unchanged until you tick it. A filter can do only this, and + Inbox Agent can set it up when you ask. +- **Make a label without leaving a filter.** A filter's "Apply label" action + now offers **Create new label**, which opens the New label window and picks + the label you make, so you no longer have to go to Settings → Labels and come + back. +- **Security → Attachment scanning.** While an antivirus scanner extension is + turned on, the Security page has a tab for it. It shows whether scanning is + set up, the scanner's address, which accounts it may scan, and whether its + sign-in is kept in the system keychain or only until you quit (and when the + saved one is locked). **Test connection** asks the scanner, with your saved + setup, whether it still answers and accepts your sign-in, and says which + ClamAV version it runs and how old its virus definitions are, or why not; it + changes nothing. **Set up scanning** (or **Sign in again or change setup**) + opens the scanner setup from there, and the tab shows when the last scan + failed since Inbox started, and why. When the scanner no longer accepts your + saved Sarv sign-in (for example once it has expired), setup now offers + **Sign in with Sarv again**. + +### Security +- **OpenPGP failures no longer say what went wrong inside.** When an + encrypted message cannot be opened, a key cannot be imported, created, + unlocked or backed up, or a message or draft cannot be encrypted or signed, + the app now always says "The OpenPGP operation could not be completed." + Before, the wording changed with the cause (a wrong passphrase, a missing + key, a damaged or altered message, the system keychain), which could tell + whoever sent a crafted message how far decryption got, and the encryption + library's own explanation was written to the app's log file. The log now + records only the kind of failure. A locked key still offers its passphrase + prompt, and Settings → Encryption still asks for a passphrase when a key + needs one and offers to unlock a key before backing it up. A message that + cannot be opened now offers **Try again** and the same tip whatever the + reason: if it was encrypted to a key you haven't added, import that key in + Settings → Encryption. Recipients without a key are still named in the + composer before you send. +- **Sending a signed message with a locked key asks for its passphrase.** + When a message you sign needs a key that is still locked this session, the + composer now comes back with your message and asks for the key's + passphrase; once it is unlocked, press **Send** again. It comes back with + the address you chose to send from, so the message is still encrypted and + signed as that address. A message already waiting in the Outbox that needs + a locked key (a scheduled send after you restarted the app) now says + "Unlock your key in Settings → Encryption, then retry."; **Retry** sends it + once the key is unlocked. Before, such a message failed with no way to tell + what to do. +- **A link asks before it opens a site the app does not know.** Clicking a + link in a message, a sender's unsubscribe page, a scanner provider's privacy + policy or an extension's homepage now shows a warning first. It names the + site on its own line (a look-alike name written in other alphabets shows in + its `xn--` form), shows the address, and says when the link is not secure + (`http`). Nothing opens unless you choose **Open link**; **Cancel** is the + default. Tick **Don't ask again** for a site you trust and its links open + without asking from then on; that site only, not other names under it. + Security → Trusted & blocked links shows how many sites you allowed, and + **Forget all** takes them back. Links that pass through a link-checking, + redirect or tracking service (Microsoft Safe Links, Google redirects and + Translate, t.co, lnkd.in, Proofpoint, Mailchimp, SendGrid, Mandrill) always + ask and cannot be set to **Don't ask again**, because one such site forwards + to any other; when the link says where it goes, the warning names that site + too. The pages the app itself links to (sarv.com, the privacy policy, the + account pages it points you to), the message menu's **Translate** command + and email addresses open as before; other pages on Sarv's sites ask like any + other link. +- **A mail server with its own certificate is trusted only for that exact + certificate.** The "Allow self-signed / invalid certificates" box is gone: it + made Sarv Inbox accept any certificate at all for that account. Now, when you + add a password account, test it, or reconnect it or verify sending in + Settings → Accounts, and its server presents a certificate your system does + not trust (a self-signed certificate, or one from your company's own + authority), Sarv Inbox shows it to you before sending anything: the server, + who issued it, its dates and its SHA-256 fingerprint. Choose **Trust this + certificate** only if it matches what your administrator gave you. From then + on that account accepts exactly that certificate from that server and port, + and refuses every other one, including a renewed certificate. An expired + certificate cannot be approved. The account's settings show the trusted + certificate's fingerprint and when you approved it, with **Remove**. +- **Sarv Inbox never asks about a certificate on its own.** A reconnect after + waking, a change of network or background syncing that meets a certificate it + does not trust stops before sending your password and shows a banner instead; + you review the certificate by reconnecting the account in Settings → + Accounts. So someone on a public network cannot make a trust question pop up + for you to click. Accounts that signed in with Google, Microsoft or Sarv are + not affected: their certificates are always checked as before. +- **Accounts set up with "allow self-signed" need one review.** After this + update they stop connecting until you open Settings → Accounts and reconnect + them; you then see the certificate their server presents, once. Approve it and + they carry on as before. +- **Extensions are unpacked with an up-to-date archive reader.** Installing + an extension from the marketplace, and the extensions that come with the app, + now use tar 8. Version 7 had security problems published in December 2026: + a link that could point outside the extension's folder, archive headers that + could rename or resize a file, and small archives that could use up memory or + stop an install from finishing. Extensions were already checked against their + published checksum and could not include links, so this is an extra layer of + protection. + +### Fixed +- **macOS no longer asks to let "Electron" find devices on your local + network.** On a network whose DNS server is a local device, such as an office + router, the app looked up names by asking that server directly, so macOS + asked for Local Network access, and named the request after a part of the app + that was still called "Electron". Names are now looked up through macOS + itself, which needs no such permission, and every part of the app carries the + Sarv Inbox name. If macOS does ask, for the app's own checks of senders + against spam blocklists, the request now says Sarv Inbox and why. +- **Inbox Agent remembers the conversation.** Every question in a chat now + carries the earlier questions and answers of that chat. Before, it did so + only when the question looked like a follow-up, so a reply such as "find it + from the email signature" or "yes" lost track of who you were asking about. + Answers that drew on accounts you have since deselected are still left out. +- **"Draft" shows on every conversation that has one.** A conversation with + an unsent reply, including one the AI drafted, showed the red "Draft" label + in the inbox list but not in search results or in category tabs such as + Needs Response. It now shows in all of them, on every page of a tab, as does the star of a + conversation starred on another copy. A draft kept in your provider's own + Drafts folder (for example `INBOX.Drafts`) now counts too. +- **Inbox Agent's "reviewed" count includes the emails it sorted.** After + sorting every email that matched a request, such as all your unread mail, + the coverage line under the answer still said "0 of 389 matching messages + reviewed", because it counted only the emails the agent opened in full. Each + email the agent sorted now counts, once. An email it could not sort, because + the AI provider did not answer for its batch, still does not. +- **A change you make for one mailbox never lands in another.** With more than + one account, trusting a sender, removing a trusted sender, saving or + discarding a draft, reopening a reply draft, creating or applying a label, + and caching a conversation summary could, if that account was briefly + unavailable (for example while it was being compacted), be applied to the + mailbox you had open instead. A trusted sender's mail skips the spam filter, + so that one could let a sender's mail through in the wrong account. These now + stop with an error, and nothing changes in the other mailbox. Thread + summaries are also kept per account now, so a summary made in All Inboxes is + shown only on that account's copy of the conversation. +- **A removed account no longer comes back.** A late request for an account + you had removed (a background check, a switch, a sending connection) could + recreate a blank database for it, and a change saved while the removal was + still finishing could put the account back in the list at the next start. The + app now opens a mailbox only for an account that is set up on this computer, + and a removed account stays removed until you add it again. +- **Switching accounts that cannot be opened keeps you where you were.** If the + account you pick (or, after you remove the open account, the next one) cannot + be opened right now, the app stays on a working mailbox, or shows no account, + instead of showing one account's name over another account's mail. +- **Compressing the database of the account you have open** no longer leaves + the app without a mailbox until you restart it. +- **A blocked attachment says why the scan failed.** Viewing, opening or saving + an attachment that could not be scanned used to say only "scanning failed. + Try again when the scanner is available.", whatever went wrong. It now says + which: the scanner is busy with other files, its sign-in is no longer valid + (sign in again under Security → Attachment scanning), its operator's policy + refused the request, it could not be reached, its certificate or a redirect + could not be trusted, it is not accepting files right now, it could not + finish the file, the attachment could not be fetched from your mail server, + the scanner changed its privacy terms or scan policy, its virus definitions + are out of date, or the attachment is too large to scan. An attachment over + the scanner's size limit no longer tells you to check your connection, and a + saved scanner sign-in that cannot be opened (a locked keychain) now says so + instead of a general error. A scan the scanner itself cancelled is no longer + shown as cancelled by you. The app's log records the kind of failure, never + the file or the message. + ## [1.5.0] - 2026-11-25 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 9c9ac800..2f44c314 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -243,7 +243,34 @@ Established shared helpers (extend this list as you add more): (renderer: `@sarvinbox/core/connection-security`). The one rule for how an IMAP/SMTP connection is secured: 'ssl' | 'starttls' (upgrade REQUIRED) | 'none' (explicit opt-out); legacy configs resolve from `secure`, OAuth never to 'none'. - Use it in clients and account forms instead of reading `secure`. + Use it in clients and account forms instead of reading `secure`. Its + `TransportOptIns` is encryption only (`allowPlaintext`): the old + `allowInsecureTLS` ("allow self-signed") is retired and ignored everywhere. +- `resolveTlsOptions(config)` — `packages/core/src/utils/tls.ts`. The ONLY place + a mail connection's TLS options are built: always `rejectUnauthorized: true` + with a TLS 1.2 floor; with a `certificatePin` (password accounts only) the + approved leaf is the sole trust anchor (`ca` + `allowPartialTrustChain`, which + Electron's BoringSSL needs) and `checkServerIdentity` accepts only that exact + SHA-256. Never set `rejectUnauthorized` anywhere else — + `test/unit/utils/tls-guard.test.ts` fails if you do; the one exception is + `inspectServerCertificate` (`certificate-inspection.ts`), which fetches a + certificate to SHOW and carries no credential. `isCertificateUntrustedError` / + `CERTIFICATE_UNTRUSTED` classify a refused handshake. +- `applyCertificatePin(config, kind, ids)` / `withCertificateApproval(attempt, request, { sameTarget })` — + `apps/desktop/electron/services/certificate-trust.ts`. Every main connect path + puts the account's approved certificate (or none) on the config right before + dialling — replacing any pin the window sent. The trust question is NEVER + asked automatically: only a connect the user started from a form, which the + form arms first with `certificates:review` (`allowCertificateReview(id, kind)` + in the renderer; one account+kind, used by the next connect, 60 s, rate- + limited), may ask in main's own dialog and retry once — for the same + `sameTarget` (the account on screen) or not at all. Reconnect ladders, + background sync, the pool and the Inbox Agent get the refusal at once. Use + `applyCertificatePin` for any new IMAP/SMTP connect path, and the wrapper only + for a user-started one; OAuth never gets a pin. Pins live in the vault + (`AccountSecrets.certificates`), written only by `setAccountCertificatePin` + with the throwing `writeBlob`. The renderer's `connectAccountId(accounts, + email, host)` (store/helpers.ts) is the id a connect runs as — arm with it. - `createLogBudget()` / `writeExtensionLog(logger, budget, line)` / `extensionDebugEnabled()` — `packages/core/src/extensions/runtime/log-budget.ts`. How many lines a stranger's code may have the main process write, and the one @@ -260,6 +287,27 @@ Established shared helpers (extend this list as you add more): conversation-level star writes to: the LATEST message when starring, every row when unstarring (Outlook / Sarv Mail behaviour). Use it for any new thread-wide star control instead of passing the whole thread's ids. +- `resolveNamedOrActiveAccountTarget(accountId?)` / `requireNamedOrActiveStorage(accountId?)` / + `requireAccountStorage(accountId)` — `apps/desktop/electron/services/account-target.ts`. + The ONLY way a handler resolves a renderer-named account: no id is the active + account; a named one is exactly that account's runtime (opened only if the + registry lists it) or a throw — never a fall back to the active mailbox + (thread ids, Message-IDs, addresses and label names exist in every account). + There is no lenient resolver; do not add one. +- `isRegisteredAccountId(id)` — `apps/desktop/electron/services/accounts-registry.ts`. + Whether an id is a configured account, read through the THROWING + `readRegistryAccounts`. `ensureAccountRuntime` gates on it, so no path opens + (or creates) a mailbox DB for an unlisted id; only `accounts:setActive` passes + `registryChecked` — after its own registry read, or for an ADD backed by + main's sign-in proof (`noteVerifiedAccount` / `takeVerifiedAccount`, + `apps/desktop/electron/services/account-add-proof.ts`: recorded by a + successful `imap:probeCredentials`, one use, ten minutes). A removed id is + tombstoned (`markAccountRemoved`) so no snapshot or seed writes its row back; + only a verified re-add clears it. +- `accounts:setActive` is TRANSACTIONAL: `success: false` means main did not + move (open first, point second; a failure after the pointer moved puts it, + the persisted pointer and the outbox back). Renderer code may rely on that — + `selectAccount` resolves `false` on a refusal and leaves the view alone. - `applyDbKey(db, key)` / `encryptPlaintextDb(db, key, schema?)` — `packages/storage-node/src/db-encryption.ts` (import `@sarvinbox/storage-node/db-encryption` from the desktop app; it has its own @@ -312,11 +360,57 @@ Established shared helpers (extend this list as you add more): throws, bounded wait, logs no file name. `writeProtectedAttachment` already calls it before its commit; call it for any other path that writes or hands an attachment to another app — never for the user's own files (key exports). +- `PGP_FAILURE_MESSAGE` / `PgpFlowCode` — `packages/core/src/pgp/failure.ts` + (renderer: `@sarvinbox/core/pgp-failure`), with `logPgpFailure(log, context, error)` / + `pgpFlowCode(error)` in `apps/desktop/electron/services/pgp-failure.ts`. The ONE + sentence every OpenPGP failure shows the user, whatever the cause (CASA 4.1.4: + no decryption oracle); the log line for it (context, then the error's class and + code, never its message); and the only causes the renderer may act on + (`locked`, `passphrase-required`). Our OpenPGP error classes carry the + sentence as their message and the cause as `code`. Never show or log a caught + OpenPGP error's message, and never add a cause-specific sentence. +- `PgpUnlockPrompt` / `PgpUnlockForm` / `PgpSendUnlockPrompt` — + `apps/desktop/src/components/PgpUnlockPrompt.tsx`, with + `lockedSigningKeyFor(request, fromHeader, keyring)` in + `apps/desktop/electron/services/pgp-failure.ts`. The one unlock prompt (fixed + guidance, passphrase form, PGP_FAILURE_MESSAGE on failure) the reader and every + composer show; its `recheck` asks whether the key THIS screen needs is open now + (never a count of keys unlocked). `lockedSigningKeyFor` is the pre-queue check + that refuses a send signed with a locked key with the `locked` code, so the + composer can be reopened with the prompt (`RestoreDraft.pgpUnlock`, with the + alias it sent as in `RestoreDraft.from`), and the prompt's re-check + (`pgp:signingKeyLocked`). A send already queued that meets a locked key fails + with `PGP_UNLOCK_THEN_RETRY_MESSAGE` (code `locked`) for the Outbox. + `PgpComposeState.downgrade`: encryption asked for but not deliverable — a + composer never sends then. - `errorClassName(error)` — `packages/core/src/utils/error-class-name.ts`. The class of a thrown value and nothing else, for a log line or error about a failure whose message may quote secret data (a decrypted payload, a keychain's refusal). Use it instead of `error.message` there. +- `openExternalUrl(url, parentWindow)` — `apps/desktop/electron/services/external-link-gate.ts`. + The ONE way main hands a URL to the OS: http/https/mailto only, then a warning + naming the host unless the link is one of the exact pages the app wrote + (`isAppLink` / `APP_LINK_PAGES` in `packages/core/src/utils/app-links.ts`, + renderer `@sarvinbox/core/app-links`) or a host the user chose "Don't ask again" + for. Use it for any path that opens a URL the app did not write (mail, a header, + an extension, a provider, configuration); never `shell.openExternal` directly — + `test/unit/electron/external-link-paths.test.ts` lists the only exceptions. + A new button to a fixed page imports its URL from app-links. An address main + builds ITSELF from fixed parts (the Translate menu item: `translationUrl` in + app-links, IPC `app:openTranslation`) opens through `openAppBuiltUrl(url)` + without the warning; the renderer sends only the values, never a URL, and the + paths test pins its one caller. +- `isLinkWrapper(url)` / `unwrappedDestination(url)` / `LINK_WRAPPERS` — + `packages/core/src/utils/link-wrappers.ts`. The known forwarders (Safe Links, + google.com/url, Translate, shorteners, bulk-mail click trackers) whose first hop + must never be trusted, and the destination a wrapper carries in a parameter, + for DISPLAY only. The link gate offers no "Don't ask again" for them. + Keep the list short; extend it rather than matching hosts by hand. +- `truncateMiddle(text, maxChars, marker?)` — `packages/core/src/utils/truncate-middle.ts` + (renderer: `@sarvinbox/core/truncate-middle`). A long text with its middle cut + out, head and tail kept. + - `checkAIEndpoint(url)` — `packages/core/src/utils/ai-provider-auth.ts`. The one transport rule for an AI provider address: https to any host, plain http only to this computer, never credentials in the URL. Use it (or `aiEndpointOrigin`) for @@ -332,7 +426,9 @@ Established shared helpers (extend this list as you add more): - `readBlob(key)` — `apps/desktop/electron/services/core-db.ts`. A core-DB blob, or null when there is none; THROWS when the store cannot be read, where `getBlob` answers null. Use it for any store whose readers decide what is gone or what to - overwrite (the OAuth token store does). + overwrite (the OAuth token store and the credential vault do). Its twin + `writeBlob(key, data)` THROWS on a failed write, where `setBlob` only logs: + use it for any write the user is told succeeded (an approved certificate). - `trimChars` / `trimCharsStart` / `trimCharsEnd(value, set)` — `packages/core/src/utils/trim-chars.ts` (and `trimTrailingSlashes(value)` in `trailing-slash.ts`, built on it). Trim a set of characters (a string, or a @@ -383,6 +479,15 @@ Established shared helpers (extend this list as you add more): the email's own flags and content, then its sender (VIP) and conversation (the user's recent reply, a colleague). A failed lookup protects. Use both for any new path that changes mail on the agent's behalf. +- `filterAiVerdict(storage, email)` — `apps/desktop/electron/services/filter-ai-skip.ts` + (built on core `filterSkipsAI(email, rules)`). Whether a user filter's "Skip AI + checks" keeps the background AI away from an email: `skip`, `run`, or `unknown` + when the rules could not be read (neither send nor mark handled). Every path + that sends an email to the AI or copies an AI verdict onto one asks it first. +- `openFilterEditor(draft)` / `filterDraftFromSender(address)` — + `apps/desktop/src/utils/filter-draft-bridge.ts`. Open Settings → Filters with a + pre-filled filter, and the draft for one sender. Use them for any new + "create a filter from here" entry point. - `isAllowedArchiveEntry(path, entry)` — `apps/desktop/electron/services/extension-archive-rules.mjs`. What may come out of an extension archive (allowlisted paths, plain files and the expected folders, diff --git a/README.md b/README.md index 1281909c..ca84518d 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,9 @@ product, or removing the Sarv branding needs our written permission — see - **Smart categorization** — AI labels (Important, Needs Response, Meetings, Invoices, …) with a customizable, section-based inbox. - **Privacy-first** — mail is stored encrypted on your device, message text - reaches an AI provider only once you connect one, and TLS verification is on - by default. + reaches an AI provider only once you connect one, and mail servers' + certificates are always verified (a server with its own certificate is + trusted only for the exact certificate you approve). - **Cross-platform** — macOS, Windows and Linux (Electron). ## Getting started diff --git a/SECURITY.md b/SECURITY.md index c3285080..510900a3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -125,10 +125,67 @@ 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-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: +Reviewed 2026-12-03: `pnpm audit --audit-level=high` exits 0. The ignore list +holds 18 CVEs, all in `tar` 7, published on 1–2 December 2026: +[CVE-2026-140230](https://github.com/advisories/GHSA-xm6h-2993-3ch9), +[CVE-2026-140231](https://github.com/advisories/GHSA-9hmx-4f52-v64x), +[CVE-2026-140234](https://github.com/advisories/GHSA-wpwg-r92p-fjjh), +[CVE-2026-140235](https://github.com/advisories/GHSA-rgjp-p5j7-w36x), +[CVE-2026-140236](https://github.com/advisories/GHSA-qv2w-fc3h-pm27), +[CVE-2026-140238](https://github.com/advisories/GHSA-mpg7-vg3p-wc3m), +[CVE-2026-140239](https://github.com/advisories/GHSA-ffhw-4r4q-5cwv), +[CVE-2026-140240](https://github.com/advisories/GHSA-7c32-79xj-j3jp), +[CVE-2026-140241](https://github.com/advisories/GHSA-72fp-85cc-g945), +[CVE-2026-140244](https://github.com/advisories/GHSA-mhqm-9wj8-w7r4), +[CVE-2026-140245](https://github.com/advisories/GHSA-jmj2-9c5q-vw73), +[CVE-2026-140246](https://github.com/advisories/GHSA-hqgx-p3r3-2cfg), +[CVE-2026-140247](https://github.com/advisories/GHSA-gvrf-jx37-rjv5), +[CVE-2026-140248](https://github.com/advisories/GHSA-6wwr-g865-f46r), +[CVE-2026-140249](https://github.com/advisories/GHSA-4pf9-5fpx-xmr6), +[CVE-2026-140250](https://github.com/advisories/GHSA-3wwj-8j6r-q339), +[CVE-2026-140251](https://github.com/advisories/GHSA-98v3-7xjr-fg83) and +[CVE-2026-140252](https://github.com/advisories/GHSA-25mm-r35j-6hgm). They cover +symbolic links that escape the extraction folder, PAX headers that rename or +resize an entry, and archives that exhaust memory or never finish. Every one is +fixed only in tar 8, a rewrite with a new API. + +- **The app's own tar is fixed.** The desktop app unpacks extension archives with + tar (`extension-marketplace.ts`, and `scripts/prefetch-default-extensions.mjs` + when the build seeds the default extensions), and now requires tar 8.1.0. +- **What still has tar 7 is build tooling.** `electron-builder` (through + `app-builder-lib`) and `node-gyp` require `^7.5.7`, including their latest + releases (26.18 and 13.1), and call tar 7's stream API, so forcing tar 8 on + them would break the build. Both are desktop devDependencies and neither ships + in the app. `app-builder-lib` packs the project's own build output and unpacks + the tool archives `electron-builder` downloads for itself. `node-gyp` unpacks + the Node and Electron headers, which it checks against their published + SHA-256 sums. A `tar@7` override keeps them on 7.5.24, which fixes the one + advisory 7.x did get a fix for, + [GHSA-ph3c-p786-j4rp](https://github.com/advisories/GHSA-ph3c-p786-j4rp). +- **The ignore list applies to every path, the app's own included,** so the gate + would no longer catch the app going back to tar 7. A unit test takes that job: + `apps/desktop/test/unit/electron/services/extension-archive-tar.test.ts` fails + if the tar that the installer or the seed script loads, or the desktop + package's declared range, is older than 8.0.2. +- **Remove these entries** when `electron-builder` and `node-gyp` move to tar 8. + The non-blocking full report in CI shows them until then. + +Fixed in the same review by overrides, all in tooling the desktop app does not +ship: +[GHSA-ghv9-86vm-4v8m](https://github.com/advisories/GHSA-ghv9-86vm-4v8m) +(critical, `cross-spawn` < 7.1.0, command injection when spawning a batch file +on Windows), used by React Native's debugger, ESLint and `electron-builder`, is +fixed by `cross-spawn@7` ^7.1.2. +[GHSA-37g9-w4hg-h9qr](https://github.com/advisories/GHSA-37g9-w4hg-h9qr) +(high, `ws`, unbounded automatic pong replies) is fixed by `ws@7` ^7.5.14 for +React Native and Metro, and by `ws@8` ^8.23.1 for `happy-dom`, which runs the +renderer tests. +[GHSA-6jpm-p5cq-9q44](https://github.com/advisories/GHSA-6jpm-p5cq-9q44) +(moderate, `terser` < 5.51.3, which Metro uses) is fixed by `terser@5` ^5.51.4. + +Reviewed 2026-11-19: `pnpm audit --audit-level=high` exited 0 with **no ignore +list**. The list had been emptied because GitHub withdrew both advisories it +held: - [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 @@ -157,17 +214,29 @@ Moderate, no fixed version these tools accept (below the gate, so not in 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. + walk to bound untrusted input. The same 13.0.6 also has + [CVE-2026-137196](https://github.com/advisories/GHSA-qxr8-q827-836c) + (13.0.5 to 14.0.5, `ignore` patterns skip the brace-expansion limit; fixed + only in 14.0.6). Its patterns come from the same build configuration. - [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. + lint configuration supplies; none comes from mail or the user. The same + versions also have + [CVE-2026-140006](https://github.com/advisories/GHSA-c859-jr93-m5j4) + (7.4.0 to 11.0.7, `minimatch.escape()` output can match more or less than the + text; fixed only in 11.0.8). These tools escape no text from mail or the user. +- [CVE-2026-140237](https://github.com/advisories/GHSA-p96f-8xj2-g85p), + `tar` 7 (a PAX size applied again to a later entry; fixed only in 8.0.0). + Only the build tools' tar 7.5.24 has it, for the reasons given for the high + tar advisories above. + +Forcing any of them onto its new major line would be an incompatible +major-version override on those tools. None of these packages 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) diff --git a/apps/desktop/build/afterPack.js b/apps/desktop/build/afterPack.js index 5dad1396..e2b223ba 100644 --- a/apps/desktop/build/afterPack.js +++ b/apps/desktop/build/afterPack.js @@ -17,6 +17,7 @@ const { rm, readdir, stat } = require('node:fs/promises') const { join } = require('node:path') const { buildKeychainHelper } = require('./keychain-helper.js') +const { brandMacHelperNames } = require('./mac-helper-names.js') // Directory names that node-gyp leaves behind and nothing loads at runtime. const DEAD_BUILD_DIRS = new Set(['obj.target', 'obj', '.deps']) @@ -63,6 +64,12 @@ exports.default = async (context) => { directory: join(appOutDir, `${appName}.app`, 'Contents', 'MacOS'), arch: context.arch, }) + // Helpers keep Electron's CFBundleName unless renamed here, and macOS shows + // it in prompts ("Allow "Electron" to find devices…"). Before signing. + await brandMacHelperNames({ + frameworksDir: join(appOutDir, `${appName}.app`, 'Contents', 'Frameworks'), + productFilename: appName, + }) } // Where the asarUnpack'd native modules land, per platform. diff --git a/apps/desktop/build/mac-helper-names.js b/apps/desktop/build/mac-helper-names.js new file mode 100644 index 00000000..cf912e34 --- /dev/null +++ b/apps/desktop/build/mac-helper-names.js @@ -0,0 +1,57 @@ +// Brands the macOS helper apps' CFBundleName. +// +// electron-builder renames each helper's file, executable, display name and +// bundle id ("Sarv Inbox Helper (GPU).app", com.sarv.sarvinbox.helper.GPU) but +// leaves CFBundleName as Electron shipped it: "Electron Helper", "Electron +// Helper (GPU)" and so on. macOS names a process by that key in some of its own +// prompts. The network service runs in "Sarv Inbox Helper", so 1.5.0 asked +// users to "Allow "Electron" to find devices on local networks?". +// +// Each helper's CFBundleName is set to its bundle's own name. Runs from +// afterPack, which comes before signing, so the signature covers the new +// value. Uses electron-builder's own plist reader and writer, the same one +// that wrote these files a moment earlier. Idempotent: the universal build +// runs it on each slice and again on the merged app, and the slices must stay +// identical for the merge. + +const { readdir } = require('node:fs/promises') +const { join } = require('node:path') + +const HELPER_SUFFIX = '.app' + +/** + * Set CFBundleName on every " Helper….app" in `frameworksDir`. + * Throws when none is found (a release must never ship with the step silently + * skipped) and when a helper still says "Electron" afterwards. + * + * @param {{ frameworksDir: string, productFilename: string, + * plist?: { parsePlistFile(file: string): Promise>, + * savePlistFile(file: string, data: unknown): Promise } }} options + * @returns {Promise} the names now set, sorted + */ +async function brandMacHelperNames({ frameworksDir, productFilename, plist = require('app-builder-lib/out/util/plist.js') }) { + const prefix = `${productFilename} Helper` + const entries = await readdir(frameworksDir, { withFileTypes: true }) + const helpers = entries + .filter((entry) => entry.isDirectory() && entry.name.startsWith(prefix) && entry.name.endsWith(HELPER_SUFFIX)) + .map((entry) => entry.name.slice(0, -HELPER_SUFFIX.length)) + .sort() + if (helpers.length === 0) { + throw new Error(`mac-helper-names: no "${prefix}*.app" in ${frameworksDir}`) + } + const names = [] + for (const name of helpers) { + const file = join(frameworksDir, `${name}${HELPER_SUFFIX}`, 'Contents', 'Info.plist') + const info = await plist.parsePlistFile(file) + if (info.CFBundleName !== name) { + await plist.savePlistFile(file, { ...info, CFBundleName: name }) + } + names.push(name) + } + for (const name of names) { + if (/electron/i.test(name)) throw new Error(`mac-helper-names: helper still named "${name}"`) + } + return names +} + +module.exports = { brandMacHelperNames } diff --git a/apps/desktop/electron/ipc/accounts-handlers.ts b/apps/desktop/electron/ipc/accounts-handlers.ts index 69a5bddf..5d9381d2 100644 --- a/apps/desktop/electron/ipc/accounts-handlers.ts +++ b/apps/desktop/electron/ipc/accounts-handlers.ts @@ -9,6 +9,8 @@ * `accounts:unifiedInbox` / `accounts:unreadSummary` fan a READ across accounts * for the unified "All Inboxes" view + per-account badges. They read each * account's own SQLite DB (no IMAP connection needed) and never mutate anything. + * Each id goes through `ensureAccountRuntime`, which opens only accounts the + * registry lists: a stale id reads as an empty account, never a new blank DB. * * DB ownership is deterministic (see ensureAccountRuntime): the persisted PRIMARY * account owns the legacy `sarvinbox.db`; every other account gets its own @@ -19,9 +21,13 @@ import type { EmailRecord, SearchQuery, ViewFilter } from '@sarvinbox/core'; import { accountLogLabel, createLogger, errorDiagnostic, redactAccountIds } from '@sarvinbox/core'; import { ipcMain } from 'electron'; +import { takeVerifiedAccount } from '../services/account-add-proof'; import { settleRevocation, type AccountRevocation } from '../services/account-revocation'; import { + clearAccountRemoved, + isRegisteredAccountId, listRegistryAccounts, + markAccountRemoved, oauthIdentityOf, readRegistryAccounts, upsertRegistryAccounts, @@ -33,7 +39,7 @@ import { deleteAppSetting, type RegistryAccount, } from '../services/accounts-registry'; -import { ensureAccountRuntime, loadPrimaryAccountId, savePrimaryAccountId, accountInboxUnread, rekeyAccount, deleteAccountData, legacyDbExists, cleanupOrphanedAccountDbs } from '../services/accounts-runtime'; +import { ensureAccountRuntime, loadPrimaryAccountId, savePrimaryAccountId, clearPrimaryAccountId, accountInboxUnread, rekeyAccount, deleteAccountData, legacyDbExists, cleanupOrphanedAccountDbs, quiesceAccountRuntime } from '../services/accounts-runtime'; import { peekAntivirusScanService } from '../services/antivirus-scan-service'; import { cleanupOrphanedAttachmentStores, removeAllCachedAttachments } from '../services/attachment-cache'; import { clearUnscannedWarningPreference } from '../services/attachment-warning-preferences'; @@ -53,6 +59,78 @@ async function findInbox(storage: { getFolders: () => Promise }): Promise return folders.find((f) => f.path === 'INBOX' || f.name?.toLowerCase() === 'inbox') ?? null; } +/** + * The account a verified ADD activated before its registry row existed — kept + * so the runtime that activation opened is closed if the add is abandoned + * (rolled back, or replaced by another add) instead of lingering as an open, + * unlisted database with a sync engine nobody closes. + */ +let addingAccountId: string | null = null; + +/** Close the runtime an abandoned add left open. Best-effort; never throws. */ +async function closeAbandonedAdd(nowActive: string): Promise { + const pending = addingAccountId; + if (!pending || pending === nowActive) return; + try { + // Completed: its registry row landed (the add's connect succeeded). + if (isRegisteredAccountId(pending)) { + addingAccountId = null; + return; + } + } catch { + return; // could not find out — never close an account on a guess + } + addingAccountId = null; + try { + await quiesceAccountRuntime(pending, 'abandoned add'); + logger.info('[Accounts] closed the runtime of an abandoned add', accountLogLabel(pending)); + } catch (error) { + logger.warn('[Accounts] closing an abandoned add failed:', errorDiagnostic(error)); + } +} + +/** + * Put main back where a failed `accounts:setActive` found it: the active + * pointer, the persisted pointer, the outbox, a legacy adopt that opened + * nothing, and the runtime a failed ADD opened. Each step is best-effort and + * logged; none throws. + */ +async function undoActivation(step: { + accountId: string; + previousId: string | null; + previousPersisted: string | null; + adding: boolean; + adopted: boolean; + opened: boolean; + pointed: boolean; + persisted: boolean; +}): Promise { + if (step.pointed) { + setCurrentAccount(step.previousId); + try { rebindOutboxStorage(); } catch (error) { + logger.warn('[Accounts] restoring the outbox after a failed switch failed:', errorDiagnostic(error)); + } + } + if (step.persisted) { + try { setRegistryActiveAccountId(step.previousPersisted); } catch (error) { + logger.warn('[Accounts] restoring the persisted active account failed:', errorDiagnostic(error)); + } + } + // An adopt whose runtime never opened: nothing claimed sarvinbox.db for this + // account, so the decision is undone. (One that did open keeps it — the file + // is now this account's open database.) + if (step.adopted && !step.opened) { + try { clearPrimaryAccountId(); } catch (error) { + logger.warn('[Accounts] undoing the legacy adopt failed:', errorDiagnostic(error)); + } + } + if (step.adding && step.opened) { + try { await quiesceAccountRuntime(step.accountId, 'failed add'); } catch (error) { + logger.warn('[Accounts] closing a failed add failed:', errorDiagnostic(error)); + } + } +} + export function registerAccountsHandlers(): void { // ===== Durable accounts registry (DB-backed source of truth) ============= // The account list + active pointer live in an encrypted main-process DB @@ -178,7 +256,10 @@ export function registerAccountsHandlers(): void { try { wasRegistered = readRegistryAccounts().some((a) => a.id === accountId); } catch { /* stays false */ } await deleteAccountData(accountId); // Drop it from the durable registry too, so it doesn't reappear on the - // next hydrate/seed. + // next hydrate/seed. Tombstoned FIRST: the window keeps the account in its + // list until this handler returns (the revocation wait below), and a + // snapshot it mirrors meanwhile must not write the row straight back. + markAccountRemoved(accountId); removeRegistryAccount(accountId); // Now the registry is authoritative (we just dropped this account from it), @@ -275,12 +356,49 @@ export function registerAccountsHandlers(): void { } }); - ipcMain.handle('accounts:setActive', async (_event, accountId: string) => { + // `options.adding`: the renderer is ADDING this account (addAccount). Only then + // may the id be one the registry does not list yet — the add flow points main + // at the new account before its first connect, and the registry row is written + // once that connect succeeds — and only when main itself saw that account sign + // in (a successful imap:probeCredentials, account-add-proof): one activation + // per proof, within its window. Every other activation (a switch, startup, an + // add's rollback) must name a configured account: otherwise a stale id (a + // removed account the renderer still remembers) re-created a blank mailbox and + // made it the active one. + // + // TRANSACTIONAL: `success: false` means main is exactly where it was. The + // runtime is opened BEFORE the pointer moves (a runtime that cannot be opened + // is a failure, never an empty active slot), and anything that fails after the + // pointer moved puts back the previous pointer, persisted pointer and outbox. + // The renderer relies on that: it keeps showing the previous account. + ipcMain.handle('accounts:setActive', async (_event, accountId: string, options?: { adding?: boolean }) => { + if (!accountId || typeof accountId !== 'string') return { success: false, error: 'No accountId provided' }; + if (getCurrentAccountId() === accountId && hasAccountRuntime(accountId)) { + return { success: true }; + } + + const previousId = getCurrentAccountId(); + let previousPersisted: string | null = null; + let adding = false; + let adopted = false; + let opened = false; + let pointed = false; + let persisted = false; try { - if (!accountId) return { success: false, error: 'No accountId provided' }; - if (getCurrentAccountId() === accountId && hasAccountRuntime(accountId)) { - return { success: true }; + // One registry read decides; an unreadable registry throws: refused. + const registered = isRegisteredAccountId(accountId); + if (!registered) { + if (options?.adding !== true) { + logger.warn('[Accounts] setActive refused: not a configured account', accountLogLabel(accountId)); + return { success: false, error: 'That account is not configured.' }; + } + if (!takeVerifiedAccount(accountId)) { + logger.warn('[Accounts] setActive refused: an add with no sign-in proof', accountLogLabel(accountId)); + return { success: false, error: 'This account has not signed in yet. Check its details and add it again.' }; + } + adding = true; } + previousPersisted = getRegistryActiveAccountId(); // NOTE: we deliberately do NOT disconnect the previous account's engine on // switch. Tearing it down made switching BACK slow (full reconnect → @@ -291,26 +409,48 @@ export function registerAccountsHandlers(): void { // LEGACY ONLY: adopt the existing sarvinbox.db for the first account that // activates AND only when that file already exists. A fresh install has no // sarvinbox.db, so no primary is set and every account uses its per-id DB. - if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(accountId); + // Never for an account being ADDED: a new account must not take over an + // existing install's mailbox. (With no primary recorded and the legacy file + // present, ensureAccountRuntime then refuses to guess, and the add fails.) + if (registered && !loadPrimaryAccountId() && legacyDbExists()) { + savePrimaryAccountId(accountId); + adopted = true; + } - // Flip the pointer, then ensure this account's runtime exists (claims the - // startup sarvinbox.db for the primary; opens sarvinbox-.db otherwise). - setCurrentAccount(accountId); + // Open first (claims the startup sarvinbox.db for the primary; opens + // sarvinbox-.db otherwise), point second. The membership was decided + // above, so the registry is not read again. if (!hasAccountRuntime(accountId)) { - await ensureAccountRuntime(accountId); + if (!(await ensureAccountRuntime(accountId, { registryChecked: true }))) { + throw new Error('That account could not be opened right now. Try again in a moment.'); + } + opened = true; } + setCurrentAccount(accountId); + pointed = true; // Persist the active pointer durably so main can auto-activate this // account on the next launch without waiting on the renderer. + persisted = true; setRegistryActiveAccountId(accountId); // Drain/send from the now-active account's outbox. rebindOutboxStorage(); - return { success: true }; + + // Being added again after a removal: its registry row may be written now. + if (adding) clearAccountRemoved(accountId); } catch (error) { - logger.error('[Accounts] setActive failed:', error); + logger.error('[Accounts] setActive failed — the previous account stays active:', errorDiagnostic(error)); + await undoActivation({ accountId, previousId, previousPersisted, adding, adopted, opened, pointed, persisted }); return { success: false, error: (error as Error).message }; } + + // An add that was abandoned (rolled back, or replaced by another add) leaves + // a runtime open for an account nobody listed: close it. After the switch, + // so it can never be the account now active. + await closeAbandonedAdd(accountId); + if (adding) addingAccountId = accountId; + return { success: true }; }); // Merged INBOX across the given accounts, tagged with accountId and sorted diff --git a/apps/desktop/electron/ipc/agent-handlers.ts b/apps/desktop/electron/ipc/agent-handlers.ts index be529f0f..80bebd15 100644 --- a/apps/desktop/electron/ipc/agent-handlers.ts +++ b/apps/desktop/electron/ipc/agent-handlers.ts @@ -12,6 +12,7 @@ import { ipcMain } from 'electron'; import { openAccountStorages, requireNamedOrActiveStorage, requireTargetAccountId } from '../services/account-target'; import { resolveAccountIdentity } from '../services/accounts-registry'; import { saveAgentConfig, loadAgentConfig } from '../services/agent-config-store'; +import { decisionActualAction, resolvedDecisionStatus } from '../services/agent-decision-values'; import { forgetAiActions, recordAiActions } from '../services/ai-action-record'; import { refreshContactClassifications } from '../services/contact-classification-service'; import { buildThreadMessages } from '../services/thread-context'; @@ -292,10 +293,15 @@ export function registerAgentHandlers(): void { } }); - ipcMain.handle('agent:resolveDecision', async (_event, decisionId: string, status: string, actualAction?: string, feedback?: string) => { + ipcMain.handle('agent:resolveDecision', async (_event, decisionId: string, status: unknown, actualAction?: unknown, feedback?: string) => { try { + // Only the enums' own values reach the row (see agent-decision-values). + const resolved = resolvedDecisionStatus(status); + if (!resolved) return { success: false, error: 'Unknown decision status' }; + const action = decisionActualAction(actualAction); + if (!action.ok) return { success: false, error: 'Unknown action' }; const agentRepo = getAgentRepo(); - await agentRepo.updateDecisionStatus(decisionId, status as any, actualAction as any, feedback); + await agentRepo.updateDecisionStatus(decisionId, resolved, action.action ?? undefined, feedback); return { success: true }; } catch (error) { return { success: false, error: (error as Error).message }; @@ -513,10 +519,12 @@ export function registerAgentHandlers(): void { } catch (error) { return { success: false, error: (error as Error).message }; } }); - ipcMain.handle('agent:resolveProposal', async (_event, proposalId: string, approved: boolean, actualAction?: string, feedback?: string) => { + ipcMain.handle('agent:resolveProposal', async (_event, proposalId: string, approved: boolean, actualAction?: unknown, feedback?: string) => { try { + const action = decisionActualAction(actualAction); + if (!action.ok) return { success: false, error: 'Unknown action' }; const agentRepo = getAgentRepo(); - await agentRepo.updateDecisionStatus(proposalId, approved ? 'approved' : 'rejected', actualAction as any, feedback); + await agentRepo.updateDecisionStatus(proposalId, approved ? 'approved' : 'rejected', action.action ?? undefined, feedback); return { success: true }; } catch (error) { return { success: false, error: (error as Error).message }; } }); diff --git a/apps/desktop/electron/ipc/ai-handlers.ts b/apps/desktop/electron/ipc/ai-handlers.ts index d5dd1463..1e5ab9f2 100644 --- a/apps/desktop/electron/ipc/ai-handlers.ts +++ b/apps/desktop/electron/ipc/ai-handlers.ts @@ -303,11 +303,17 @@ export function registerAIHandlers(): void { }); /** - * Get thread summary + * Get thread summary, from the account that owns the thread. + * + * The cache is keyed by thread id, and the same thread id exists in every + * account that received the conversation — so it takes the owning account + * (All Inboxes shows other accounts' threads) and resolves it STRICTLY: an + * unavailable account is an error, never the active account's summary of + * its own copy. No id means the active account. */ - ipcMain.handle('ai:getThreadSummary', async (_event, threadId: string) => { + ipcMain.handle('ai:getThreadSummary', async (_event, threadId: string, accountId?: string) => { try { - const storage = requireStorage(); + const storage = await requireNamedOrActiveStorage(accountId); const summary = await storage.getThreadSummary(threadId); return { success: true, data: summary }; } catch (error) { @@ -317,11 +323,13 @@ export function registerAIHandlers(): void { }); /** - * Save thread summary + * Save thread summary into the account that owns the thread — strictly, as + * above: account B's summary must never land in account A's cache under a + * thread id both share. */ - ipcMain.handle('ai:saveThreadSummary', async (_event, summary: any) => { + ipcMain.handle('ai:saveThreadSummary', async (_event, summary: any, accountId?: string) => { try { - const storage = requireStorage(); + const storage = await requireNamedOrActiveStorage(accountId); await storage.upsertThreadSummary(summary); return { success: true }; } catch (error) { diff --git a/apps/desktop/electron/ipc/antivirus-handlers.ts b/apps/desktop/electron/ipc/antivirus-handlers.ts index 4e126d03..fcff0541 100644 --- a/apps/desktop/electron/ipc/antivirus-handlers.ts +++ b/apps/desktop/electron/ipc/antivirus-handlers.ts @@ -4,8 +4,8 @@ import { ipcMain, type IpcMainInvokeEvent } from 'electron'; import { requireTargetAccountId } from '../services/account-target'; import { readRegistryAccounts } from '../services/accounts-registry'; import { cancelSarvScannerOAuth, completeSarvScannerOAuth, connectSarvScannerOAuth, getOnboardingScannerSetup } from '../services/antivirus-onboarding'; -import { getAntivirusScanService } from '../services/antivirus-scan-service'; -import { isScannerExtensionAvailable } from '../services/attachment-download-protection'; +import { getAntivirusScanService, peekAntivirusScanService } from '../services/antivirus-scan-service'; +import { enabledScannerSummaries, isScannerExtensionAvailable } from '../services/attachment-download-protection'; import { getPendingUnscannedAttachmentWarning, respondUnscannedAttachmentWarning } from '../services/attachment-unscanned-warning'; import { unscannedWarningPreferences } from '../services/attachment-warning-preferences'; import { getExtensionManager, getMainWindow } from '../shared'; @@ -53,6 +53,8 @@ export function registerAntivirusHandlers(): void { await getAntivirusScanService().onExtensionDisabled(id); return getAntivirusScanService().getTrustedSetup(id); }); + // Read-only: the saved setup is checked against its scanner and left as it is. + register('antivirus:testConnection', (_event, id) => getAntivirusScanService().testConnection(id)); const registerWarning = (channel: string, run: (...args: unknown[]) => Promise | unknown) => { ipcMain.handle(channel, async (event, ...args) => { @@ -60,6 +62,11 @@ export function registerAntivirusHandlers(): void { catch (error) { return { success: false, error: error instanceof Error ? error.message : 'The antivirus warning could not be updated.' }; } }); }; + // Which scanners Security → Attachment scanning shows. Asked before any + // scanner is set up (or when its code failed to load), so it needs only the + // trusted frame, not a working, permitted extension. + registerWarning('antivirus:listScanners', () => + enabledScannerSummaries(getExtensionManager(), id => peekAntivirusScanService()?.lastScanFailure(id) ?? null)); registerWarning('antivirus:getPendingUnscannedWarning', getPendingUnscannedAttachmentWarning); registerWarning('antivirus:respondUnscannedWarning', respondUnscannedAttachmentWarning); registerWarning('antivirus:getUnscannedWarningPreferences', () => ({ diff --git a/apps/desktop/electron/ipc/app-handlers.ts b/apps/desktop/electron/ipc/app-handlers.ts index 11d711b1..2fb6cedd 100644 --- a/apps/desktop/electron/ipc/app-handlers.ts +++ b/apps/desktop/electron/ipc/app-handlers.ts @@ -7,10 +7,18 @@ import { readFileSync } from 'fs'; import { join } from 'path'; -import { createLogger, urlSchemeForLog } from '@sarvinbox/core'; -import { ipcMain, shell } from 'electron'; +import { createLogger, errorDiagnostic, translationUrl, valueShapeForLog } from '@sarvinbox/core'; +import { ipcMain } from 'electron'; import { crashReportChoice, setCrashReportsEnabled } from '../sentry'; +import { + forgetRememberedLinkHosts, + openAppBuiltUrl, + openExternalUrl, + rememberedLinkHostCount, + windowOfSender, + type ExternalLinkOutcome, +} from '../services/external-link-gate'; const logger = createLogger('app-handlers'); @@ -23,17 +31,37 @@ export function getAppVersion(): string { return APP_VERSION; } -// Only these schemes may be handed to shell.openExternal. Email content is -// attacker-controlled, so an unrestricted openExternal could be coerced into -// opening file://, smb://, or OS-registered custom-protocol handlers. This is -// the single choke point every renderer caller funnels through. -const SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:']); +/** What the renderer is told about one `app:openExternal` request. */ +export interface OpenExternalResult { + success: boolean; + /** The user chose Cancel on the warning: nothing to report, nothing opened. */ + cancelled?: boolean; + error?: string; +} + +const OPEN_EXTERNAL_RESULTS: Record = { + opened: { success: true }, + cancelled: { success: false, cancelled: true }, + refused: { success: false, error: 'Unsupported URL scheme' }, + busy: { success: false, error: 'Another link is waiting for an answer' }, + failed: { success: false, error: 'The link could not be opened' }, +}; + +/** What a renderer is told about the sites that open without asking. */ +export interface RememberedLinkSitesResult { + success: boolean; + data?: { count: number }; + error?: string; +} -function isSafeExternalUrl(url: string): boolean { +const UNREADABLE_SITES = "The list of sites couldn't be read, so every link asks before it opens."; + +function rememberedLinkSites(): RememberedLinkSitesResult { try { - return SAFE_EXTERNAL_SCHEMES.has(new URL(url).protocol); - } catch { - return false; + return { success: true, data: { count: rememberedLinkHostCount() } }; + } catch (error) { + logger.warn('[App] The sites that open without asking could not be read:', errorDiagnostic(error)); + return { success: false, error: UNREADABLE_SITES }; } } @@ -64,19 +92,41 @@ export function registerAppHandlers(): void { }); /** - * Open URL in default browser + * Open a URL in the default browser (or mail handler), through the + * external-link gate: the scheme allow-list, then a warning naming the host + * unless the link is one the app wrote or a site the user chose "Don't ask + * again" for. The renderer cannot skip it — this is the only way it opens one. */ - ipcMain.handle('app:openExternal', async (_event, url: string) => { - if (typeof url !== 'string' || !isSafeExternalUrl(url)) { - // The scheme only: the URL is typically a link clicked in a message. - logger.warn('[App] Blocked openExternal for unsafe URL scheme:', urlSchemeForLog(url)); - return { success: false, error: 'Unsupported URL scheme' }; - } - try { - await shell.openExternal(url); - return { success: true }; - } catch (error) { - return { success: false, error: String(error) }; + ipcMain.handle('app:openExternal', async (event, url: unknown): Promise => + OPEN_EXTERNAL_RESULTS[await openExternalUrl(url, windowOfSender(event))]); + + /** + * The Translate menu item. The renderer sends only WHAT to translate (the + * text, cut to TRANSLATE_MAX_CHARS, and a target language); main builds the + * Google Translate address itself (`translationUrl`) and opens it without + * the warning, because the user chose the app's own command. Anything that + * is not a string, is over the limit, or is not a language tag is refused, + * so no address of the renderer's choosing can ride through here. The text + * is the message's: only its type and length may be logged. + */ + ipcMain.handle('app:openTranslation', async (_event, text: unknown, targetLanguage: unknown): Promise => { + const url = translationUrl(text, targetLanguage); + if (!url) { + logger.warn('[App] Refused a translation request:', valueShapeForLog(text), valueShapeForLog(targetLanguage)); + return { success: false, error: 'This message cannot be sent for translation' }; } + return OPEN_EXTERNAL_RESULTS[await openAppBuiltUrl(url)]; + }); + + // Security → Trusted & blocked links: how many sites open without asking, + // and "Forget all". The hosts themselves never cross to the renderer. + ipcMain.handle('security:getRememberedLinkSites', (): RememberedLinkSitesResult => rememberedLinkSites()); + ipcMain.handle('security:forgetRememberedLinkSites', (): RememberedLinkSitesResult => { + forgetRememberedLinkHosts(); + // Re-read rather than answer 0: a delete that did not land must not show + // an empty list the next link would contradict. + const after = rememberedLinkSites(); + logger.info(`[App] Forgot the sites that open without asking: cleared=${after.data?.count === 0}`); + return after; }); } diff --git a/apps/desktop/electron/ipc/certificate-handlers.ts b/apps/desktop/electron/ipc/certificate-handlers.ts new file mode 100644 index 00000000..39573685 --- /dev/null +++ b/apps/desktop/electron/ipc/certificate-handlers.ts @@ -0,0 +1,74 @@ +/** + * IPC surface for approved mail-server certificates (CASA 4.1.2). + * + * The window can SEE an account's approved certificates (fingerprint, server, + * date — no PEM) and REMOVE one, and it can say the user just started a connect + * from a form (`certificates:review`): only such an armed connect may ask about + * an untrusted certificate, once, rate-limited. It can never approve one: + * approval happens only in main's own dialog, during that connect + * (certificate-trust.ts). + */ +import { createLogger, failureCause } from '@sarvinbox/core'; +import { ipcMain } from 'electron'; + +import { + armCertificateReview, + listAccountCertificates, + removeAccountCertificate, +} from '../services/certificate-trust'; +import { getCurrentAccountId, getSmtpClient, getSmtpClientFor, getSyncEngineFor } from '../shared'; + +const logger = createLogger('certificate-handlers'); + +const isKind = (value: unknown): value is 'imap' | 'smtp' => value === 'imap' || value === 'smtp'; +const isAccountId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 512; + +/** + * Close the account's live connections of `kind`, which were opened while the + * removed certificate was trusted: the removal takes effect now, not at the + * next network blip. Best-effort. + */ +async function closeConnections(accountId: string, kind: 'imap' | 'smtp'): Promise { + try { + if (kind === 'imap') { + await getSyncEngineFor(accountId)?.disconnect(); + return; + } + await getSmtpClientFor(accountId)?.disconnect(); + if (getCurrentAccountId() === accountId) await getSmtpClient()?.disconnect(); + } catch (error) { + logger.warn(`[Certificates] closing the ${kind} connections after a removal failed (${failureCause(error)})`); + } +} + +export function registerCertificateHandlers(): void { + ipcMain.handle('certificates:list', async (_event, accountId: unknown) => { + if (!isAccountId(accountId)) return { success: false, error: 'An account is required.' }; + try { + return { success: true, data: await listAccountCertificates(accountId) }; + } catch (error) { + logger.warn(`[Certificates] could not list approved certificates (${failureCause(error)})`); + return { success: false, error: 'Approved certificates could not be read. Try again in a moment.' }; + } + }); + + ipcMain.handle('certificates:remove', async (_event, accountId: unknown, kind: unknown) => { + if (!isAccountId(accountId) || !isKind(kind)) return { success: false, error: 'An account and a server kind are required.' }; + try { + const removed = await removeAccountCertificate(accountId, kind); + if (removed) await closeConnections(accountId, kind); + return { success: true, data: { removed } }; + } catch (error) { + logger.warn(`[Certificates] could not remove an approved certificate (${failureCause(error)})`); + return { success: false, error: 'The approved certificate could not be removed. Try again in a moment.' }; + } + }); + + // The user just started a connect for this account's `kind` server from a + // form: that connect (the next one, within a minute) may ask about an + // untrusted certificate. Rate-limited per account+kind and overall. + ipcMain.handle('certificates:review', async (_event, accountId: unknown, kind: unknown) => { + if (!isAccountId(accountId) || !isKind(kind)) return { success: false, error: 'An account and a server kind are required.' }; + return { success: true, data: { armed: armCertificateReview(accountId, kind) === 'armed' } }; + }); +} diff --git a/apps/desktop/electron/ipc/draft-handlers.ts b/apps/desktop/electron/ipc/draft-handlers.ts index 1a10c040..1d4c87dd 100644 --- a/apps/desktop/electron/ipc/draft-handlers.ts +++ b/apps/desktop/electron/ipc/draft-handlers.ts @@ -7,16 +7,17 @@ import { basename } from 'path'; import { folderLogLabel, emailContentHash, errorDiagnostic, resolveStandardFolder, createLogger, messageIdKey, withFolderSelected } from '@sarvinbox/core'; -import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; +import { PGP_ENCRYPTED_PLACEHOLDER, PGP_FAILURE_MESSAGE } 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'; import MailComposer from 'nodemailer/lib/mail-composer'; import pLimit from 'p-limit'; import type { LocalCalendarAvailability } from '../../src/types/local-calendar'; -import { requireAccountStorage, requireTargetAccountId, resolveAccountTarget, resolveNamedOrActiveAccountTarget } from '../services/account-target'; +import { requireAccountStorage, requireTargetAccountId, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { seedAttachmentCache } from '../services/attachment-cache'; import { deleteDraftCalendarAvailability, readDraftCalendarAvailability, saveDraftCalendarAvailability, validateDraftCalendarAvailability } from '../services/draft-calendar-metadata'; +import { logPgpFailure } from '../services/pgp-failure'; import { encryptDraftMime } from '../services/pgp-outgoing'; import { getPgpKeyring } from '../services/pgp-service'; import { pokeReadModel } from '../services/read-model-poke'; @@ -269,13 +270,16 @@ export async function saveDraftToIMAP(draft: { /** Local-only scheduling evidence; never included in the IMAP MIME. */ calendarAvailability?: LocalCalendarAvailability; }, options: { messageId?: string } = {}): Promise<{ success: boolean; folderPath?: string; messageId?: string; error?: string }> { - // Resolve the TARGET account's storage + sync engine (falls back to the active - // account when no accountId is given). + // Resolve the TARGET account's storage + sync engine: the active account when + // no accountId is given; a named one strictly. A draft is keyed by its + // thread id and In-Reply-To, which exist in every account's database, so an + // unavailable named account is an error — never a draft written into (or + // replacing a draft of) the active mailbox's copy of the same conversation. const proposal = draft.calendarAvailability === undefined ? undefined : validateDraftCalendarAvailability(draft.calendarAvailability); const strictOwner = proposal ? requireTargetAccountId(draft.accountId) : undefined; const { storage, syncEngine, accountId: owner } = strictOwner ? { ...await resolveNamedOrActiveAccountTarget(strictOwner), accountId: strictOwner } - : await resolveAccountTarget(draft.accountId); + : await resolveNamedOrActiveAccountTarget(draft.accountId); if (!syncEngine) { return { success: false, error: 'No sync engine for account' }; } @@ -339,14 +343,16 @@ export async function saveDraftToIMAP(draft: { // An encrypted draft that cannot be encrypted is not saved at all: the only // other thing to save is the plaintext, which is what the user turned off. + // Whatever failed (no key for the address, the keyring, openpgp.js), the + // answer is the one OpenPGP sentence and the log the error's class and code. const encrypted = draft.pgp?.encrypt === true; let rawMessage = builtMessage; if (encrypted) { try { rawMessage = await encryptDraftMime(builtMessage, draft.accountEmail || '', getPgpKeyring()); } catch (err) { - logger.warn('[Drafts] Encrypted draft not saved:', (err as Error)?.message ?? String(err)); - return { success: false, error: `The draft could not be encrypted, so it was not saved: ${(err as Error)?.message ?? String(err)}` }; + logPgpFailure(logger, '[Drafts] Encrypted draft not saved', err); + return { success: false, error: PGP_FAILURE_MESSAGE }; } } @@ -664,13 +670,18 @@ export async function writeLocalDraftRow(storage: ReturnType { +export async function deleteDraftsForThread(accountId: string | null | undefined, threadId: string): Promise { if (!threadId) return; - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) return; @@ -740,7 +751,8 @@ export function registerDraftHandlers(): void { // Get the drafts folder name ipcMain.handle('drafts:get-folder', async (_event, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); + // Strict: another mailbox's Drafts path is not this account's answer. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); const folderPath = await findDraftsFolderPath(storage); return { success: true, data: folderPath }; } catch (error: any) { @@ -781,7 +793,9 @@ export function registerDraftHandlers(): void { if (!Array.isArray(messageIds) || messageIds.length === 0) { return { success: true, data: null }; } - const { storage } = await resolveAccountTarget(accountId); + // Strict: Message-IDs exist in every account that got the thread, so a + // fallback would reopen ANOTHER mailbox's draft in this composer. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) return { success: true, data: null }; const placeholders = messageIds.map(() => '?').join(','); @@ -834,11 +848,21 @@ export function registerDraftHandlers(): void { namedAccount: !!options.accountId, namedAccountIsActive: options.accountId ? options.accountId === getCurrentAccountId() : null, }); - // Resolve the draft's OWNING account (falls back to active). Without this the - // delete ran against the active account's DB/engine — the wrong ones when the - // draft belongs to another account (e.g. opened from All Inboxes) — so it - // removed 0 rows and the draft was undeletable ("immortal draft"). - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(options.accountId); + // Resolve the draft's OWNING account (the active one when none is named). + // Without this the delete ran against the active account's DB/engine — the + // wrong ones when the draft belongs to another account (e.g. opened from All + // Inboxes) — so it removed 0 rows and the draft was undeletable ("immortal + // draft"). STRICT: a discard is keyed by thread id or Message-ID, which + // exist in every account, so an unavailable named account is refused rather + // than deleting the active account's drafts of the same conversation. + let resolved: Awaited>; + try { + resolved = await resolveNamedOrActiveAccountTarget(options.accountId); + } catch (error) { + draftLog('delete:refused', { error: errorDiagnostic(error) }); + return { success: false, error: (error as Error).message }; + } + const { storage, syncEngine, accountId: owner } = resolved; draftLog('delete:resolved', { dbFile: dbFileOf(storage), hasSyncEngine: !!syncEngine, @@ -1033,7 +1057,9 @@ export function registerDraftHandlers(): void { const targets = accountIds.length ? accountIds : [undefined as any]; for (const accountId of targets) { try { - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + // Strict: a named account that cannot be resolved is reported as that + // account's error below — never a sweep of the ACTIVE account's drafts. + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const db = (storage as any).db; if (!db?.prepare) continue; diff --git a/apps/desktop/electron/ipc/email-handlers.ts b/apps/desktop/electron/ipc/email-handlers.ts index ec5b02f3..3af635cf 100644 --- a/apps/desktop/electron/ipc/email-handlers.ts +++ b/apps/desktop/electron/ipc/email-handlers.ts @@ -10,7 +10,7 @@ import { folderLogLabel, createDeferredFetchError, errorDiagnostic, fetchBodyQue import { app, ipcMain, dialog, shell, type IpcMainInvokeEvent } from 'electron'; import ICAL from 'ical.js'; -import { resolveAccountTarget, resolveNamedOrActiveAccountTarget, requireTargetAccountId } from '../services/account-target'; +import { resolveNamedOrActiveAccountTarget, requireTargetAccountId } from '../services/account-target'; import { getAntivirusScanService } from '../services/antivirus-scan-service'; import { attachmentErrorMessage, MAX_ATTACHMENT_BYTES, readCachedAttachment, resolveAttachmentFile } from '../services/attachment-cache'; import { AttachmentDownloadProtection, downloadScanners, setAttachmentOperationProtection, writeProtectedAttachment } from '../services/attachment-download-protection'; @@ -743,7 +743,7 @@ export function registerEmailHandlers(): void { deferBodyPrefetch(); // Unified view: read/fetch from the email's own account (DB + engine). - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1236,7 +1236,7 @@ export function registerEmailHandlers(): void { params: { query: ParsedSearchQuery; folderId?: string; accountId?: string; maxFetch?: number }, ) => { try { - const { storage, syncEngine } = await resolveAccountTarget(params.accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(params.accountId); if (!syncEngine) return { success: false, error: 'No sync engine for account' }; if (typeof (syncEngine as any).serverSearch !== 'function') { return { success: false, error: 'Server search unsupported' }; @@ -1271,7 +1271,7 @@ export function registerEmailHandlers(): void { ipcMain.handle('emails:markRead', async (_event, emailId: string, read: boolean, accountId?: string) => { try { // Route to the row's own account (unified view) or the active one. - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1325,7 +1325,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:markStarred', async (_event, emailId: string, starred: boolean, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1417,7 +1417,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToFolder', async (_event, emailId: string, destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const res = await moveOrCopyOne(storage, syncEngine, emailId, destinationFolderId, 'move'); if (!res.ok) return { success: false, error: res.error }; // Recount once. Await so the renderer's follow-up loadFolders() reads fresh @@ -1434,7 +1434,7 @@ export function registerEmailHandlers(): void { /** Restore tagged Trash members to Inbox, including rows whose primary copy is elsewhere. */ ipcMain.handle('emails:restoreFromTrash', async (_event, emailIds: string[], accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const data = await restoreEmailsFromTrash(storage, syncEngine, emailIds); return { success: data.failedIds.length === 0, data }; } catch (error) { @@ -1449,7 +1449,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:copyToFolder', async (_event, emailId: string, destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const res = await moveOrCopyOne(storage, syncEngine, emailId, destinationFolderId, 'copy'); if (!res.ok) return { success: false, error: res.error }; try { await storage.recalculateFolderCounts(); } catch (err) { logger.error('[email-handlers] recalculateFolderCounts failed:', err); } @@ -1463,7 +1463,7 @@ export function registerEmailHandlers(): void { /** Bulk Move / Copy many emails to one destination folder (toolbar/bulk-bar picker). */ ipcMain.handle('emails:bulkMoveToFolder', async (_event, emailIds: string[], destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); let moved = 0; for (const id of emailIds) { const res = await moveOrCopyOne(storage, syncEngine, id, destinationFolderId, 'move'); @@ -1479,7 +1479,7 @@ export function registerEmailHandlers(): void { ipcMain.handle('emails:bulkCopyToFolder', async (_event, emailIds: string[], destinationFolderId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); let copied = 0; for (const id of emailIds) { const res = await moveOrCopyOne(storage, syncEngine, id, destinationFolderId, 'copy'); @@ -1496,7 +1496,7 @@ export function registerEmailHandlers(): void { /** Mailbox storage quota (bytes) for the account, or null when unavailable. */ ipcMain.handle('account:getQuota', async (_event, accountId?: string) => { try { - const { syncEngine } = await resolveAccountTarget(accountId); + const { syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const quota = syncEngine ? await syncEngine.getQuota() : null; return { success: true, data: quota }; } catch (error) { @@ -1510,7 +1510,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToTrash', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1583,7 +1583,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveToSpam', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const outcome = await applyUserSpamVerdict({ storage, queue: (syncEngine as any)?.operationQueue ?? null, @@ -1609,7 +1609,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:moveFromSpam', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const outcome = await applyUserSpamVerdict({ storage, queue: (syncEngine as any)?.operationQueue ?? null, @@ -1627,7 +1627,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:archive', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1694,7 +1694,7 @@ export function registerEmailHandlers(): void { */ ipcMain.handle('emails:delete', async (_event, emailId: string, accountId?: string) => { try { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) { @@ -1832,10 +1832,11 @@ export function registerEmailHandlers(): void { if (typeof emailId !== 'string' || !emailId) { return { success: false, error: 'Invalid emailId' }; } - // Route to the email's OWNING account (falls back to active). In All + // Route to the email's OWNING account (the active one when none is named; + // a named one that cannot be resolved is an error). In All // Inboxes the opened mail can belong to a non-active account, so // requireStorage() (active account) missed it → "Email not found". - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) return { success: false, error: 'Email not found' }; @@ -1891,7 +1892,7 @@ export function registerEmailHandlers(): void { return await downloads.operations.run(emailId, targetAccountId, 'calendar-event.ics', async operation => { // Owning-account routing — otherwise "Add to calendar" on an All-Inboxes // mail from a non-active account failed with "Email not found". - const { storage, syncEngine } = await resolveAccountTarget(targetAccountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(targetAccountId); await operation.assertCurrent(); const email = await storage.getEmail(emailId); await operation.assertCurrent(); @@ -1958,7 +1959,7 @@ export function registerEmailHandlers(): void { return { success: false, error: 'Invalid emailId' }; } // Owning-account routing so the persisted flag lands in the RIGHT DB. - const { storage } = await resolveAccountTarget(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); await storage.updateEmail(emailId, { calendarAdded: Boolean(added) }); return { success: true }; } catch (error) { diff --git a/apps/desktop/electron/ipc/image-trust-handlers.ts b/apps/desktop/electron/ipc/image-trust-handlers.ts index dd606e85..edbc3aa2 100644 --- a/apps/desktop/electron/ipc/image-trust-handlers.ts +++ b/apps/desktop/electron/ipc/image-trust-handlers.ts @@ -6,8 +6,9 @@ * Every channel takes an optional `accountId`. The reading pane can show a * message of an account that is not the active one (the unified "All Inboxes" * view), and "Load images" on it must be remembered in THAT account's database - * — a sender address exists in every mailbox, so the lenient resolver's - * fall-back-to-active would silently file account B's choice under account A. + * — a sender address exists in every mailbox, so a fall-back-to-active (what + * the since-removed lenient resolver did) would silently file account B's + * choice under account A. * A named account is therefore resolved strictly (an unknown one is an error * the renderer sees and retries); no id means the active account, as before. */ diff --git a/apps/desktop/electron/ipc/index.ts b/apps/desktop/electron/ipc/index.ts index e32c9140..a93e491f 100644 --- a/apps/desktop/electron/ipc/index.ts +++ b/apps/desktop/electron/ipc/index.ts @@ -13,6 +13,7 @@ import { registerAIHandlers } from './ai-handlers'; import { registerAntivirusHandlers } from './antivirus-handlers'; import { registerAppHandlers } from './app-handlers'; import { registerCalendarHandlers } from './calendar-handlers'; +import { registerCertificateHandlers } from './certificate-handlers'; import { registerContactEnrichmentHandlers } from './contact-enrichment-handlers'; import { registerContactsHandlers } from './contacts-handlers'; import { registerDefaultAppHandlers } from './default-app-handlers'; @@ -75,6 +76,7 @@ export function registerAllHandlers(): void { registerLabelHandlers(); registerAccountsHandlers(); registerSecureCredentialsHandlers(); + registerCertificateHandlers(); registerNotificationHandlers(); registerStorageHandlers(); registerIdentityHandlers(); diff --git a/apps/desktop/electron/ipc/label-handlers.ts b/apps/desktop/electron/ipc/label-handlers.ts index df5427ed..3fb4a5ae 100644 --- a/apps/desktop/electron/ipc/label-handlers.ts +++ b/apps/desktop/electron/ipc/label-handlers.ts @@ -9,38 +9,24 @@ import { failureCause, labelLogLabel, createLogger, type LabelInput } from '@sarvinbox/core'; import { ipcMain } from 'electron'; -import { ensureAccountRuntime } from '../services/accounts-runtime'; +import { resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { setEmailLabel } from '../services/email-labels'; -import { requireStorage, getCurrentAccountId, getSyncEngine } from '../shared'; +import { requireStorage } from '../shared'; const logger = createLogger('label-handlers'); -// Labels live in each account's own DB. Resolve the target account's storage so -// the unified "All Inboxes" view can list/create labels for the account a -// message actually belongs to, not just the active one. -async function labelStorageFor(accountId?: string) { - if (accountId && accountId !== getCurrentAccountId()) { - const rt = await ensureAccountRuntime(accountId); - if (rt?.storage) return rt.storage; - } - return requireStorage(); -} - -// The sync engine for the label's account — used to mirror an opt-in label to -// the server. Active account uses the live engine; a foreign account uses its -// runtime's engine (which may not be connected — caller handles that). -async function labelEngineFor(accountId?: string) { - if (accountId && accountId !== getCurrentAccountId()) { - const rt = await ensureAccountRuntime(accountId); - return rt?.syncEngine ?? null; - } - return getSyncEngine(); -} +// Labels live in each account's own DB. Resolve the target account's storage +// (and engine, to mirror an opt-in label to the server) so the unified "All +// Inboxes" view can list/create labels for the account a message actually +// belongs to, not just the active one. STRICT: a label is keyed by its name, +// which can exist in every account, so a named account that cannot be resolved +// is an error the renderer sees — never a label listed from, created in, or +// tagged onto the ACTIVE mailbox instead. No id means the active account. export function registerLabelHandlers(): void { ipcMain.handle('labels:list', async (_event, accountId?: string) => { try { - const storage = await labelStorageFor(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); return { success: true, data: await storage.getLabels() }; } catch (error) { return { success: false, error: (error as Error).message }; @@ -49,7 +35,9 @@ export function registerLabelHandlers(): void { ipcMain.handle('labels:create', async (_event, input: LabelInput, accountId?: string) => { try { - const storage = await labelStorageFor(accountId); + // The engine belongs to the same account; it may not be connected — + // handled below. + const { storage, syncEngine: engine } = await resolveNamedOrActiveAccountTarget(accountId); const name = (input?.name || '').trim(); if (!name) return { success: false, error: 'Label name is required' }; // Opt-in: also CREATE the label as a folder on the mail server so it shows @@ -58,7 +46,6 @@ export function registerLabelHandlers(): void { let syncedToServer = false; if (input?.syncToServer) { try { - const engine = await labelEngineFor(accountId); if (engine?.isConnected?.()) { syncedToServer = await engine.createServerLabel(name); } else { @@ -102,10 +89,9 @@ export function registerLabelHandlers(): void { ipcMain.handle('emails:setLabel', async (_event, emailId: string, label: string, on: boolean, accountId?: string) => { try { // Route to the email's own account (unified "All Inboxes" rows can belong - // to a non-active account) so the tag is written to the right DB. - const storage = accountId && accountId !== getCurrentAccountId() - ? ((await ensureAccountRuntime(accountId))?.storage ?? requireStorage()) - : requireStorage(); + // to a non-active account) so the tag is written to the right DB — and + // only there: an unavailable named account is an error, not the active DB. + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); if (!(label || '').trim()) return { success: false, error: 'Label is required' }; if (await setEmailLabel(storage, emailId, label, on) === 'missing') return { success: false, error: 'Email not found' }; return { success: true }; diff --git a/apps/desktop/electron/ipc/pgp-handlers.ts b/apps/desktop/electron/ipc/pgp-handlers.ts index 8ce7bfe4..8cdeea94 100644 --- a/apps/desktop/electron/ipc/pgp-handlers.ts +++ b/apps/desktop/electron/ipc/pgp-handlers.ts @@ -12,22 +12,28 @@ import { writeFile } from 'fs/promises'; import path from 'path'; -import { createLogger, waitForAbortableOperation } from '@sarvinbox/core'; -import { PGP_ENCRYPTED_PLACEHOLDER, PgpKeyError } from '@sarvinbox/core/pgp'; +import { createLogger, errorDiagnostic, waitForAbortableOperation } from '@sarvinbox/core'; +import { PGP_ENCRYPTED_PLACEHOLDER, PGP_FAILURE_MESSAGE, type PgpFlowCode } from '@sarvinbox/core/pgp'; import { dialog, ipcMain } from 'electron'; -import { requireTargetAccountId, resolveAccountTarget } from '../services/account-target'; +import { requireTargetAccountId, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { attachmentScanRequired, getAttachmentOperationProtection, writeProtectedAttachment, type ProtectedAttachmentOperation } from '../services/attachment-download-protection'; import { markDownloadedFromInternet } from '../services/mark-downloaded'; -import { pgpUserMessage } from '../services/pgp-failure'; -import { PgpKeyringError, type PgpKeyring } from '../services/pgp-keyring'; -import { PgpReader, type StoredSource } from '../services/pgp-reader'; +import { lockedSigningKeyFor, logPgpFailure, pgpFlowCode } from '../services/pgp-failure'; +import type { PgpKeyring } from '../services/pgp-keyring'; +import { PgpReader, pgpOpenFailure, type StoredSource } from '../services/pgp-reader'; import { getPgpKeyring, readPgpPrefsFromSettings } from '../services/pgp-service'; import { getExtensionManager, getMainWindow } from '../shared'; const logger = createLogger('pgp-handlers'); -export type PgpIpcResult = { success: true; data: T } | { success: false; error: string; code?: string }; +/** + * A key operation's answer. On failure `error` is PGP_FAILURE_MESSAGE for + * every OpenPGP cause (CASA 4.1.4) — PGP_FILE_WRITE_FAILED_MESSAGE is the one + * other sentence, for a key file the filesystem would not write — and `code` + * is set only for a prompt the renderer may open (see PgpFlowCode). + */ +export type PgpIpcResult = { success: true; data: T } | { success: false; error: string; code?: PgpFlowCode }; export interface PgpComposeDefaults { /** The From address has a usable key of its own — encrypting and signing are possible. */ @@ -61,40 +67,44 @@ export interface PgpHandlerDeps { const ok = (data: T): PgpIpcResult => ({ success: true, data }); /** - * A refusal of this layer's own — a missing argument, a file that would not - * write — whose sentence the user reads as written. Everything else a key - * operation throws that is not one of our typed OpenPGP errors is the - * library's (or the platform's) own account, and the renderer never sees it. + * A request the renderer sent without what it needs (a key, a passphrase, an + * address). It is answered like every other OpenPGP failure; its code is for + * the log. */ class PgpRequestError extends Error { - constructor(message: string) { - super(message); + readonly code = 'missing-argument'; + constructor() { + super(PGP_FAILURE_MESSAGE); this.name = 'PgpRequestError'; } } -/** - * What the renderer reads when a key operation fails for a reason that is not - * ours: openpgp.js refusing a key the user imported, generating one, or - * re-protecting one for a backup. The library's reason is logged (CASA 4.1.4). - */ -export const PGP_REQUEST_FAILED_MESSAGE = 'The OpenPGP operation could not be completed.'; - /** What a key backup or public-key export says when the chosen file cannot be written. */ export const PGP_FILE_WRITE_FAILED_MESSAGE = 'The file could not be saved. Choose another location and try again.'; /** - * A key operation's failure, for the renderer. Our own sentences keep their - * words — a keyring or key refusal its code too, so the UI can ask for the - * passphrase, and a keychain refusal (SealError) its guidance; anything else - * is logged and answered with {@link PGP_REQUEST_FAILED_MESSAGE}. + * The chosen key file would not write. Not an OpenPGP failure — the user can + * pick another folder — so it keeps its own sentence. + */ +class PgpFileWriteError extends Error { + constructor() { + super(PGP_FILE_WRITE_FAILED_MESSAGE); + this.name = 'PgpFileWriteError'; + } +} + +/** + * A key operation's failure, for the renderer: PGP_FAILURE_MESSAGE whatever + * the cause (CASA 4.1.4) — a key that will not read, a wrong passphrase, a + * public key imported as private, a keychain that will not open, an + * openpgp.js error, a missing argument — plus a code only for a prompt + * (`locked`, `passphrase-required`). The log gets the class and code. */ const failure = (error: unknown): PgpIpcResult => { - if (error instanceof PgpRequestError) return { success: false, error: error.message }; - const message = pgpUserMessage(error, PGP_REQUEST_FAILED_MESSAGE, logger, 'OpenPGP request failed'); - return error instanceof PgpKeyringError || error instanceof PgpKeyError - ? { success: false, error: message, code: error.code } - : { success: false, error: message }; + if (error instanceof PgpFileWriteError) return { success: false, error: PGP_FILE_WRITE_FAILED_MESSAGE }; + logPgpFailure(logger, 'OpenPGP request failed', error); + const code = pgpFlowCode(error); + return code ? { success: false, error: PGP_FAILURE_MESSAGE, code } : { success: false, error: PGP_FAILURE_MESSAGE }; }; /** @@ -102,9 +112,10 @@ const failure = (error: unknown): PgpIpcResult => { * worded it ("Download blocked: …", "Download cancelled."). Those sentences * are the user's guidance, and no OpenPGP operation runs in a save: the * plaintext was decrypted, and its errors mapped, when the message was opened. + * The log gets the error's class and code — a write error's text names the path. */ const saveFailure = (error: unknown): PgpIpcResult => { - logger.warn(`OpenPGP request failed: ${(error as Error)?.message ?? String(error)}`); + logger.warn('OpenPGP attachment save failed', errorDiagnostic(error)); return { success: false, error: (error as Error)?.message ?? String(error) }; }; @@ -118,8 +129,8 @@ const guarded = } }; -const requireText = (value: unknown, what: string): string => { - if (typeof value !== 'string' || !value.trim()) throw new PgpRequestError(`${what} is required`); +const requireText = (value: unknown): string => { + if (typeof value !== 'string' || !value.trim()) throw new PgpRequestError(); return value; }; @@ -149,7 +160,7 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { // Not an OpenPGP failure, so not the vague OpenPGP sentence: the user can // pick another folder. The code only — fs messages carry the path. logger.warn(`Could not write an OpenPGP key file (${(error as NodeJS.ErrnoException)?.code ?? 'error'})`); - throw new PgpRequestError(PGP_FILE_WRITE_FAILED_MESSAGE); + throw new PgpFileWriteError(); } return { saved: true as const, filePath }; }; @@ -160,36 +171,36 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { 'pgp:generateKey': guarded((input: { name?: string; email?: string; passphrase?: string }) => deps.keyring().generateOwnKey({ name: typeof input?.name === 'string' ? input.name.trim() : '', - email: requireText(input?.email, 'An email address').trim(), + email: requireText(input?.email).trim(), passphrase: input?.passphrase || undefined, }), ), 'pgp:importOwnKey': guarded((armored: string, passphrase?: string) => - deps.keyring().importOwnKey(requireText(armored, 'A key'), passphrase || undefined), + deps.keyring().importOwnKey(requireText(armored), passphrase || undefined), ), 'pgp:unlock': guarded((fingerprint: string, passphrase: string) => - deps.keyring().unlockOwnKey(requireText(fingerprint, 'A key'), requireText(passphrase, 'A passphrase')), + deps.keyring().unlockOwnKey(requireText(fingerprint), requireText(passphrase)), ), 'pgp:exportOwnKey': guarded(async (fingerprint: string, passphrase: string) => { - const armored = await deps.keyring().exportOwnKey(requireText(fingerprint, 'A key'), passphrase); + const armored = await deps.keyring().exportOwnKey(requireText(fingerprint), passphrase); return saveTo(keyFileName(fingerprint, 'secret'), armored, ASC_FILTER); }), 'pgp:exportPublicKey': guarded((fingerprint: string) => - saveTo(keyFileName(fingerprint, 'public'), deps.keyring().exportOwnPublicKey(requireText(fingerprint, 'A key')), ASC_FILTER), + saveTo(keyFileName(fingerprint, 'public'), deps.keyring().exportOwnPublicKey(requireText(fingerprint)), ASC_FILTER), ), 'pgp:deleteOwnKey': guarded((fingerprint: string) => { - const deleted = deps.keyring().deleteOwnKey(requireText(fingerprint, 'A key')); + const deleted = deps.keyring().deleteOwnKey(requireText(fingerprint)); // What that key opened must not stay readable. deps.reader.forget(); return deleted; }), 'pgp:setSignByDefault': guarded((fingerprint: string, on: boolean) => - deps.keyring().setSignByDefault(requireText(fingerprint, 'A key'), on === true), + deps.keyring().setSignByDefault(requireText(fingerprint), on === true), ), 'pgp:listContactKeys': guarded(() => deps.keyring().listContactKeys()), - 'pgp:importContactKeys': guarded((armored: string) => deps.keyring().importContactKeys(requireText(armored, 'A key'))), + 'pgp:importContactKeys': guarded((armored: string) => deps.keyring().importContactKeys(requireText(armored))), 'pgp:deleteContactKey': guarded((email: string, fingerprint: string) => - deps.keyring().deleteContactKey(requireText(email, 'An address'), requireText(fingerprint, 'A key')), + deps.keyring().deleteContactKey(requireText(email), requireText(fingerprint)), ), 'pgp:resolveRecipients': guarded((emails: unknown) => deps.keyring().resolveRecipients( @@ -197,6 +208,13 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { { discover: true }, ), ), + // The composer's unlock prompt asks whether the key for the address it + // sends as is still locked — `locked` is the one cause it may know (a + // prompt); every other answer is false, and the send decides. + 'pgp:signingKeyLocked': guarded( + async (fromEmail: string) => + (await lockedSigningKeyFor({ encrypt: false, sign: true }, typeof fromEmail === 'string' ? fromEmail : '', deps.keyring)) === 'locked', + ), 'pgp:composeDefaults': guarded(async (fromEmail: string): Promise => { const ring = deps.keyring(); const from = typeof fromEmail === 'string' ? fromEmail : ''; @@ -205,14 +223,15 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { : [null, false]; return { hasOwnKey: ownKey !== null, signByDefault: ownKey !== null && signByDefault, autoEncrypt: deps.autoEncrypt() }; }), - // Returns the reader's own result shape: a refusal ("locked", "no-key") is - // a state the reader shows, not an IPC failure. + // Returns the reader's own result shape: a refusal ("locked", "failed") is + // a state the reader shows, not an IPC failure. A missing id reads like + // any other failure to open. 'pgp:open': async (emailId: string, accountId?: string) => { - if (typeof emailId !== 'string' || !emailId) return { ok: false, code: 'unavailable', error: 'No message' } as const; + if (typeof emailId !== 'string' || !emailId) return pgpOpenFailure(); return deps.reader.open(emailId, accountId); }, 'pgp:openDraft': async (emailId: string, accountId?: string) => { - if (typeof emailId !== 'string' || !emailId) return { ok: false, code: 'unavailable', error: 'No draft' } as const; + if (typeof emailId !== 'string' || !emailId) return pgpOpenFailure(); return deps.reader.openDraft(emailId, accountId); }, 'pgp:saveAttachment': guarded(async (emailId: string, accountId: string | undefined, index: number) => { @@ -251,7 +270,7 @@ export function createPgpHandlers(deps: PgpHandlerDeps) { /** The stored message's raw source and sender, from the account that owns it. */ export async function storedSourceFor(emailId: string, accountId?: string): Promise { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) return null; const fromAddress = email.fromAddress ?? null; diff --git a/apps/desktop/electron/ipc/smtp-handlers.ts b/apps/desktop/electron/ipc/smtp-handlers.ts index d47bcab9..34ac83be 100644 --- a/apps/desktop/electron/ipc/smtp-handlers.ts +++ b/apps/desktop/electron/ipc/smtp-handlers.ts @@ -7,18 +7,20 @@ import * as fs from 'fs'; import * as path from 'path'; -import { folderLogLabel, SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, withFolderSelected, messageIdKey, parseAddresses, STARTTLS_UNAVAILABLE, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; -import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; +import { folderLogLabel, SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, isCertificateUntrustedError, withFolderSelected, messageIdKey, parseAddresses, resolveConnectionSecurity, STARTTLS_UNAVAILABLE, CERTIFICATE_UNTRUSTED, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; +import { PGP_ENCRYPTED_PLACEHOLDER, PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, bodyLengthFromParam, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, dialog } from 'electron'; import { registryAccountEmail } from '../services/accounts-registry'; import { ensureAccountRuntime } from '../services/accounts-runtime'; import { seedAttachmentCache } from '../services/attachment-cache'; +import { applyCertificatePin, requestingWindow, withCertificateApproval, type CertificateTrustRequest } from '../services/certificate-trust'; import { CalendarInvitationValidationError, getLocalCalendarInvitationService } from '../services/local-calendar-invitations'; import { getAccessTokenForMailHost } from '../services/oauth-service'; import { getOutboxQueue, drainOutbox, getOutboxQueueForAccount, drainOutboxForAccount, notifyOutboxChanged } from '../services/outbox-service'; -import { sendTransformFor } from '../services/pgp-service'; +import { lockedSigningKeyFor } from '../services/pgp-failure'; +import { getPgpKeyring, sendTransformFor } from '../services/pgp-service'; import { pokeReadModel } from '../services/read-model-poke'; import { getPipelineUserName } from '../services/unified-pipeline-service'; import { narrowSavedTransport, resolveVaultPassword, vaultIdCandidates, vaultRefusalMessage, withSavedPassword, type VaultPasswordFound } from '../services/vault-credentials'; @@ -66,34 +68,59 @@ function getMimeType(filename: string): string { } /** - * A password-auth SMTP config with its password filled in from the vault. + * A password-auth SMTP config with its password filled in from the vault, and + * the certificate this account approved for its sending server (or none). * The renderer never holds stored passwords, so a saved account's config * arrives without one; main injects it — but only for the host it was saved * for, and no more loosely than it was saved for (vault-credentials.ts), since * the config comes from the renderer. `saved` is the vault hit, for * `narrowSavedTransport` once the connection works. - * Configs that already carry a password (the user just typed it) or use - * OAuth pass through unchanged. + * A config that already carries a password (the user just typed it) keeps it; + * OAuth gets no password and no pin. Every config leaves with exactly main's + * pin — the one SMTP entry point for both connect handlers. */ export async function withVaultSmtpPassword( config: SMTPConfig, accountId: string | undefined, ): Promise<{ config: SMTPConfig; saved?: VaultPasswordFound }> { - if (config.authMethod === 'oauth2' || config.password) return { config }; - const vaulted = await resolveVaultPassword(vaultIdCandidates(accountId, config.username, config.host), 'smtp', config.host); + const ids = vaultIdCandidates(accountId, config.username, config.host); + if (config.authMethod === 'oauth2' || config.password) return { config: await applyCertificatePin(config, 'smtp', ids) }; + const vaulted = await resolveVaultPassword(ids, 'smtp', config.host); if (vaulted.status !== 'found') { throw new Error(vaultRefusalMessage('smtp', config.host, vaulted) ?? `No sending password saved for ${config.host} — set up sending for this account.`); } const applied = withSavedPassword(config, 'smtp', vaulted); if ('refusal' in applied) throw new Error(applied.refusal); - return { config: applied.config, saved: vaulted }; + return { config: await applyCertificatePin(applied.config, 'smtp', ids), saved: vaulted }; +} + +/** + * Whom to ask when an ARMED SMTP connect was refused over its certificate, or + * null for OAuth. What the dialog says about the account comes from main's own + * records, never from this config. + */ +function smtpCertificateRequest(event: unknown, config: SMTPConfig, accountId: string | undefined): CertificateTrustRequest | null { + if (!config || config.authMethod === 'oauth2' || !config.host) return null; + return { + kind: 'smtp', + ids: vaultIdCandidates(accountId, config.username, config.host), + host: config.host, + port: config.port, + security: resolveConnectionSecurity(config), + window: requestingWindow(event), + }; } export function registerSmtpHandlers(): void { /** * Connect to SMTP server */ - ipcMain.handle('smtp:connect', async (_event, config: SMTPConfig, accountId?: string) => { + // Refused over the certificate (CASA 4.1.2): only a connect the user started + // from a form (armed) asks, in main's dialog, and on approval connects once + // more with the new pin — on the client of the account still on screen, or + // not at all. Startup and lazy-send connects get the refusal at once. + ipcMain.handle('smtp:connect', (event, original: SMTPConfig, accountId?: string) => withCertificateApproval(async () => { + let config = original; try { const vaulted = await withVaultSmtpPassword(config, accountId); config = vaulted.config; @@ -116,9 +143,9 @@ export function registerSmtpHandlers(): void { }; } - // Certificate checks are decided in core (resolveTlsOptions): on unless a - // password account opted out, and the opt-out of a saved password is the - // one saved with it (withVaultSmtpPassword). + // Certificate checks are decided in core (resolveTlsOptions): always on, + // and a pinned password account accepts exactly its approved certificate + // (withVaultSmtpPassword). await smtpClient.connect(config); logger.info('[SMTP] Connected successfully'); if (vaulted.saved) await narrowSavedTransport('smtp', vaulted.saved, config); @@ -132,13 +159,18 @@ export function registerSmtpHandlers(): void { if (isStarttlsRefusedError(error)) { return { success: false, error: (error as Error).message, code: STARTTLS_UNAVAILABLE }; } + // The sending server's certificate is not trusted (CASA 4.1.2); the + // client already said so in one line, before AUTH. + if (isCertificateUntrustedError(error)) { + return { success: false, error: (error as Error).message, code: CERTIFICATE_UNTRUSTED }; + } logger.error('SMTP connect error:', error); return { success: false, error: (error as Error).message, }; } - }); + }, () => smtpCertificateRequest(event, original, accountId), { sameTarget: () => getCurrentAccountId() })); /** * Disconnect from SMTP server @@ -185,11 +217,16 @@ export function registerSmtpHandlers(): void { // Connect a SPECIFIC account's SMTP on demand (multi-account send-as). The // renderer supplies the target account's SMTPConfig (main doesn't store it). // Idempotent: no-op if that account's client is already connected. - ipcMain.handle('smtp:connectFor', async (_event, accountId: string, config: SMTPConfig) => { + ipcMain.handle('smtp:connectFor', (event, accountId: string, config: SMTPConfig) => withCertificateApproval(async () => { try { if (!accountId || !config) return { success: false, error: 'accountId + config required' }; if (getSmtpClientFor(accountId)?.isConnected()) return { success: true }; - await ensureAccountRuntime(accountId); // ensure the runtime slot exists + // The runtime slot the client is stored in. Registry-checked: no slot + // (and no database) for an account that is not configured — and nothing + // connected or vault password read for it either. + if (!(await ensureAccountRuntime(accountId))) { + return { success: false, error: `Account ${accountId} is not available` }; + } const vaulted = await withVaultSmtpPassword(config, accountId); let cfg = vaulted.config; if (cfg.authMethod === 'oauth2') { @@ -204,10 +241,13 @@ export function registerSmtpHandlers(): void { drainOutboxForAccount(accountId).catch((e) => logger.warn('[SMTP] connectFor drain failed:', e)); return { success: true }; } catch (error) { + if (isCertificateUntrustedError(error)) { + return { success: false, error: (error as Error).message, code: CERTIFICATE_UNTRUSTED }; + } logger.error('[SMTP] connectFor error:', error); return { success: false, error: (error as Error).message }; } - }); + }, () => (accountId ? smtpCertificateRequest(event, config, accountId) : null))); ipcMain.handle('smtp:send', async (_event, options: SendEmailOptions) => { try { @@ -245,6 +285,22 @@ export function registerSmtpHandlers(): void { ? getOutboxQueueForAccount(accountId) : getOutboxQueue(); + // A send that asks to be signed with a key still locked this session is + // refused BEFORE it is queued, with the `locked` prompt code: the composer + // is still open to ask for the passphrase, and the queued send would only + // fail after the undo window. The From address is the one the send will + // write (sendEmailFromMain → SMTPClient.sendEmail): the chosen alias, else + // the sending account's SMTP identity — and, before that client is + // connected (no config yet, or a failed verify), the account's address. + const refuseLockedSend = async (options: SendEmailOptions) => { + const client = options.accountId && options.accountId !== getCurrentAccountId() ? getSmtpClientFor(options.accountId) : getSmtpClient(); + const config = client?.getConfig(); + const fromHeader = options.from || config?.from || config?.username || registryAccountEmail(options.accountId ?? getCurrentAccountId()); + return (await lockedSigningKeyFor(options.pgp, fromHeader, getPgpKeyring)) + ? { success: false as const, error: PGP_FAILURE_MESSAGE, code: 'locked' as const } + : null; + }; + // Persist-first undo-send: write the mail to the outbox NOW (durable), held for // the undo window. The renderer commits it when the window elapses, or cancels // it on Undo. A crash during the window can only DELAY delivery (the outbox @@ -252,6 +308,8 @@ export function registerSmtpHandlers(): void { // memory only, so a quit within 5s destroyed the whole email. ipcMain.handle('smtp:sendWithUndo', async (_event, options: SendEmailOptions, undoDelayMs: number) => { try { + const locked = await refuseLockedSend(options); + if (locked) return locked; const { id } = await queueFor(options.accountId).enqueueHeld(options, undoDelayMs); notifyOutboxChanged(); return { success: true, id }; @@ -284,6 +342,8 @@ export function registerSmtpHandlers(): void { */ ipcMain.handle('smtp:scheduleSend', async (_event, options: SendEmailOptions, sendAt: number) => { try { + const locked = await refuseLockedSend(options); + if (locked) return locked; const { id } = await queueFor(options.accountId).scheduleSend(options, sendAt); notifyOutboxChanged(); return { success: true, id }; @@ -491,6 +551,10 @@ export async function sendEmailFromMain( } } const scoped = !!acctId && acctId !== getCurrentAccountId(); + // Whose storage `scopedStorage` is, fixed NOW: the post-send draft cleanup + // runs after the network round-trip, and an account switch in between must + // not re-point it at whichever account became active meanwhile. + const sendingAccountId = scoped ? acctId! : getCurrentAccountId(); const smtpClient = scoped ? getSmtpClientFor(acctId!) : getSmtpClient(); const scopedStorage = scoped ? getStorageFor(acctId!) : getStorage(); const scopedSyncEngine = scoped ? getSyncEngineFor(acctId!) : getSyncEngine(); @@ -585,7 +649,7 @@ export async function sendEmailFromMain( try { const answeredThreadId = await markThreadRepliesAnswered(scopedStorage, options.inReplyTo); if (answeredThreadId) { - await deleteDraftsForThread(acctId, answeredThreadId); + await deleteDraftsForThread(sendingAccountId, answeredThreadId); } } catch (err) { logger.warn('[SMTP] Post-send thread cleanup (proposals/drafts) failed (non-fatal):', err); diff --git a/apps/desktop/electron/ipc/spam-handlers.ts b/apps/desktop/electron/ipc/spam-handlers.ts index dd526ef2..be5d7426 100644 --- a/apps/desktop/electron/ipc/spam-handlers.ts +++ b/apps/desktop/electron/ipc/spam-handlers.ts @@ -6,11 +6,18 @@ * section of the settings blob (Security > Blocklists), which main reads from * the core DB mirror and hears about through `appSettings:set` — see * reputation-service.ts. + * + * Every channel's optional `accountId` is resolved STRICTLY: a named account + * that cannot be resolved is an error the renderer sees, never the active + * mailbox. The trusted-sender list is keyed by a sender address, which exists + * in every mailbox, and a trusted sender's authenticated mail bypasses the + * filter — so a fallback would have switched the filter off for that sender in + * the wrong account. No id means the active account, as before. */ -import { SUSPICIOUS_THRESHOLD, createLogger, type SpamUserVerdict } from '@sarvinbox/core'; +import { SUSPICIOUS_THRESHOLD, accountLogLabel, createLogger, errorDiagnostic, type SpamUserVerdict } from '@sarvinbox/core'; import { ipcMain } from 'electron'; -import { resolveAccountTarget } from '../services/account-target'; +import { requireNamedOrActiveStorage, resolveNamedOrActiveAccountTarget } from '../services/account-target'; import { reportSenderVerdict } from '../services/reputation-service'; import { getSpamReputationState, kickSpamReputation } from '../services/spam-reputation-service'; import { applyUserSpamVerdict, trustSender, type VerdictDeps } from '../services/spam-verdict-actions'; @@ -26,7 +33,7 @@ export function verdictDepsOf(storage: VerdictDeps['storage'], syncEngine: unkno /** What a verdict needs for one account: its storage, its server queue, the report hook. */ async function verdictDepsFor(accountId?: string): Promise { - const { storage, syncEngine } = await resolveAccountTarget(accountId); + const { storage, syncEngine } = await resolveNamedOrActiveAccountTarget(accountId); return verdictDepsOf(storage, syncEngine); } @@ -41,7 +48,7 @@ export function registerSpamHandlers(): void { // Everything the filter had an opinion on — for the Security page's Spam tab. ipcMain.handle('spam:listJudged', async (_event, limit?: number, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); + const { storage } = await resolveNamedOrActiveAccountTarget(accountId); return { success: true, data: storage.getSpamJudgedEmails(typeof limit === 'number' ? limit : 200, SUSPICIOUS_THRESHOLD) }; } catch (error) { return fail(error); @@ -56,7 +63,7 @@ export function registerSpamHandlers(): void { const outcome = await applyUserSpamVerdict(deps, emailId, verdict); return outcome.success ? { success: true, data: { moved: outcome.moved } } : { success: false, error: outcome.error }; } catch (error) { - logger.error('spam:setUserVerdict failed:', error); + logger.error(`spam:setUserVerdict failed for account ${accountLogLabel(accountId, '(active)')}:`, errorDiagnostic(error)); return fail(error); } }); @@ -64,11 +71,11 @@ export function registerSpamHandlers(): void { // "Trust this sender": their authenticated mail bypasses the filter from now on. ipcMain.handle('spam:trustSender', async (_event, address: string, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - await trustSender(storage, address); + await trustSender(await requireNamedOrActiveStorage(accountId), address); return { success: true }; } catch (error) { - logger.error('spam:trustSender failed:', error); + // Class and code only: the message names the account (an address). + logger.error(`spam:trustSender failed for account ${accountLogLabel(accountId, '(active)')}:`, errorDiagnostic(error)); return fail(error); } }); @@ -76,16 +83,14 @@ export function registerSpamHandlers(): void { // The Security page's list, and its remove. ipcMain.handle('spam:listTrustedSenders', async (_event, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - return { success: true, data: await storage.getTrustedSenders() }; + return { success: true, data: await (await requireNamedOrActiveStorage(accountId)).getTrustedSenders() }; } catch (error) { return fail(error); } }); ipcMain.handle('spam:untrustSender', async (_event, address: string, accountId?: string) => { try { - const { storage } = await resolveAccountTarget(accountId); - await storage.untrustSender(address); + await (await requireNamedOrActiveStorage(accountId)).untrustSender(address); return { success: true }; } catch (error) { return fail(error); diff --git a/apps/desktop/electron/ipc/sync-handlers.ts b/apps/desktop/electron/ipc/sync-handlers.ts index bc199411..7324c877 100644 --- a/apps/desktop/electron/ipc/sync-handlers.ts +++ b/apps/desktop/electron/ipc/sync-handlers.ts @@ -5,15 +5,17 @@ */ import type { IMAPConfig, SyncEngineOptions } from '@sarvinbox/core'; -import { failureCause, folderLogLabel, accountLogLabel, withTimeout, transportOptInsOf, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, STARTTLS_UNAVAILABLE } from '@sarvinbox/core'; +import { failureCause, folderLogLabel, accountLogLabel, withTimeout, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isCertificateUntrustedError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, resolveConnectionSecurity, STARTTLS_UNAVAILABLE, CERTIFICATE_UNTRUSTED } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { identifyClient } from '../sentry'; +import { noteVerifiedAccount } from '../services/account-add-proof'; import { ensureAccountRuntime, accountInboxUnread, accountDbExists } from '../services/accounts-runtime'; // Static import (not require()): the bundled main.js has no on-disk services // file, so a runtime require() throws "Cannot find module". import { kickBackfillScheduler } from '../services/backfill-scheduler'; import { kickBodyPrefetchScheduler } from '../services/body-prefetch-scheduler'; +import { applyCertificatePin, requestingWindow, withCertificateApproval, type CertificateTrustRequest } from '../services/certificate-trust'; import { markConnectionUnstable } from '../services/connection-health'; import { saveImapAccount, loadImapAccount, clearImapAccount, forgetImapAccountFor } from '../services/imap-account-store'; import { getAccessTokenForMailHost, attachImapBearer } from '../services/oauth-service'; @@ -78,6 +80,25 @@ function resolveVaultImapPassword( return resolveVaultPassword(vaultIdCandidates(accountId, username, host), 'imap', host); } +/** + * Whom to ask when an ARMED IMAP connect was refused over its certificate (CASA + * 4.1.2), or null for OAuth, which never uses pins. The server and port are the + * ones the connect dialled, and a pin approved is bound to exactly them; what + * the dialog says about the account comes from main's own records, never from + * this config. + */ +function imapCertificateRequest(event: unknown, config: IMAPConfig, accountId: string | undefined): CertificateTrustRequest | null { + if (!config || config.authMethod === 'oauth2' || !config.host) return null; + return { + kind: 'imap', + ids: vaultIdCandidates(accountId, config.username, config.host), + host: config.host, + port: config.port, + security: resolveConnectionSecurity(config), + window: requestingWindow(event), + }; +} + /** * Resolve the vault password as a PROMISE that settles the instant the data is * available, then the caller proceeds — no fixed delay. At app launch the connect @@ -123,7 +144,7 @@ function resolveVaultImapPasswordWaiting( * Shared by the `imap:probeCredentials` IPC (gating account overwrites) and the * oauth2→password self-heal in `imap:connect`. */ -async function probeImapCredentials(config: IMAPConfig): Promise<{ success: boolean; error?: string }> { +async function probeImapCredentials(config: IMAPConfig): Promise<{ success: boolean; error?: string; code?: string }> { const client = new ImapFlowClient(); // A probe reports its outcome purely through connect()'s resolve/reject, so // silence the client's own error channel BEFORE connecting. This is not @@ -144,7 +165,8 @@ async function probeImapCredentials(config: IMAPConfig): Promise<{ success: bool } catch (error) { // Expected outcome for bad credentials — log at info, not error. logger.info('[Main] probeCredentials rejected:', (error as Error).message); - return { success: false, error: (error as Error).message }; + // An untrusted certificate is tagged, so the caller can offer it for review. + return { success: false, error: (error as Error).message, ...(isCertificateUntrustedError(error) ? { code: CERTIFICATE_UNTRUSTED } : {}) }; } finally { // Never leave the probe socket open, even when connect() threw midway. try { await client.disconnect(); } catch { /* nothing to tear down */ } @@ -372,7 +394,18 @@ export function registerSyncHandlers(): void { /** * Connect to IMAP server */ - ipcMain.handle('imap:connect', async (_event, config: IMAPConfig, accountId?: string) => { + // A connect refused over the server's certificate (CASA 4.1.2): when the + // user started it from a form (armed via certificates:review), main asks in + // its own dialog and, on approval, connects once more with the new pin — for + // the account still on screen, or not at all. Focus/online reconnects are not + // armed: they get the refusal at once, and the window points to the settings. + ipcMain.handle('imap:connect', (event, config: IMAPConfig, accountId?: string) => withCertificateApproval( + () => connectImap(config, accountId), + () => imapCertificateRequest(event, config, accountId), + { sameTarget: () => getCurrentAccountId() }, + )); + + async function connectImap(config: IMAPConfig, accountId?: string) { // App is shutting down — refuse to (re)establish connections. The renderer's // periodic timers keep firing during teardown; without this they resurrect // the IMAP connection AFTER we disconnected it, so the process can't settle. @@ -390,9 +423,11 @@ export function registerSyncHandlers(): void { // never runs and EVERY IPC fails "Storage not initialized" — the app bricks // despite the account's DB being safe on disk. The renderer still hands us // the accountId here, so activate it ourselves. Guarded by accountDbExists - // so we only REUSE an existing DB, never create a blank one. - if (!getSyncEngine() && accountId && accountDbExists(accountId)) { - await ensureAccountRuntime(accountId); + // so we only REUSE an existing DB, never create a blank one, and by the + // registry (inside ensureAccountRuntime) so a configured account's DB is + // the only one adopted. The pointer moves only once the runtime opened: + // an id that was refused must not leave main on an empty slot. + if (!getSyncEngine() && accountId && accountDbExists(accountId) && await ensureAccountRuntime(accountId)) { setCurrentAccount(accountId); logger.info(`[Main] imap:connect self-activated account ${accountLogLabel(accountId)} (storage was uninitialized)`); } @@ -508,6 +543,11 @@ export function registerSyncHandlers(): void { } } + // The certificate this account approved for this server, or none (normal + // verification) — never one the config arrived with. Applied to the ONE + // config that the primary, the pool and every reconnect dial with. + config = await applyCertificatePin(config, 'imap', vaultIdCandidates(accountId, config.username, config.host)); + // Never connect a password-auth account with no password. It fails with // "No password configured" AND connection-manager latches the config, so // every subsequent auto-reconnect re-hammers the same password-less config @@ -518,9 +558,9 @@ export function registerSyncHandlers(): void { return { success: false, error: 'Credentials not ready — will retry', retryable: true }; } - // Certificate checks are decided in core (resolveTlsOptions): on unless a - // password account opted out, and a saved password's opt-out is the one - // saved with it (above). attachImapBearer wires a fresh-token resolver for + // Certificate checks are decided in core (resolveTlsOptions): always on, + // and a pinned password account accepts exactly its approved certificate + // (above). attachImapBearer wires a fresh-token resolver for // OAuth so the pool + reconnects never authenticate with a token that // expired after pool init (no-op for password auth). This single config // flows into both connect() and initializePool(), and is what @@ -670,13 +710,14 @@ export function registerSyncHandlers(): void { } }); // The server stopped encrypting a STARTTLS account mid-session (CASA - // M-5): reconnects have stopped. Tell the renderer what to change. The + // M-5), or now presents a certificate the account does not trust (CASA + // 4.1.2): reconnects have stopped. Tell the renderer what to change. The // saved config is KEPT — the credentials were never rejected. syncEngine.onSecurityError((error) => { if (!isActiveEngine()) return; const win = getMainWindow(); if (win && !win.isDestroyed()) { - win.webContents.send('imap:security-error', error.message); + win.webContents.send('imap:security-error', error.message, isCertificateUntrustedError(error) ? CERTIFICATE_UNTRUSTED : STARTTLS_UNAVAILABLE); } }); } @@ -717,12 +758,12 @@ export function registerSyncHandlers(): void { password: (config as any).password ?? '', authMethod: config.authMethod, oauthProvider: config.oauthProvider, - // Connection security and the self-signed opt-in are part of the - // account: dropping them here made a recovered 'none' account dial - // as STARTTLS-required, and a self-signed one fail verification. - // What was actually used, not what the request asked for. + // Connection security is part of the account: dropping it here made + // a recovered 'none' account dial as STARTTLS-required. What was + // actually used, not what the request asked for. An approved + // certificate is not kept here: it lives with the saved credentials + // and is applied by main on every connect. security: config.security, - allowInsecureTLS: transportOptInsOf(config).allowInsecureTLS, }).catch((e) => logger.error('[Main] saveImapAccount failed:', e)); } @@ -748,6 +789,13 @@ export function registerSyncHandlers(): void { logger.warn(`[Main] connect refused — STARTTLS is required for ${config.host} but the server did not encrypt the session`); return { success: false, error: (error as Error).message, retryable: false, code: STARTTLS_UNAVAILABLE }; } + // The server's certificate is not trusted (CASA 4.1.2): settled until the + // user approves one, never parked as a blip; the password was never sent. + // The wrapper around this handler offers the certificate for review. + if (isCertificateUntrustedError(error)) { + logger.warn(`[Main] connect refused — the incoming server's certificate is not trusted for ${accountLogLabel(accountId ?? getCurrentAccountId() ?? undefined)}`); + return { success: false, error: (error as Error).message, retryable: false, code: CERTIFICATE_UNTRUSTED }; + } logger.error('IMAP connect error:', error); const quotaKey = accountId ?? getCurrentAccountId(); // Quota ("too many simultaneous connections"): tear our engine down so a @@ -772,7 +820,7 @@ export function registerSyncHandlers(): void { retryable: parked.reason !== null, }; } - }); + } /** * Prove a candidate set of credentials can actually authenticate, WITHOUT @@ -788,7 +836,12 @@ export function registerSyncHandlers(): void { * "can THESE credentials connect?". OAuth is the one exception: the renderer * never holds tokens, so we resolve it from the main-process store here. */ - ipcMain.handle('imap:probeCredentials', async (_event, config: IMAPConfig) => { + // + // A password probe dials with the certificate approved for the account it is + // about to become (`accountId`, from the add-account flow), and an untrusted + // certificate is offered for review here — the probe is a new account's first + // connect, so this is where a self-signed server is first approved. + ipcMain.handle('imap:probeCredentials', (event, config: IMAPConfig, accountId?: string) => withCertificateApproval(async () => { let probeConfig = config; if (config.authMethod === 'oauth2') { if (!config.oauthProvider) { @@ -803,8 +856,14 @@ export function registerSyncHandlers(): void { return { success: false, error: (error as Error).message }; } } - return probeImapCredentials(probeConfig); - }); + probeConfig = await applyCertificatePin(probeConfig, 'imap', vaultIdCandidates(accountId, config.username, config.host)); + const probe = await probeImapCredentials(probeConfig); + // Main's own proof that this address signed in: the one thing that lets + // accounts:setActive open a database for an account not yet in the + // registry (the add flow). See account-add-proof. + if (probe.success) noteVerifiedAccount(config.username, config.host); + return probe; + }, () => imapCertificateRequest(event, config, accountId))); /** * Disconnect from IMAP server @@ -1283,7 +1342,12 @@ export function registerSyncHandlers(): void { // The active account is untouched (it has its own IDLE). New-email events from // this sync flow through the shared emitter but are filtered out by the active // idle-bridge's belongsToActive guard, so they never disturb the active view. - ipcMain.handle('accounts:backgroundSync', async (_event, opts: { accountId: string; config: IMAPConfig }) => { + // Background sync never asks about a certificate (CASA 4.1.2): a refusal + // comes back at once, tagged, and is reviewed from Settings → Accounts. An + // unanswered dialog can never hold a background cycle either. + ipcMain.handle('accounts:backgroundSync', (_event, opts: { accountId: string; config: IMAPConfig }) => backgroundSync(opts)); + + async function backgroundSync(opts: { accountId: string; config: IMAPConfig }) { if (getIsQuitting()) return { success: true, data: { skipped: true } }; const { accountId, config } = opts ?? ({} as { accountId: string; config: IMAPConfig }); // Unread for the "All Inboxes" badge / account switcher — INBOX distinct-thread @@ -1315,6 +1379,8 @@ export function registerSyncHandlers(): void { return { success: true, data: { unread: await totalUnread(getStorageFor(accountId) ?? getStorage()), skipped: true } }; } + // Registry-checked inside: an account that is not configured (a removed + // one the renderer's timer still names) gets no runtime and no database. const rt = await ensureAccountRuntime(accountId); if (!rt?.storage || !rt.syncEngine) return { success: false, error: 'Runtime unavailable' }; const engine = rt.syncEngine; @@ -1377,6 +1443,8 @@ export function registerSyncHandlers(): void { bgSaved = vaulted; } } + // The account's approved certificate for this server, or none. + cfg = await applyCertificatePin(cfg, 'imap', vaultIdCandidates(accountId, cfg.username, cfg.host)); // Don't connect password-less (fails "No password configured" and latches // that config for auto-reconnect to hammer). Skip this cycle; the next // background tick retries once the vault is readable. @@ -1448,6 +1516,12 @@ export function registerSyncHandlers(): void { // aborts/closes it so it releases back to the server instead of leaking. try { await getSyncEngineFor(accountId)?.disconnect?.(); } catch { /* best effort */ } + // An untrusted certificate (CASA 4.1.2): settled, never parked as a blip. + if (isCertificateUntrustedError(error)) { + logger.warn(`[Accounts] backgroundSync: the incoming server's certificate is not trusted for ${accountLogLabel(accountId)}`); + return { success: false, error: (error as Error).message, retryable: false, code: CERTIFICATE_UNTRUSTED }; + } + // "Too many simultaneous connections" (or a connect timeout, usually the // same saturated condition) — park this account via the shared back-off so // the next cycles (and the active-account path) don't keep hammering the @@ -1464,5 +1538,5 @@ export function registerSyncHandlers(): void { logger.warn('[Accounts] backgroundSync failed for', accountLogLabel(accountId), (error as Error).message); return { success: false, error: (error as Error).message }; } - }); + } } diff --git a/apps/desktop/electron/ipc/unsubscribe-handlers.ts b/apps/desktop/electron/ipc/unsubscribe-handlers.ts index 3d181f3d..6c4410dc 100644 --- a/apps/desktop/electron/ipc/unsubscribe-handlers.ts +++ b/apps/desktop/electron/ipc/unsubscribe-handlers.ts @@ -12,13 +12,15 @@ * * `one-click` — RFC 8058. A POST from here, no browser, nothing shown to * the sender beyond the request itself. * * `page` — the sender's own form, opened in the default browser - * through the app's existing scheme allow-list. + * through the external-link gate, which names the sender's host in a + * warning before anything opens (the address is the sender's choice). * * `mailto` — an ordinary message through the outbox, so it is durable, * retried and visible in Sent exactly like any other mail. */ import { createLogger, resolveUnsubscribeAction, type UnsubscribeRoute } from '@sarvinbox/core'; -import { ipcMain, shell } from 'electron'; +import { ipcMain } from 'electron'; +import { openExternalUrl, windowOfSender } from '../services/external-link-gate'; import { getOutboxQueue, getOutboxQueueForAccount, notifyOutboxChanged } from '../services/outbox-service'; import { postOneClick } from '../services/unsubscribe-service'; import { getCurrentAccountId, getStorageFor, requireStorage } from '../shared'; @@ -31,6 +33,8 @@ export interface UnsubscribeRunResult { route?: UnsubscribeRoute; /** True when the reader still has something to do (a browser form is open). */ needsBrowser?: boolean; + /** The reader chose Cancel on the link warning: nothing opened, nothing failed. */ + cancelled?: boolean; error?: string; } @@ -39,7 +43,7 @@ const ROUTES: ReadonlySet = new Set(['one-click', 'pag export function registerUnsubscribeHandlers(): void { ipcMain.handle( 'unsubscribe:run', - async (_event, emailId: string, route: UnsubscribeRoute, accountId?: string): Promise => { + async (event, emailId: string, route: UnsubscribeRoute, accountId?: string): Promise => { if (typeof emailId !== 'string' || !emailId || !ROUTES.has(route)) { return { success: false, error: 'Unsupported unsubscribe request' }; } @@ -68,7 +72,9 @@ export function registerUnsubscribeHandlers(): void { } if (action.kind === 'page') { - await shell.openExternal(action.url); + const outcome = await openExternalUrl(action.url, windowOfSender(event)); + if (outcome === 'cancelled') return { success: false, cancelled: true }; + if (outcome !== 'opened') return { success: false, error: "The sender's unsubscribe page could not be opened" }; logger.info(`[Unsubscribe] opened the sender's page for ${emailId}`); return { success: true, route, needsBrowser: true }; } diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index cdb37c45..3c88ac75 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -24,7 +24,7 @@ import { pathToFileURL } from 'url'; 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'; +import { app, BrowserWindow, Menu, dialog, ipcMain, powerMonitor, protocol, session } from 'electron'; import { registerAllHandlers } from './ipc'; import { sendEmailFromMain, appendSentCopy } from './ipc/smtp-handlers'; @@ -40,11 +40,8 @@ import { } from './services/accounts-registry'; import { PRIMARY_DB_FILE, - ensureAccountRuntime, + activatePersistedAccount, loadPrimaryAccountId, - savePrimaryAccountId, - legacyDbExists, - accountDbExists, cleanupOrphanedAccountDbs, cleanupStaleUserDataArtifacts, } from './services/accounts-runtime'; @@ -88,10 +85,12 @@ import { import { createSandboxChannel, SANDBOX_SCHEME_PRIVILEGES } from './services/extension-runtime'; import { createExtensionUIBackend, noteWindowGone } from './services/extension-ui-backend'; import { startExtensionWorkflowRunner, stopExtensionWorkflowRunner } from './services/extension-workflow-runner'; +import { openExternalUrl } from './services/external-link-gate'; import { getExternalOpenService } from './services/external-open-service'; import { wireFolderCountBroadcast } from './services/folder-count-broadcast'; import { startFollowUpChecker, stopFollowUpChecker } from './services/follow-up-checker'; import { startHeaderBackfill, stopHeaderBackfill } from './services/header-backfill'; +import { useSystemHostResolver } from './services/host-resolver'; import { startLocalCalendarReminders, stopLocalCalendarReminders } from './services/local-calendar-reminders'; import { initializeLocalDataReset, isLocalDataResetRestarting } from './services/local-data-reset'; import { offerMoveToApplications } from './services/mac-install-location'; @@ -155,8 +154,6 @@ import { setSystemSuspended, getAccountIdForStorage, sendToWindow, - setCurrentAccount, - hasAccountRuntime, } from './shared'; import { resolveAppIconPath } from './utils/app-icon'; import { devServerUrlFor, isDevBuild, isReleaseBundle } from './utils/dev-mode'; @@ -165,7 +162,7 @@ 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 { installNavigationGuards, installWindowOpenGuard } from './utils/navigation-guards'; import { installPermissionPolicy } from './utils/permission-policy'; import { restoreAndFocusWindow } from './utils/window-focus'; import { appJsFlags } from './v8-flags'; @@ -576,19 +573,18 @@ function createWindow(): void { mainWindow.loadFile(APP_ENTRY_FILE); } - // Open all external links in the default browser - mainWindow.webContents.setWindowOpenHandler(({ url }) => { - if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('mailto:')) { - shell.openExternal(url); - } - return { action: 'deny' }; - }); + // Every web address that leaves this window — a window-open request (an + // email's target="_blank" link) or a navigation the policy sends to the + // browser — goes through the external-link gate, which warns before an + // untrusted host (CASA 5.1.2). Never shell.openExternal directly. + const leaveWindow = { + openExternal: (url: string) => openExternalUrl(url, mainWindow), + warn: (message: string, ...args: unknown[]) => logger.warn(message, ...args), + }; + installWindowOpenGuard(mainWindow.webContents, leaveWindow); // Both navigation guards share one decision (electron/utils/navigation-policy.ts). - installNavigationGuards(mainWindow.webContents, APP_URL, { - openExternal: (url) => shell.openExternal(url), - warn: (message, ...args) => logger.warn(message, ...args), - }); + installNavigationGuards(mainWindow.webContents, APP_URL, leaveWindow); mainWindow.once('ready-to-show', () => { mainWindow.show(); @@ -752,22 +748,9 @@ async function initializeAccountRegistry(): Promise { const activeId = getRegistryActiveAccountId(); if (!activeId) return; - // Mirror accounts:setActive's legacy-adopt rule: the FIRST account to - // activate claims the existing sarvinbox.db (only when it already exists); - // fresh installs never create it and use per-id DBs. - if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(activeId); - - // Only activate when the account's DB can be resolved — the recorded primary - // (legacy sarvinbox.db) or an existing per-id DB. Never spin up a blank - // mailbox for an id whose data isn't on disk. - const isPrimary = loadPrimaryAccountId() === activeId && legacyDbExists(); - if (!isPrimary && !accountDbExists(activeId)) { - logger.info('[Main] Persisted active account has no DB yet — deferring to renderer:', accountLogLabel(activeId)); - return; - } - - setCurrentAccount(activeId); - if (!hasAccountRuntime(activeId)) await ensureAccountRuntime(activeId); + // Registry-checked, and the pointer moves only once the runtime is open: + // see activatePersistedAccount. + if (!(await activatePersistedAccount(activeId))) return; rebindOutboxStorage(); logger.info('[Main] Auto-activated persisted account:', accountLogLabel(activeId)); } catch (e) { @@ -1042,6 +1025,11 @@ app.whenReady().then(async () => { // down, so this guard is what actually prevents the duplicate footprint. if (!gotSingleInstanceLock) return; try { + // First, before anything can make a request: Chromium resolves names + // through the OS, not by sending DNS packets to a server that may be on the + // local network (macOS would ask for Local Network access). See host-resolver.ts. + useSystemHostResolver(app, logger); + // PROD: now that we own the lock, publish our liveness heartbeat so the NEXT // launch can tell us apart from a wedged primary (see evaluateLockContention). // Stopped + removed on teardown. Dev has no lock, so no heartbeat. diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index ce58e161..00d828fe 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -15,6 +15,7 @@ import type { InboxAgentChangeSetRequest } from '../src/types/inbox-assistant-ch import type { LocalCalendarAPI, LocalCalendarAvailability, LocalCalendarOpenEvent } from '../src/types/local-calendar'; import type { LocalDataAPI } from '../src/types/local-data'; import type { SecureStorageAccessResult, SecureStorageStatus } from '../src/types/secure-storage'; +import type { AttachmentScannerSummary, ScannerConnectionTest } from '../src/utils/attachment-scan-failures'; import type { PgpComposeDefaults, PgpIpcResult } from './ipc/pgp-handlers'; @@ -53,6 +54,21 @@ interface SecureAccountSecrets { smtp?: { password?: string; accessToken?: string; refreshToken?: string; host?: string }; } +/** An approved mail-server certificate as the account settings show it (CASA 4.1.2). */ +interface ApprovedCertificate { + host: string; + port: number; + /** SHA-256 fingerprint, Node's colon-separated form. */ + sha256: string; + approvedAt: number; + subject: string; + issuer: string; + validTo: string; +} + +/** Why a connect was refused before any credential was sent. */ +type SecurityRefusalCode = 'STARTTLS_UNAVAILABLE' | 'CERTIFICATE_UNTRUSTED'; + interface AntivirusConfigureRequest { challenge: string; allowedAccountIds: string[]; @@ -186,6 +202,9 @@ contextBridge.exposeInMainWorld('electronAPI', { app: { getVersion: () => ipcRenderer.invoke('app:version'), openExternal: (url: string) => ipcRenderer.invoke('app:openExternal', url), + // The Translate menu item: the text and target language only — main builds the address. + openTranslation: (text: string, targetLanguage: string) => + ipcRenderer.invoke('app:openTranslation', text, targetLanguage), }, // Appearance. The renderer owns the setting (it lives in localStorage, mirrored @@ -260,7 +279,7 @@ contextBridge.exposeInMainWorld('electronAPI', { // IMAP operations imap: { connect: (config: IMAPConfig, accountId?: string) => ipcRenderer.invoke('imap:connect', config, accountId), - probeCredentials: (config: IMAPConfig) => ipcRenderer.invoke('imap:probeCredentials', config), + probeCredentials: (config: IMAPConfig, accountId?: string) => ipcRenderer.invoke('imap:probeCredentials', config, accountId), disconnect: () => ipcRenderer.invoke('imap:disconnect'), getSavedConfig: () => ipcRenderer.invoke('imap:getSavedConfig'), clearSavedConfig: () => ipcRenderer.invoke('imap:clearSavedConfig'), @@ -327,9 +346,10 @@ contextBridge.exposeInMainWorld('electronAPI', { removeAuthErrorListener: () => { ipcRenderer.removeAllListeners('imap:auth-error'); }, - /** A STARTTLS account's server stopped encrypting mid-session (CASA M-5). */ - onSecurityError: (callback: (message: string) => void) => { - ipcRenderer.on('imap:security-error', (_e, message: string) => callback(message)); + /** Reconnects stopped before sending anything: a STARTTLS account's server + * stopped encrypting (CASA M-5), or its certificate is not trusted (4.1.2). */ + onSecurityError: (callback: (message: string, code: SecurityRefusalCode) => void) => { + ipcRenderer.on('imap:security-error', (_e, message: string, code?: SecurityRefusalCode) => callback(message, code ?? 'STARTTLS_UNAVAILABLE')); }, removeSecurityErrorListener: () => { ipcRenderer.removeAllListeners('imap:security-error'); @@ -504,6 +524,10 @@ contextBridge.exposeInMainWorld('electronAPI', { removeLinkRule: (id: number) => ipcRenderer.invoke('security:removeLinkRule', id), getHeaderBackfillState: () => ipcRenderer.invoke('security:getHeaderBackfillState'), kickHeaderBackfill: () => ipcRenderer.invoke('security:kickHeaderBackfill'), + // The sites the user chose "Don't ask again" for on the link warning: a + // count and "Forget all". The hosts never cross this bridge. + getRememberedLinkSites: () => ipcRenderer.invoke('security:getRememberedLinkSites'), + forgetRememberedLinkSites: () => ipcRenderer.invoke('security:forgetRememberedLinkSites'), onHeaderBackfillProgress: (cb: (state: HeaderBackfillState) => void) => { const listener = (_e: unknown, state: HeaderBackfillState) => cb(state); ipcRenderer.on('header-backfill:progress', listener); @@ -524,6 +548,8 @@ contextBridge.exposeInMainWorld('electronAPI', { configure: (extensionId: string, config: AntivirusConfigureRequest) => ipcRenderer.invoke('antivirus:configure', extensionId, config), disable: (extensionId: string) => ipcRenderer.invoke('antivirus:disable', extensionId), + listScanners: () => ipcRenderer.invoke('antivirus:listScanners'), + testConnection: (extensionId: string) => ipcRenderer.invoke('antivirus:testConnection', extensionId), getPendingUnscannedWarning: () => ipcRenderer.invoke('antivirus:getPendingUnscannedWarning'), respondUnscannedWarning: (response: UnscannedWarningResponse) => ipcRenderer.invoke('antivirus:respondUnscannedWarning', response), getUnscannedWarningPreferences: () => ipcRenderer.invoke('antivirus:getUnscannedWarningPreferences'), @@ -698,6 +724,7 @@ contextBridge.exposeInMainWorld('electronAPI', { deleteContactKey: (email: string, fingerprint: string) => ipcRenderer.invoke('pgp:deleteContactKey', email, fingerprint), resolveRecipients: (emails: string[]) => ipcRenderer.invoke('pgp:resolveRecipients', emails), composeDefaults: (fromEmail: string) => ipcRenderer.invoke('pgp:composeDefaults', fromEmail), + signingKeyLocked: (fromEmail: string) => ipcRenderer.invoke('pgp:signingKeyLocked', fromEmail), open: (emailId: string, accountId?: string) => ipcRenderer.invoke('pgp:open', emailId, accountId), openDraft: (emailId: string, accountId?: string) => ipcRenderer.invoke('pgp:openDraft', emailId, accountId), saveAttachment: (emailId: string, accountId: string | undefined, index: number) => @@ -783,10 +810,10 @@ contextBridge.exposeInMainWorld('electronAPI', { upsertCategoryDefinition: (def: any) => ipcRenderer.invoke('ai:upsertCategoryDefinition', def), deleteCategoryDefinition: (slug: string) => ipcRenderer.invoke('ai:deleteCategoryDefinition', slug), toggleCategoryDefinition: (slug: string, enabled: boolean) => ipcRenderer.invoke('ai:toggleCategoryDefinition', slug, enabled), - getThreadSummary: (threadId: string) => - ipcRenderer.invoke('ai:getThreadSummary', threadId), - saveThreadSummary: (summary: any) => - ipcRenderer.invoke('ai:saveThreadSummary', summary), + getThreadSummary: (threadId: string, accountId?: string) => + ipcRenderer.invoke('ai:getThreadSummary', threadId, accountId), + saveThreadSummary: (summary: any, accountId?: string) => + ipcRenderer.invoke('ai:saveThreadSummary', summary, accountId), // First-email split cache — every call names its account (never the active one by default). getFirstSplit: (accountId: string, threadId: string, options?: { withSource?: boolean }) => ipcRenderer.invoke('ai:firstSplit:get', accountId, threadId, options), @@ -870,7 +897,7 @@ contextBridge.exposeInMainWorld('electronAPI', { // Multi-account: flip the active account (main resolves storage/sync/SMTP to it) accounts: { - setActive: (accountId: string) => ipcRenderer.invoke('accounts:setActive', accountId), + setActive: (accountId: string, options?: { adding?: boolean }) => ipcRenderer.invoke('accounts:setActive', accountId, options), rekey: (oldId: string, newId: string) => ipcRenderer.invoke('accounts:rekey', oldId, newId), remove: (accountId: string) => ipcRenderer.invoke('accounts:remove', accountId), // Durable DB-backed registry (source of truth). list → hydrate on startup; @@ -919,6 +946,15 @@ contextBridge.exposeInMainWorld('electronAPI', { requestAccess: () => ipcRenderer.invoke('secureCreds:requestAccess'), }, + // Approved mail-server certificates (CASA 4.1.2). Read and remove only: + // approving one happens in main's own dialog, during a connect the user + // started from a form (which the form announces with `review`). + certificates: { + list: (accountId: string) => ipcRenderer.invoke('certificates:list', accountId), + remove: (accountId: string, kind: 'imap' | 'smtp') => ipcRenderer.invoke('certificates:remove', accountId, kind), + review: (accountId: string, kind: 'imap' | 'smtp') => ipcRenderer.invoke('certificates:review', accountId, kind), + }, + // New-mail OS notifications. The renderer pushes the live config (mode, sound, // per-account notify flags, current view); the main process owns the firing. // onOpenEmail wires a notification CLICK back to open that mail. @@ -1362,7 +1398,16 @@ export interface ElectronAPI { inboxAssistant: InboxAssistantAPI; app: { getVersion: () => Promise<{ success: boolean; data?: string; error?: string }>; - openExternal: (url: string) => Promise<{ success: boolean; error?: string }>; + /** + * Open a URL in the browser through main's external-link gate, which warns + * before an untrusted host. `cancelled`: the user chose Cancel. + */ + openExternal: (url: string) => Promise<{ success: boolean; cancelled?: boolean; error?: string }>; + /** + * Translate a message's text in Google Translate. Main builds the address + * from the text (at most TRANSLATE_MAX_CHARS) and the target language. + */ + openTranslation: (text: string, targetLanguage: string) => Promise<{ success: boolean; error?: string }>; }; appearance: { setZoomFactor: (factor: number) => void; @@ -1402,11 +1447,15 @@ export interface ElectronAPI { /** `healedAuthMethod` is set when main repaired an account that was marked * oauth2 but whose server rejected the token; persist it to make it stick. */ /** `code` 'STARTTLS_UNAVAILABLE': a STARTTLS account's server would not - * encrypt; `error` says what the user can change. */ - connect: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; healedAuthMethod?: 'password'; code?: 'STARTTLS_UNAVAILABLE' }>; + * encrypt; 'CERTIFICATE_UNTRUSTED': its certificate is not approved (main + * asked only if the connect was armed with certificates.review). `error` + * says what the user can do. */ + connect: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; healedAuthMethod?: 'password'; code?: SecurityRefusalCode }>; /** Verify credentials against the server without touching the active - * connection or any stored account. Used to gate account overwrites. */ - probeCredentials: (config: IMAPConfig) => Promise<{ success: boolean; error?: string }>; + * connection or any stored account. Used to gate account overwrites. + * `accountId` is the account these settings are for (or will be), whose + * approved certificate the probe uses. */ + probeCredentials: (config: IMAPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; disconnect: () => Promise<{ success: boolean; error?: string }>; getSavedConfig: () => Promise<{ success: boolean; data?: any; error?: string }>; clearSavedConfig: () => Promise<{ success: boolean; error?: string }>; @@ -1439,7 +1488,7 @@ export interface ElectronAPI { removeReconnectingListener: () => void; onAuthError: (callback: () => void) => void; removeAuthErrorListener: () => void; - onSecurityError: (callback: (message: string) => void) => void; + onSecurityError: (callback: (message: string, code: SecurityRefusalCode) => void) => void; removeSecurityErrorListener: () => void; }; folders: { @@ -1544,6 +1593,10 @@ export interface ElectronAPI { removeLinkRule: (id: number) => Promise<{ success: boolean; error?: string }>; getHeaderBackfillState: () => Promise<{ success: boolean; data?: HeaderBackfillState; error?: string }>; kickHeaderBackfill: () => Promise<{ success: boolean; data?: HeaderBackfillState; error?: string }>; + /** How many sites open from a link without the warning ("Don't ask again"). */ + getRememberedLinkSites: () => Promise<{ success: boolean; data?: { count: number }; error?: string }>; + /** Forget them all; answers the count read back afterwards. */ + forgetRememberedLinkSites: () => Promise<{ success: boolean; data?: { count: number }; error?: string }>; /** Subscribe to backfill progress. Returns an unsubscribe fn. */ onHeaderBackfillProgress: (cb: (state: HeaderBackfillState) => void) => () => void; }; @@ -1562,6 +1615,10 @@ export interface ElectronAPI { probe: (extensionId: string, endpoint: string, credential?: string) => Promise<{ success: boolean; data?: AntivirusProbeResult; error?: string }>; configure: (extensionId: string, config: AntivirusConfigureRequest) => Promise<{ success: boolean; data?: AntivirusSetupStatus; error?: string }>; disable: (extensionId: string) => Promise<{ success: boolean; data?: AntivirusSetupStatus; error?: string }>; + /** Scanner extensions that are turned on, each with its last failed scan this session. */ + listScanners: () => Promise<{ success: boolean; data?: AttachmentScannerSummary[]; error?: string }>; + /** Read-only check of the saved scanner setup; never returns the credential. */ + testConnection: (extensionId: string) => Promise<{ success: boolean; data?: ScannerConnectionTest; error?: string }>; getPendingUnscannedWarning: () => Promise<{ success: boolean; data?: UnscannedWarningRequest | null; error?: string }>; respondUnscannedWarning: (response: UnscannedWarningResponse) => Promise<{ success: boolean; error?: string }>; getUnscannedWarningPreferences: () => Promise<{ success: boolean; data?: { suppressedAccountIds: string[] }; error?: string }>; @@ -1664,16 +1721,18 @@ export interface ElectronAPI { }; smtp: { /** `code` 'STARTTLS_UNAVAILABLE': the sending server would not encrypt a - * STARTTLS account; `error` says what the user can change. */ - connect: (config: SMTPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: 'STARTTLS_UNAVAILABLE' }>; - connectFor: (accountId: string, config: SMTPConfig) => Promise<{ success: boolean; error?: string }>; + * STARTTLS account; 'CERTIFICATE_UNTRUSTED': its certificate is not + * approved. `error` says what the user can do. */ + connect: (config: SMTPConfig, accountId?: string) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; + connectFor: (accountId: string, config: SMTPConfig) => Promise<{ success: boolean; error?: string; code?: SecurityRefusalCode }>; disconnect: () => Promise<{ success: boolean; error?: string }>; isConnected: () => Promise<{ success: boolean; data?: boolean; error?: string }>; send: (options: SendEmailOptions) => Promise<{ success: boolean; queued?: boolean; messageId?: string; error?: string }>; - sendWithUndo: (options: SendEmailOptions, undoDelayMs: number) => Promise<{ success: boolean; id?: number; error?: string }>; + /** `code` 'locked': the send asked to be signed with a key still locked this session; nothing was queued. */ + sendWithUndo: (options: SendEmailOptions, undoDelayMs: number) => Promise<{ success: boolean; id?: number; error?: string; code?: 'locked' }>; commitSend: (id: number, accountId?: string) => Promise<{ success: boolean; failed?: number; deferred?: boolean }>; cancelSend: (id: number, accountId?: string) => Promise<{ success: boolean; cancelled: boolean; error?: string }>; - scheduleSend: (options: SendEmailOptions, sendAt: number) => Promise<{ success: boolean; id?: number; error?: string }>; + scheduleSend: (options: SendEmailOptions, sendAt: number) => Promise<{ success: boolean; id?: number; error?: string; code?: 'locked' }>; rescheduleSend: (id: number, sendAt: number, accountId?: string) => Promise<{ success: boolean; moved: boolean; error?: string }>; }; unsubscribe: { @@ -1681,7 +1740,7 @@ export interface ElectronAPI { emailId: string, route: 'one-click' | 'page' | 'mailto', accountId?: string, - ) => Promise<{ success: boolean; route?: 'one-click' | 'page' | 'mailto'; needsBrowser?: boolean; error?: string }>; + ) => Promise<{ success: boolean; route?: 'one-click' | 'page' | 'mailto'; needsBrowser?: boolean; cancelled?: boolean; error?: string }>; }; pgp: { status: () => Promise>; @@ -1698,6 +1757,8 @@ export interface ElectronAPI { deleteContactKey: (email: string, fingerprint: string) => Promise>; resolveRecipients: (emails: string[]) => Promise>; composeDefaults: (fromEmail: string) => Promise>; + /** Whether the key for this From address is locked this session — the composer's unlock prompt re-checks with it. */ + signingKeyLocked: (fromEmail: string) => Promise>; open: (emailId: string, accountId?: string) => Promise; openDraft: (emailId: string, accountId?: string) => Promise; saveAttachment: (emailId: string, accountId: string | undefined, index: number) => Promise>; @@ -1764,9 +1825,16 @@ export interface ElectronAPI { Promise<{ success: boolean; data?: { deleted: boolean }; error?: string }>; toggleCategoryDefinition: (slug: string, enabled: boolean) => Promise<{ success: boolean; error?: string }>; - getThreadSummary: (threadId: string) => + /** + * The cached summary of a thread, in the account that owns it (the + * active one when `accountId` is omitted). Thread ids repeat across + * accounts, so a named account that cannot be resolved fails rather than + * answering from the active account's cache. + */ + getThreadSummary: (threadId: string, accountId?: string) => Promise<{ success: boolean; data?: ThreadSummaryRecord | null; error?: string }>; - saveThreadSummary: (summary: any) => + /** Cache a summary in the account that owns the thread — strictly, as above. */ + saveThreadSummary: (summary: any, accountId?: string) => Promise<{ success: boolean; error?: string }>; /** * The first-email split cache row plus main's CURRENT key for the thread @@ -1859,7 +1927,13 @@ export interface ElectronAPI { discardAll: () => Promise<{ success: boolean; data?: { removed: number }; error?: string }>; }; accounts: { - setActive: (accountId: string) => Promise<{ success: boolean; error?: string }>; + /** + * Point main at a configured account. `adding: true` only from the add + * flow, whose new account is not in the registry until its first connect + * succeeds; any other id the registry does not list is refused + * (`success: false`) and main stays where it was. + */ + setActive: (accountId: string, options?: { adding?: boolean }) => Promise<{ success: boolean; error?: string }>; rekey: (oldId: string, newId: string) => Promise<{ success: boolean; error?: string }>; /** * `revocation` (OAuth accounts only): what happened to the grant at the @@ -1894,6 +1968,14 @@ export interface ElectronAPI { status: () => Promise<{ success: boolean; data?: SecureStorageStatus; error?: string }>; requestAccess: () => Promise<{ success: boolean; data?: SecureStorageAccessResult; error?: string }>; }; + certificates: { + list: (accountId: string) => Promise<{ success: boolean; data?: { imap?: ApprovedCertificate; smtp?: ApprovedCertificate }; error?: string }>; + remove: (accountId: string, kind: 'imap' | 'smtp') => Promise<{ success: boolean; data?: { removed: boolean }; error?: string }>; + /** The user just started a connect for this account's `kind` server from a + * form: that connect may ask (in main) about an untrusted certificate. + * Rate-limited; `armed` false when asked again too soon. */ + review: (accountId: string, kind: 'imap' | 'smtp') => Promise<{ success: boolean; data?: { armed: boolean }; error?: string }>; + }; notifications: { setConfig: (config: unknown) => Promise<{ success: boolean; error?: string }>; /** `supported: false` = the OS reports notifications unavailable for the app. */ diff --git a/apps/desktop/electron/services/__testing__/fake-core-db.ts b/apps/desktop/electron/services/__testing__/fake-core-db.ts index c9fc0b87..4eb0d5dd 100644 --- a/apps/desktop/electron/services/__testing__/fake-core-db.ts +++ b/apps/desktop/electron/services/__testing__/fake-core-db.ts @@ -214,6 +214,13 @@ export function setBlob(key: string, data: Buffer): void { state.blobs.set(key, Buffer.from(data)); } +/** The throwing write (core-db's `writeBlob`); fails like setBlob under `failBlobWrite`. */ +export function writeBlob(key: string, data: Buffer): void { + if (!key) throw new Error('A blob needs a key'); + if (state.failBlobWrite) throw new Error('fake core-db: writeBlob failed'); + state.blobs.set(key, Buffer.from(data)); +} + export function deleteBlob(key: string): void { state.blobs.delete(key); } diff --git a/apps/desktop/electron/services/account-add-proof.ts b/apps/desktop/electron/services/account-add-proof.ts new file mode 100644 index 00000000..90b8555f --- /dev/null +++ b/apps/desktop/electron/services/account-add-proof.ts @@ -0,0 +1,52 @@ +/** + * Main's own proof that an account being ADDED really signed in. + * + * `accounts:setActive` opens (and creates) a mailbox database only for an + * account the registry lists — except while one is being added: the add flow + * points main at the new account before its first connect, and the renderer + * writes the registry row only once that connect succeeds. That exception used + * to rest on the renderer's word alone (`{ adding: true }`), so any id could be + * activated unregistered, any number of times, each one a new database, an + * open storage and a sync engine nobody closed. + * + * Now the exception needs a proof main recorded itself: a successful + * `imap:probeCredentials` for that address and host. Every add path probes + * first — `addAccount` itself, and the onboarding steps that pass + * `alreadyVerified` (email setup, Sarv sign-in) probe just before. A proof + * names exactly one account id (`accountIdFor(username, host)`, the id the add + * flow mints), is good for one activation, and expires. + */ +import { accountIdFor } from '@sarvinbox/core'; + +/** How long after its probe an add may still activate the new account. */ +export const ADD_PROOF_TTL_MS = 10 * 60_000; +/** Proofs kept at once; the oldest goes first. Bounded: they are cheap, but not free. */ +const MAX_PROOFS = 16; + +/** account id → when its probe succeeded. Memory only: a proof never outlives the process. */ +const proofs = new Map(); + +/** Record that `username` on `host` just signed in (a successful probe). */ +export function noteVerifiedAccount(username: unknown, host: unknown, now: number = Date.now()): void { + if (typeof username !== 'string' || typeof host !== 'string' || !username.trim() || !host.trim()) return; + const id = accountIdFor(username, host); + proofs.delete(id); // re-insert as the newest + proofs.set(id, now); + while (proofs.size > MAX_PROOFS) proofs.delete(proofs.keys().next().value as string); +} + +/** + * Whether `accountId` has an unused, unexpired proof — and USE it: a proof + * admits one activation. An expired one is dropped either way. + */ +export function takeVerifiedAccount(accountId: string, now: number = Date.now()): boolean { + const at = proofs.get(accountId); + if (at === undefined) return false; + proofs.delete(accountId); + return now - at >= 0 && now - at <= ADD_PROOF_TTL_MS; +} + +/** Forget every proof. Tests only. */ +export function clearVerifiedAccounts(): void { + proofs.clear(); +} diff --git a/apps/desktop/electron/services/account-target.ts b/apps/desktop/electron/services/account-target.ts index 656b5853..f2bd5a5e 100644 --- a/apps/desktop/electron/services/account-target.ts +++ b/apps/desktop/electron/services/account-target.ts @@ -7,26 +7,16 @@ import { getCurrentAccountId, } from '../shared'; -import { readRegistryAccounts } from './accounts-registry'; +import { isRegisteredAccountId } from './accounts-registry'; import { ensureAccountRuntime } from './accounts-runtime'; type AccountStorage = ReturnType; type AccountSyncEngine = ReturnType; -/** - * Is `accountId` one of the configured accounts? Read with the THROWING - * registry reader: an unreadable registry and an empty one are the same value - * and opposite facts, so "could not find out" must surface as an error, never - * as "not registered" (nor as "registered"). - */ -function isRegisteredAccount(accountId: string): boolean { - return readRegistryAccounts().some((account) => account.id === accountId); -} - /** Resolve a download's owner once, without falling back from a named mailbox. */ export function requireTargetAccountId(accountId?: string): string { const target = accountId === undefined ? getCurrentAccountId() : accountId; - if (typeof target !== 'string' || !target || !isRegisteredAccount(target)) { + if (typeof target !== 'string' || !target || !isRegisteredAccountId(target)) { throw new Error('The attachment account is unavailable. Select its mailbox and try again.'); } return target; @@ -34,26 +24,21 @@ export function requireTargetAccountId(accountId?: string): string { /** * The storage + sync engine of one SPECIFIC, non-active account: its open - * runtime, or one opened now. Null when the account cannot be resolved (unknown, - * held for maintenance, primary not established yet). The one lookup both - * resolvers below share, so the lenient and the strict answer can never - * disagree about which database an account id names. + * runtime, or — only when the registry lists it — one opened now. Null when + * the account cannot be resolved (unknown or removed, held for maintenance, + * primary not established yet). A registry that cannot be read throws. * - * `strict` opens a runtime only for an account the registry lists. - * `ensureAccountRuntime` creates a new, migrated, EMPTY database (plus a sync - * engine and a registered runtime) for any id it is handed — so a removed - * account's id arriving late (a background request queued before the account - * was deleted) would recreate a blank mailbox under the dead id, which then - * joins every all-accounts loop. A registry that cannot be read throws. + * The registry is checked HERE as well as inside `ensureAccountRuntime`, so + * this module's promise ("never a database created for an id that is not + * configured") does not rest on a check two modules away. */ async function lookupAccountRuntime( accountId: string, - { strict = false }: { strict?: boolean } = {}, ): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine } | null> { let storage = getStorageFor(accountId); let syncEngine = getSyncEngineFor(accountId); if (!storage) { - if (strict && !isRegisteredAccount(accountId)) return null; + if (!isRegisteredAccountId(accountId)) return null; const rt = await ensureAccountRuntime(accountId); storage = rt?.storage ?? null; syncEngine = rt?.syncEngine ?? null; @@ -62,48 +47,40 @@ async function lookupAccountRuntime( } /** - * Resolve the storage + sync engine for an operation, honoring a per-row - * `accountId` when acting on a message from the unified "All Inboxes" view (whose - * rows can belong to non-active accounts). Falls back to the active account when - * no accountId is given (the normal single-account path). Ensures the target - * account's runtime exists first, so we never silently hit the wrong DB — the - * root cause of the mark-read "Email not found" loop across accounts. + * Resolve an operation's storage and sync engine, honoring a per-row + * `accountId` (the unified "All Inboxes" view shows rows of non-active + * accounts). With no id, or the active account's id, it is the active account + * (the single-account path). A NAMED account must resolve to its own runtime: + * an unknown, removed or unavailable one is an error the caller sees, NEVER a + * fall back to the active mailbox. + * + * There used to be a lenient twin that fell back to the active account. For an + * email-id key that only turned into "Email not found" (email ids are random + * per insert, so another account's id is in no other database) — but thread + * ids, Message-IDs, sender addresses, label and folder names exist in EVERY + * account's database, and on that fallback "trust this sender" bypassed the + * spam filter in the wrong mailbox, a discard deleted the active account's + * drafts of the same conversation, and a label was created in the wrong + * mailbox. No flow needed the fallback, so it is gone; every caller resolves + * strictly. * - * LENIENT: an account that cannot be resolved also falls back to the active - * one. Anything that WRITES data keyed by ids that exist in every account (a - * thread id is derived from headers, so the same one lives in each account's - * database) must use {@link requireAccountStorage} instead. + * `accountId` in the result says whose storage it is: the named account, or + * the active account's id (null on the pre-account default slot) — what + * per-account stores (the attachment cache, draft meeting metadata) key by. * * Lives here rather than in the IPC module because the `sarv-attachment://` * protocol handler needs the same resolution and must not import the IPC layer. */ -export async function resolveAccountTarget( - accountId?: string, -): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine; accountId: string | null }> { - if (accountId && accountId !== getCurrentAccountId()) { - const found = await lookupAccountRuntime(accountId); - if (found) return { ...found, accountId }; - } - // `accountId` says whose storage this is after the fallback (null on the - // pre-account default slot) — what per-account stores key by. - return { storage: requireStorage(), syncEngine: getSyncEngine(), accountId: getCurrentAccountId() }; -} - -/** - * Resolve a mutation's storage and sync engine. A named account must resolve - * to its own runtime; an unavailable or removed account is an error instead - * of a fallback to the active mailbox. Requests without an id use the active - * account, preserving the single-account path. - */ export async function resolveNamedOrActiveAccountTarget( - accountId?: string, -): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine }> { - if (!accountId || accountId === getCurrentAccountId()) { - return { storage: requireStorage(), syncEngine: getSyncEngine() }; + accountId?: string | null, +): Promise<{ storage: AccountStorage; syncEngine: AccountSyncEngine; accountId: string | null }> { + const activeId = getCurrentAccountId(); + if (!accountId || accountId === activeId) { + return { storage: requireStorage(), syncEngine: getSyncEngine(), accountId: activeId }; } - const found = await lookupAccountRuntime(accountId, { strict: true }); + const found = await lookupAccountRuntime(accountId); if (!found) throw new Error(`Account ${accountId} is not available`); - return found; + return { ...found, accountId }; } /** @@ -116,18 +93,17 @@ export async function resolveNamedOrActiveAccountTarget( * * anything else (an unknown or removed account, maintenance, no id) → * throws; an unreadable registry throws too. * - * The lenient {@link resolveAccountTarget} falls back to the active account, - * which is right for a click on a row and wrong for a cache keyed by thread id: - * the same thread id exists in every account's database, so a fallback would - * silently read account A's cached split for account B's thread, or write B's - * result into A's database. A failed lookup has to be an error the caller sees. + * A cache keyed by thread id is why: the same thread id exists in every + * account's database, so a fallback would silently read account A's cached + * split for account B's thread, or write B's result into A's database. A + * failed lookup has to be an error the caller sees. */ export async function requireAccountStorage(accountId: string): Promise { if (typeof accountId !== 'string' || accountId === '') { throw new Error('requireAccountStorage: an account id is required'); } if (accountId === getCurrentAccountId()) return requireStorage(); - const found = await lookupAccountRuntime(accountId, { strict: true }); + const found = await lookupAccountRuntime(accountId); if (!found) throw new Error(`Account ${accountId} is not available`); return found.storage; } @@ -138,10 +114,9 @@ export async function requireAccountStorage(accountId: string): Promise { return accountId ? requireAccountStorage(accountId) : requireStorage(); diff --git a/apps/desktop/electron/services/accounts-registry.ts b/apps/desktop/electron/services/accounts-registry.ts index cd053e45..74ea2d21 100644 --- a/apps/desktop/electron/services/accounts-registry.ts +++ b/apps/desktop/electron/services/accounts-registry.ts @@ -121,6 +121,20 @@ export function readRegistryAccounts(): RegistryAccount[] { return rows.map(rowToAccount); } +/** + * Is `accountId` one of the configured accounts? Read with the THROWING + * {@link readRegistryAccounts}: "I could not read the registry" surfaces as an + * error, never as "not configured" (nor as "configured"). + * + * The one membership check for anything that opens a mailbox database or + * resolves a named account, so every such path refuses the same ids: a removed + * account's id arriving late, a mistyped one, or one never added. + */ +export function isRegisteredAccountId(accountId: string): boolean { + if (typeof accountId !== 'string' || accountId === '') return false; + return readRegistryAccounts().some((account) => account.id === accountId); +} + /** All accounts in the registry (secrets already excluded). `[]` if the read * fails — only safe for callers that merely DISPLAY or hydrate. */ export function listRegistryAccounts(): RegistryAccount[] { @@ -132,9 +146,70 @@ export function listRegistryAccounts(): RegistryAccount[] { } } -/** Insert or update ONE account (by id). Secrets are stripped before writing. */ +// ===== Removed accounts (tombstones) ========================================== +// +// `accounts:remove` drops the registry row early, but the window keeps the +// account in its own list until the removal returns — which waits for the +// provider to confirm the OAuth sign-out. Any snapshot the window mirrors in that +// time (`accounts:save` after a reconnect or a sending-setup change) used to +// upsert the row straight back, and on the next launch the removed account was +// "configured" again: in the switcher, in every all-accounts loop, its database +// recreated on first touch. A token still on disk did the same through seeding. +// +// So a removed id is remembered, durably, and every upsert drops it. Only adding +// that account again through the add flow (accounts:setActive with a verified +// `adding`) clears it. +const REMOVED_META_KEY = 'removed_account_ids'; +/** Tombstones kept; the oldest goes first. A re-add clears its own anyway. */ +const MAX_REMOVED_IDS = 200; + +function readRemovedAccountIds(): string[] { + const raw = getMeta(REMOVED_META_KEY); + if (!raw) return []; + try { + const parsed: unknown = JSON.parse(raw); + return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string' && id !== '') : []; + } catch { + return []; + } +} + +function writeRemovedAccountIds(ids: string[]): void { + setMeta(REMOVED_META_KEY, ids.length ? JSON.stringify(ids.slice(-MAX_REMOVED_IDS)) : null); +} + +/** Remember that `id` was removed, so no snapshot or seed can re-add it. */ +export function markAccountRemoved(id: string): void { + if (!id) return; + writeRemovedAccountIds([...readRemovedAccountIds().filter((removed) => removed !== id), id]); +} + +/** Forget `id`'s removal: the user is adding that account again. */ +export function clearAccountRemoved(id: string): void { + if (!id) return; + const ids = readRemovedAccountIds(); + if (ids.includes(id)) writeRemovedAccountIds(ids.filter((removed) => removed !== id)); +} + +/** Whether `id` was removed and not added again since. */ +export function isAccountRemoved(id: string): boolean { + return !!id && readRemovedAccountIds().includes(id); +} + +/** + * Insert or update ONE account (by id). Secrets are stripped before writing. + * A removed account (see the tombstones above) is not written. + */ export function upsertRegistryAccount(a: RegistryAccount): void { if (!a?.id || !a.email) return; + if (isAccountRemoved(a.id)) { + logger.info('[Registry] not re-adding a removed account', accountLogLabel(a.id)); + return; + } + writeRegistryRow(a); +} + +function writeRegistryRow(a: RegistryAccount): void { const imap = stripSecrets(a.imapConfig); const smtp = stripSecrets(a.smtpConfig); const now = Date.now(); @@ -177,10 +252,17 @@ export function upsertRegistryAccount(a: RegistryAccount): void { */ export function upsertRegistryAccounts(accounts: RegistryAccount[]): void { if (!Array.isArray(accounts) || accounts.length === 0) return; + // Removed accounts are dropped from the snapshot (read once, not per row). + const removed = new Set(readRemovedAccountIds()); + const kept = accounts.filter((a) => !a?.id || !removed.has(a.id)); + if (kept.length < accounts.length) { + logger.info(`[Registry] snapshot mirror skipped ${accounts.length - kept.length} removed account(s)`); + } + if (kept.length === 0) return; const tx = getCoreDb().transaction((list: RegistryAccount[]) => { - for (const a of list) upsertRegistryAccount(a); + for (const a of list) if (a?.id && a.email) writeRegistryRow(a); }); - try { tx(accounts); } catch (e) { logger.error('[Registry] bulk upsert failed:', e); } + try { tx(kept); } catch (e) { logger.error('[Registry] bulk upsert failed:', e); } } /** Permanently remove one account row (on account deletion). Idempotent. */ diff --git a/apps/desktop/electron/services/accounts-runtime.ts b/apps/desktop/electron/services/accounts-runtime.ts index b5a1e249..d02bb265 100644 --- a/apps/desktop/electron/services/accounts-runtime.ts +++ b/apps/desktop/electron/services/accounts-runtime.ts @@ -18,10 +18,10 @@ import { SHARED_CONTACTS_FILE, SQLiteStorage } from '@sarvinbox/storage-node'; import { app } from 'electron'; import type { AccountRuntime } from '../shared'; -import { claimDefaultRuntime, getAccountIdForStorage, getAccountRuntime, hasAccountRuntime, registerAccountRuntime, rekeyRuntime, sendToWindow, unregisterRuntime } from '../shared'; +import { claimDefaultRuntime, getAccountIdForStorage, getAccountRuntime, hasAccountRuntime, registerAccountRuntime, rekeyRuntime, sendToWindow, setCurrentAccount, unregisterRuntime } from '../shared'; import { logPath } from '../utils/log-path'; -import { listRegistryAccounts } from './accounts-registry'; +import { isRegisteredAccountId, listRegistryAccounts } from './accounts-registry'; import { deleteAccountAttachments, rekeyAccountAttachments } from './attachment-cache'; import { getMeta, setMeta } from './core-db'; import { getDbEncryptionKey } from './db-key-store'; @@ -227,8 +227,26 @@ export function releaseAccountMaintenance(accountId: string): void { * Returns null (never a wrong/empty DB) when the primary hasn't been * established yet, because the primary's file can't be resolved until then. * Does NOT connect IMAP — storage/engine only; safe to call for background reads. + * + * REGISTRY-CHECKED: a runtime that is not open yet is opened only for an id + * the account registry lists. Opening creates the file when it is missing, so + * without this a removed account's id arriving late (a background request + * queued before the delete, a stale unified-inbox id) recreated a blank, + * migrated mailbox under the dead id, which then joined every all-accounts + * loop. An unknown id answers null like the other refusals; a registry that + * cannot be read THROWS — "could not find out" is not "not configured". + * + * `registryChecked` is for ONE caller: `accounts:setActive`, which has already + * decided — from its own registry read, or, while an account is being added, + * from main's proof that the account just signed in (account-add-proof). The + * add flow points main at the new account BEFORE its first connect, and the + * renderer writes the registry row only once that connect succeeds, so at that + * moment the id is legitimately not listed yet. Nothing else may pass it. */ -export async function ensureAccountRuntime(accountId: string): Promise { +export async function ensureAccountRuntime( + accountId: string, + { registryChecked = false }: { registryChecked?: boolean } = {}, +): Promise { const existing = getAccountRuntime(accountId); if (existing?.storage) return existing; @@ -239,6 +257,11 @@ export async function ensureAccountRuntime(accountId: string): Promise { + if (!isRegisteredAccountId(activeId)) { + logger.info('[Accounts] persisted active account is not configured — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + + // Mirror accounts:setActive's legacy-adopt rule: the FIRST account to + // activate claims the existing sarvinbox.db (only when it already exists); + // fresh installs never create it and use per-id DBs. + if (!loadPrimaryAccountId() && legacyDbExists()) savePrimaryAccountId(activeId); + + // Only activate when the account's DB can be resolved — the recorded primary + // (legacy sarvinbox.db) or an existing per-id DB. + const isPrimary = loadPrimaryAccountId() === activeId && legacyDbExists(); + if (!isPrimary && !accountDbExists(activeId)) { + logger.info('[Accounts] persisted active account has no DB yet — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + + // Open first, point second: a runtime that cannot be opened (held for + // maintenance) must not leave the active pointer on an empty slot. + if (!hasAccountRuntime(activeId) && !(await ensureAccountRuntime(activeId))) { + logger.info('[Accounts] persisted active account could not be opened — deferring to renderer:', accountLogLabel(activeId)); + return false; + } + setCurrentAccount(activeId); + return true; +} + /** True once `ensureAccountRuntime` can resolve DB files (primary established). */ export function canResolveAccountRuntimes(): boolean { return !!loadPrimaryAccountId(); diff --git a/apps/desktop/electron/services/agent-decision-values.ts b/apps/desktop/electron/services/agent-decision-values.ts new file mode 100644 index 00000000..1bf12b0b --- /dev/null +++ b/apps/desktop/electron/services/agent-decision-values.ts @@ -0,0 +1,77 @@ +/** + * The values a renderer may write into an agent decision row when it resolves + * one (`agent:resolveDecision`, `agent:resolveProposal`). + * + * Both handlers used to cast whatever arrived (`as any`) straight into the + * parameterized UPDATE. The SQL was safe, but any string became the row's + * status or action, and the learning code reads those back as its enums — an + * unknown status is a decision no query counts, and a bogus action a user + * correction nothing understands. Each set below is the full enum, checked by + * the compiler (a `Record` over the union fails to build when the core type + * gains or loses a member), so a renderer value outside it is refused. + */ +import type { AgentDecisionStatus, UserActionType } from '@sarvinbox/core'; + +/** + * The statuses a decision can be RESOLVED to. `pending` is the unresolved + * state: writing it from a resolve call would stamp `resolved_at` on a row that + * then reads as still waiting. + */ +const RESOLVED_STATUSES: Readonly, true>> = { + approved: true, + rejected: true, + auto: true, + expired: true, + overridden: true, +}; + +/** + * What the user actually did instead, recorded with the resolution: any + * {@link UserActionType}, plus `dismissed` — what the composer and the agent + * dashboard (and the pipeline's own housekeeping) record when a proposal is + * thrown away without another action. It is not a mail action, so it is not + * in the core union, but it is in the data. + */ +const ACTUAL_ACTIONS: Readonly> = { + read: true, + unread: true, + star: true, + unstar: true, + archive: true, + delete: true, + spam: true, + move: true, + label_add: true, + label_remove: true, + snooze: true, + unsnooze: true, + reply: true, + reply_all: true, + forward: true, + important: true, + unimportant: true, + mute: true, + open: true, + ignore: true, + dismissed: true, +}; + +function isOwnKey(table: T, value: unknown): value is keyof T { + return typeof value === 'string' && Object.prototype.hasOwnProperty.call(table, value); +} + +/** `value` as a resolved decision status, or null when it is not one. */ +export function resolvedDecisionStatus(value: unknown): Exclude | null { + return isOwnKey(RESOLVED_STATUSES, value) ? value : null; +} + +/** + * `value` as a recorded actual action. `undefined` / `null` mean "none given" + * (the row keeps what it had); anything else must be a known action. + */ +export function decisionActualAction( + value: unknown, +): { ok: true; action: UserActionType | 'dismissed' | null } | { ok: false } { + if (value === undefined || value === null) return { ok: true, action: null }; + return isOwnKey(ACTUAL_ACTIONS, value) ? { ok: true, action: value } : { ok: false }; +} diff --git a/apps/desktop/electron/services/ai-categorization-service.ts b/apps/desktop/electron/services/ai-categorization-service.ts index 1a633e79..39fc46a4 100644 --- a/apps/desktop/electron/services/ai-categorization-service.ts +++ b/apps/desktop/electron/services/ai-categorization-service.ts @@ -13,6 +13,7 @@ import type { EmailRecord , AIErrorInfo, EmailSecurityContext, SenderSignals } f import { getMainWindow, requireStorage } from '../shared'; import { ensureBundledAgentPrompts } from './agent-prompt-defaults'; +import { filterAiVerdict } from './filter-ai-skip'; import { chromiumFetch } from './net-fetch'; import { readCategorizationSenderHistory } from './sender-history-context'; const logger = createLogger('ai-categorization-service'); @@ -774,6 +775,11 @@ export class AICategorizationService { } if (existingCategoryClassification(email) || automaticCategorizationDeferred(email) || isSpamProtectedEmail(email, await storage.getFolder?.(email.folderId), await storage.getFolders?.())) continue; + // A filter with "Skip AI checks": never sent, and marked handled so the + // run does not pick it again. Unreadable rules: left pending, not sent. + const filterVerdict = await filterAiVerdict(storage, email); + if (filterVerdict === 'skip') storage.getRepositories?.()?.agent?.markAgentGaveUp?.(email.id, {}); + if (filterVerdict !== 'run') continue; // Body for the LLM prompt — see categorizationBodyOf. const body = categorizationBodyOf(email); const fromAddr = (email.fromAddress || '').toLowerCase(); diff --git a/apps/desktop/electron/services/antivirus-desktop-backend.ts b/apps/desktop/electron/services/antivirus-desktop-backend.ts index 271a404a..13422cc2 100644 --- a/apps/desktop/electron/services/antivirus-desktop-backend.ts +++ b/apps/desktop/electron/services/antivirus-desktop-backend.ts @@ -1,4 +1,4 @@ -import type { ExtensionSecurityBackend } from '@sarvinbox/core'; +import { AttachmentSizeLimitError, isAttachmentSizeLimitError, type ExtensionSecurityBackend } from '@sarvinbox/core'; import { safeStorage } from 'electron'; import { getMainWindow, getSyncEngineFor } from '../shared'; @@ -128,7 +128,9 @@ async function read(source: ScanSource, maxBytes: number, signal?: AbortSignal, const email = await storage.getEmail(source.messageId); if (!email || email.pgpStatus === 'encrypted') throw new Error('Message is unavailable or encrypted.'); if (source.kind === 'email-body') { - if (!email.rawBody || Buffer.byteLength(email.rawBody, 'utf8') > maxBytes) throw new Error('Message text is unavailable or exceeds the scan limit.'); + if (!email.rawBody) throw new Error('Message text is unavailable.'); + // Over the scanner's limit is its own failure (too large to scan), never "unavailable". + if (Buffer.byteLength(email.rawBody, 'utf8') > maxBytes) throw new AttachmentSizeLimitError('Message text exceeds the scan limit.'); return Buffer.from(email.rawBody, 'utf8'); } const folder = await storage.getFolder(email.folderId); @@ -139,7 +141,13 @@ async function read(source: ScanSource, maxBytes: number, signal?: AbortSignal, const content = onProgress ? sync.fetchAttachmentScanPart(folder.path, email.uid, source.partId, source.partFilename ?? source.displayName, maxBytes, signal, onProgress) : sync.fetchAttachmentScanPart(folder.path, email.uid, source.partId, source.partFilename ?? source.displayName, maxBytes, signal); - return content.catch(() => { throw new Error('The exact attachment could not be downloaded within the scan limit.'); }); + // A part over the scan limit keeps its typed error (too large to scan, not a + // failed download). Any other IMAP error stays attached only as the cause, for + // the scan log's one-word diagnosis; its message can quote the mail. + return content.catch((error: unknown) => { + if (isAttachmentSizeLimitError(error)) throw error; + throw Object.assign(new Error('The exact attachment could not be downloaded for scanning.'), { cause: error }); + }); } export function createAntivirusDesktopBackend(): ExtensionSecurityBackend { diff --git a/apps/desktop/electron/services/antivirus-oauth-service.ts b/apps/desktop/electron/services/antivirus-oauth-service.ts index c884d163..0dd8ceb5 100644 --- a/apps/desktop/electron/services/antivirus-oauth-service.ts +++ b/apps/desktop/electron/services/antivirus-oauth-service.ts @@ -107,6 +107,16 @@ interface Pending { setup: AntivirusSetupStatus; } +/** + * Whether a Sarv sign-in may take the scanner's place: none is set up, the + * saved one cannot be opened (a locked keychain), or the Sarv scanner itself + * refused its saved credential this session (401). A working setup, and any + * other scanner's setup, refused or not, is never replaced from here. + */ +const replaceable = (setup: AntivirusSetupStatus): boolean => + !setup.configured || Boolean(setup.savedCredentialsLocked) || + (Boolean(setup.signInRejected) && setup.endpoint === SARV_SCANNER_ORIGIN); + const disclosure = (setup: AntivirusSetupStatus): string => JSON.stringify([ setup.endpoint, setup.operator, setup.region, setup.privacyPolicyUrl, setup.privacyTermsVersion, setup.scanPolicyVersion, setup.metadataRetentionSeconds, setup.contentLifetimeSeconds, setup.resultLifetimeSeconds, @@ -180,7 +190,7 @@ export class AntivirusOAuthService { await this.dependencies.prepareExtension(); this.assertLive(controller, accountId); const previous = await this.dependencies.scanService().getTrustedSetup(SARV_SCANNER_EXTENSION_ID); - if (previous.configured && !previous.savedCredentialsLocked) throw new Error('A scanner is already configured. Keep its connection, or update its approved accounts in Extensions settings.'); + if (!replaceable(previous)) throw new Error('A scanner is already configured. Keep its connection, or update its approved accounts in Extensions settings.'); const config = await this.request('/ui/config', {}, undefined, controller.signal); if (config.authProvider !== 'sarv' || config.serviceMode !== 'scanner' || config.issuerUrl !== ISSUER || config.clientId !== CLIENT_ID || config.tokenAudience !== AUDIENCE || config.discoveryUrl !== '/ui/oauth/discovery' || @@ -238,7 +248,7 @@ export class AntivirusOAuthService { let issuedId: string | undefined; try { const existing = await this.dependencies.scanService().getTrustedSetup(SARV_SCANNER_EXTENSION_ID); - if (existing.configured && !existing.savedCredentialsLocked) { + if (!replaceable(existing)) { throw new Error('Scanner setup changed. Keep the existing connection or review it in Extensions settings.'); } const issued = await this.request('/api/v1/tokens', { method: 'POST', body: JSON.stringify({ name: 'Sarv Inbox attachment scanning', expiresInDays: 90 }) }, pending.accessToken); @@ -251,7 +261,7 @@ export class AntivirusOAuthService { if (disclosure(fresh.setup) !== disclosure(pending.setup)) throw new Error('The scanner privacy, credential storage or scan policy changed. Sign in and review its terms again.'); this.dependencies.assertAuthorized(input.accountId); const beforeSave = await this.dependencies.scanService().getTrustedSetup(SARV_SCANNER_EXTENSION_ID); - if (beforeSave.configured && !beforeSave.savedCredentialsLocked) { + if (!replaceable(beforeSave)) { throw new Error('Scanner setup changed. Keep the existing connection or review it in Extensions settings.'); } const setup = await this.dependencies.scanService().configure(SARV_SCANNER_EXTENSION_ID, { challenge: fresh.challenge, diff --git a/apps/desktop/electron/services/antivirus-scan-service.ts b/apps/desktop/electron/services/antivirus-scan-service.ts index 4114df77..729aa2be 100644 --- a/apps/desktop/electron/services/antivirus-scan-service.ts +++ b/apps/desktop/electron/services/antivirus-scan-service.ts @@ -1,12 +1,17 @@ import { createHash, randomUUID } from 'node:crypto'; import type { AntivirusScanJob, AntivirusScanTarget, AntivirusSetupStatus, ExtensionSecurityBackend } from '@sarvinbox/core'; -import { waitForAbortableOperation } from '@sarvinbox/core'; +import { createLogger, errorDiagnostic, failureCause, isAttachmentSizeLimitError, isTimeoutError, waitForAbortableOperation } from '@sarvinbox/core'; -import { consentFingerprint, hasControlCharacters, object, opaqueId, ScannerTransport, scannerOrigin, timestamp, validateCapabilities, validateEngine, - type ScannerCapabilities } from './antivirus-transport'; +import { isTransientScanFailure, SCAN_FAILURE_DOWNLOAD_MESSAGES, type ScanFailureReason, type ScanFailureRecord, + type ScannerConnectionTest } from '../../src/utils/attachment-scan-failures'; + +import { consentFingerprint, hasControlCharacters, object, opaqueId, ScannerError, scanFailureReason, ScannerTransport, scannerOrigin, timestamp, + validateCapabilities, validateEngine, type ScannerCapabilities } from './antivirus-transport'; import type { AttachmentTransferBytes } from './attachment-download-protection'; +const logger = createLogger('antivirus-scan'); + export interface ScanSource { accountId: string; messageId: string; @@ -57,6 +62,8 @@ interface Work { transport: ScannerTransport; ticketId?: string; finishedAt?: number; + /** Why the scan gave no verdict, once `run` has recorded it. */ + failure?: ScanFailureReason; download?: { content?: Buffer; onProgress?: (phase: 'downloading' | 'uploading' | 'scanning', bytes?: AttachmentTransferBytes) => void }; } export interface VerifiedAttachmentDownload { @@ -71,6 +78,50 @@ export interface AttachmentSetupRequirement { const terminal = new Set(['completed', 'cancelled', 'error', 'expired']); const safeError = (error: unknown): string => error instanceof Error ? error.message : 'The scan could not be completed.'; +/** + * A view, open or save the scanner did not clear, saying why in the user's + * words. `code` is the reason, so the IPC handler's `errorDiagnostic` line + * names it too; the message never carries the file, the message or the server. + */ +export class AttachmentScanBlockedError extends Error { + readonly code: ScanFailureReason; + constructor(reason: ScanFailureReason) { + super(SCAN_FAILURE_DOWNLOAD_MESSAGES[reason]); + this.name = 'AttachmentScanBlockedError'; + this.code = reason; + } +} + +/** The innermost cause of a failure (a fetch error inside a scanner error), as one log token. */ +function underlyingCause(error: unknown): string { + let current = error; + for (let depth = 0; depth < 4; depth++) { + const next = current instanceof Error ? (current as { cause?: unknown }).cause : undefined; + if (next === undefined || next === null) break; + current = next; + } + return failureCause(current); +} + +/** + * What a per-item verdict that is not a clean one says about the scan, by the + * scanner's own reason code (the same codes the panel words). Anything else is + * read from the verdict: `incomplete` could not cover the file, `error` failed. + */ +const VERDICT_FAILURES: Readonly> = { + stale_definitions: 'outdated-definitions', engine_unavailable: 'scanner-unavailable', + scan_timeout: 'scanner-error', scan_failed: 'scanner-error', ticket_deadline_expired: 'scanner-error', cancelled: 'scanner-error', + encrypted_archive: 'incomplete-scan', scan_limit: 'incomplete-scan', coverage_unknown: 'incomplete-scan', invalid_content: 'incomplete-scan', +}; +function verdictFailure(verdict?: { verdict: string; code: string }): ScanFailureReason { + if (verdict && Object.prototype.hasOwnProperty.call(VERDICT_FAILURES, verdict.code)) return VERDICT_FAILURES[verdict.code]!; + return verdict?.verdict === 'incomplete' ? 'incomplete-scan' : 'scanner-error'; +} + +/** Who a saved credential is, without keeping it: a rejection is remembered for this pair only. */ +const credentialIdentity = (config: Pick): string => + createHash('sha256').update(JSON.stringify([config.endpoint, config.credential])).digest('hex'); + /** Content/credentials remain in main. The extension receives opaque handles and verdicts only. */ export class AntivirusScanService implements ExtensionSecurityBackend { private contexts = new Map(); @@ -78,6 +129,10 @@ export class AntivirusScanService implements ExtensionSecurityBackend { private accountGenerations = new Map(); private jobs = new Map(); private probes = new Map(); + /** The most recent failed scan per extension, this session. Codes and times only. */ + private lastFailures = new Map(); + /** Per extension: the saved credential the scanner last refused (by identity, never the value). */ + private rejectedSignIns = new Map(); private sweep: ReturnType; private disposed = false; constructor(private deps: AntivirusDependencies) { @@ -94,6 +149,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { const accounts = this.deps.accounts(); return { endpoint: config?.endpoint ?? '', configured: !!config, enabled: !!config, ...(extensionId && this.deps.credentialStorage ? { credentialStorage: this.deps.credentialStorage(extensionId) } : {}), + ...(config && extensionId && this.signInRejected(extensionId, config) ? { signInRejected: true } : {}), allowedAccountIds: config?.allowedAccountIds.filter(id => accounts.some(a => a.id === id)) ?? [], allowBody: config?.allowBody ?? false, accounts, operator: config?.capabilities.operator.name, region: config?.capabilities.operator.region, @@ -127,6 +183,16 @@ export class AntivirusScanService implements ExtensionSecurityBackend { throw new Error('The attachment account or antivirus service is unavailable.'); } }; + // A saved setup that cannot be opened (a locked keychain) or is damaged is + // never "setup missing": the view, open or save stops with its own reason, + // which is kept as the last failure and logged once. + const unreadable = (error: unknown): never => { + throw new AttachmentScanBlockedError(this.recordFailure(extensionId, 'setup-unreadable', error)); + }; + const read = async (): Promise => { + try { return await this.deps.readConfiguration(extensionId); } + catch (error) { return unreadable(error); } + }; const identity = (config?: ScannerConfiguration) => { if (config !== undefined) { try { @@ -139,7 +205,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { // Stored engine metadata may be old; freshness is checked against the live scanner when scanning. const capabilities = validateCapabilities(config.capabilities, timestamp(config.capabilities?.engine?.signaturesUpdatedAt)); if (consentFingerprint(capabilities) !== config.fingerprint) throw new Error('Invalid configuration'); - } catch { throw new Error('Scanner configuration cannot be securely read.'); } + } catch (error) { unreadable(error); } } return createHash('sha256').update(JSON.stringify(config ?? null)).digest('hex'); }; @@ -147,7 +213,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { const generation = this.generation(extensionId); const accountGeneration = this.accountGenerations.get(accountId) ?? 0; // An unreadable configuration must throw; it is never proof of missing setup. - const config = await this.deps.readConfiguration(extensionId); + const config = await read(); assertAvailable(); if (generation !== this.generation(extensionId) || accountGeneration !== (this.accountGenerations.get(accountId) ?? 0)) { throw new Error('Antivirus setup changed. Try again.'); @@ -156,7 +222,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { if (config?.allowedAccountIds.includes(accountId)) return undefined; return { assertCurrent: async () => { assertAvailable(); - const current = await this.deps.readConfiguration(extensionId); + const current = await read(); assertAvailable(); if (generation !== this.generation(extensionId) || accountGeneration !== (this.accountGenerations.get(accountId) ?? 0) || identity(current) !== fingerprint) { throw new Error('Antivirus setup changed. Try again.'); @@ -165,6 +231,77 @@ export class AntivirusScanService implements ExtensionSecurityBackend { } async openSetup(extensionId: string): Promise { this.deps.openSetup(extensionId); } + /** The most recent failed scan for this scanner since the app started, if any. */ + lastScanFailure(extensionId: string): ScanFailureRecord | null { + const record = this.lastFailures.get(extensionId); + return record ? { ...record } : null; + } + + private signInRejected(extensionId: string, config: Pick): boolean { + return this.rejectedSignIns.get(extensionId) === credentialIdentity(config); + } + + /** A credential the scanner accepted again is no longer reported as refused. */ + private signInAccepted(extensionId: string, config: Pick): void { + if (this.signInRejected(extensionId, config)) this.rejectedSignIns.delete(extensionId); + } + + /** + * Note one failed scan: kept as this scanner's last failure, and written as + * ONE log line of codes (the reason, whether it can clear on its own, and + * the underlying cause's class, code or HTTP status). Never the file name, + * the message id, the scanner's path or any error's message text. + */ + private recordFailure(extensionId: string, reason: ScanFailureReason, error?: unknown, + config?: Pick): ScanFailureReason { + const transient = isTransientScanFailure(reason); + this.lastFailures.set(extensionId, { reason, transient, at: this.now() }); + if (reason === 'sign-in-rejected' && config) this.rejectedSignIns.set(extensionId, credentialIdentity(config)); + logger.warn('Attachment scan failed', { extension: extensionId, reason, transient, + ...(error === undefined ? {} : { cause: underlyingCause(error), error: errorDiagnostic(error) }) }); + return reason; + } + /** Each scan ends at most once (a thrown error, or the scanner's own failed ticket), so this runs at most once per scan. */ + private failWork(work: Work, reason: ScanFailureReason, error?: unknown): void { + work.failure = this.recordFailure(work.extensionId, reason, error, work.config); + } + + /** + * Check the SAVED setup without changing it: ask the saved scanner origin, + * with the saved credential, for its capabilities and compare its policy + * with the one the user approved. Writes nothing, opens no setup, starts no + * consent, and answers codes and engine facts only, never the credential. + */ + async testConnection(extensionId: string): Promise { + const checkedAt = this.now(); + const fail = (reason: ScanFailureReason, error?: unknown): ScannerConnectionTest => { + logger.info('Scanner connection test failed', { extension: extensionId, reason, + ...(error === undefined ? {} : { cause: underlyingCause(error), error: errorDiagnostic(error) }) }); + return { ok: false, checkedAt, reason, transient: isTransientScanFailure(reason) }; + }; + let config: ScannerConfiguration | undefined; + try { config = await this.deps.readConfiguration(extensionId); } + catch (error) { return fail('setup-unreadable', error); } + if (!config) return fail('not-set-up'); + let transport: ScannerTransport; + try { + // Only the saved origin, re-validated, ever receives the saved credential. + transport = this.transport({ endpoint: scannerOrigin(config.endpoint, this.deps.allowDevelopmentLoopback), credential: config.credential }); + } catch (error) { return fail('setup-unreadable', error); } + let capabilities: ScannerCapabilities; + try { capabilities = await transport.capabilities(); } + catch (error) { + const reason = scanFailureReason(error); + if (reason === 'sign-in-rejected') this.rejectedSignIns.set(extensionId, credentialIdentity(config)); + return fail(reason, error); + } + this.signInAccepted(extensionId, config); + if (consentFingerprint(capabilities) !== config.fingerprint) return fail('policy-changed'); + const { name, version, signatureVersion, signaturesUpdatedAt } = capabilities.engine; + logger.info('Scanner connection test passed', { extension: extensionId }); + return { ok: true, checkedAt, engine: { name, version, signatureVersion, signaturesUpdatedAt } }; + } + async probe(extensionId: string, endpoint: string, credential?: string): Promise<{ challenge: string; setup: AntivirusSetupStatus }> { const origin = scannerOrigin(endpoint, this.deps.allowDevelopmentLoopback); let previous: ScannerConfiguration | undefined; @@ -209,6 +346,9 @@ export class AntivirusScanService implements ExtensionSecurityBackend { // write; verifying again can explicitly select OS-backed persistence. await this.deps.writeConfiguration(extensionId, config, probe.credentialStorage); this.probes.delete(input.challenge); + // A failure under the replaced setup says nothing about this one. + this.lastFailures.delete(extensionId); + this.rejectedSignIns.delete(extensionId); return this.publicSetup(config, extensionId); } @@ -240,17 +380,22 @@ export class AntivirusScanService implements ExtensionSecurityBackend { private checkAccounts(config: ScannerConfiguration, accountIds: string[]): void { const existing = new Set(this.deps.accounts().map(a => a.id)); if (accountIds.some(id => !existing.has(id) || !config.allowedAccountIds.includes(id))) { - throw new Error('This account is removed or has not consented to scanner uploads.'); + throw new ScannerError('This account is removed or has not consented to scanner uploads.', 'setup-changed'); } } private async assertCurrent(work: Work, ignoreAbort = false): Promise { - if (this.disposed) throw new Error('The antivirus service is unavailable.'); - const current = await this.deps.readConfiguration(work.extensionId); + if (this.disposed) throw new ScannerError('The antivirus service is unavailable.', 'setup-changed'); + let current: ScannerConfiguration | undefined; + try { current = await this.deps.readConfiguration(work.extensionId); } + catch (error) { + // An unreadable store is never "setup removed": it keeps its own reason. + throw new ScannerError(error instanceof Error ? error.message : 'Scanner configuration cannot be securely read.', 'setup-unreadable', { cause: error }); + } if (this.disposed || (!ignoreAbort && work.abort.signal.aborted) || !current || work.generation !== this.generation(work.extensionId) || current.endpoint !== work.config.endpoint || current.fingerprint !== work.config.fingerprint || - current.credential !== work.config.credential) throw new Error('Scanner consent was revoked or changed.'); + current.credential !== work.config.credential) throw new ScannerError('Scanner consent was revoked or changed.', 'setup-changed'); this.checkAccounts(current, work.targets.map(t => t.accountId)); - if (work.targets.some(t => t.kind === 'email-body') && !current.allowBody) throw new Error('Message text sharing is not enabled.'); + if (work.targets.some(t => t.kind === 'email-body') && !current.allowBody) throw new ScannerError('Message text sharing is not enabled.', 'setup-changed'); } private prune(): void { for (const [id, probe] of this.probes) if (probe.expires <= this.now()) this.probes.delete(id); @@ -294,19 +439,30 @@ export class AntivirusScanService implements ExtensionSecurityBackend { throw new Error('Download blocked: scanner settings changed. Review scanner setup and try again.'); } }; + // The host's own deadline (a TimeoutError as the abort reason) is a scan + // that took too long, kept and logged; the user's own cancel is neither. + const cancelled = (): Error => { + if (isTimeoutError(options.signal?.reason)) this.recordFailure(extensionId, 'timed-out', options.signal?.reason); + return new Error('Download cancelled.'); + }; assertLookupCurrent(); - const config = await this.deps.readConfiguration(extensionId); + let config: ScannerConfiguration | undefined; + try { config = await this.deps.readConfiguration(extensionId); } + catch (error) { + assertLookupCurrent(); + throw new AttachmentScanBlockedError(this.recordFailure(extensionId, 'setup-unreadable', error)); + } assertLookupCurrent(); if (!config) { this.deps.openSetup(extensionId); - throw new Error('Configure ClamAV Scan before downloading attachments.'); + throw new Error(SCAN_FAILURE_DOWNLOAD_MESSAGES['not-set-up']); } try { this.checkAccounts(config, [accountId]); } catch { this.deps.openSetup(extensionId); throw new Error('This account is not approved for attachment scanning. Review scanner setup.'); } - if (options.signal?.aborted) throw new Error('Download cancelled.'); + if (options.signal?.aborted) throw cancelled(); options.onProgress?.('downloading'); const metadataAbort = new AbortController(); const metadataSignal = options.signal ? AbortSignal.any([options.signal, metadataAbort.signal]) : metadataAbort.signal; @@ -315,7 +471,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { try { sources = await waitForAbortableOperation(this.deps.sources(messageId, accountId, metadataSignal), metadataSignal); } catch { - if (options.signal?.aborted) throw new Error('Download cancelled.'); + if (options.signal?.aborted) throw cancelled(); throw new Error(metadataAbort.signal.aborted ? 'Download blocked: attachment details timed out. Reconnect this account and try again.' : 'Download blocked: attachment details are unavailable. Reopen this email and try again.'); @@ -337,7 +493,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { this.prune(); const running = [...this.jobs.values()].filter(work => !terminal.has(work.job.state)); if (running.length >= 4 || running.filter(work => work.extensionId === extensionId).length >= 2 || this.jobs.size >= 100) { - throw new Error('Download blocked: scanning failed. Try again when the scanner is available.'); + throw new AttachmentScanBlockedError(this.recordFailure(extensionId, 'busy')); } const target: Target = { ...source, targetId: randomUUID(), extensionId, generation }; const job: AntivirusScanJob = { id: randomUUID(), state: 'preparing', createdAt: this.iso(), updatedAt: this.iso(), @@ -352,10 +508,12 @@ export class AntivirusScanService implements ExtensionSecurityBackend { const dispose = () => { disposed = true; work.download?.content?.fill(0); this.jobs.delete(job.id); }; try { await this.run(work); - if (work.abort.signal.aborted || options.signal?.aborted || job.state === 'cancelled') throw new Error('Download cancelled.'); - if (job.state !== 'completed' || !work.download?.content) throw new Error('Download blocked: scanning failed. Try again when the scanner is available.'); + if (work.abort.signal.aborted || options.signal?.aborted || job.state === 'cancelled') throw cancelled(); + // `run` recorded why; a finished scan without a receipt is the scanner's failure. + if (job.state !== 'completed' || !work.download?.content) throw new AttachmentScanBlockedError(work.failure ?? 'scanner-error'); if (job.items[0]?.status === 'threat-detected') throw new Error('Download blocked: ClamAV detected a threat.'); - if (job.items[0]?.status !== 'no-threat-detected') throw new Error('Download blocked: the attachment could not be fully scanned.'); + // An error or incomplete verdict: `run` recorded the scanner's reason for it. + if (job.items[0]?.status !== 'no-threat-detected') throw new AttachmentScanBlockedError(work.failure ?? 'incomplete-scan'); const content = work.download.content; const assertCurrent = async () => { if (options.signal?.aborted || work.abort.signal.aborted) throw new Error('Download cancelled.'); @@ -378,22 +536,34 @@ export class AntivirusScanService implements ExtensionSecurityBackend { try { await this.assertCurrent(work); const cap = await work.transport.capabilities(work.abort.signal); - if (consentFingerprint(cap) !== work.config.fingerprint) throw new Error('The scanner policy changed. Review setup before uploading.'); + this.signInAccepted(work.extensionId, work.config); + if (consentFingerprint(cap) !== work.config.fingerprint) throw new ScannerError('The scanner policy changed. Review setup before uploading.', 'policy-changed'); const items: Array<{ clientItemId: string; kind: string; byteLength: number; sha256: string; content: Buffer }> = []; let total = 0; for (const target of work.targets) { await this.assertCurrent(work); + // A size known up front (message text) over the limit is not worth fetching. + if (target.byteLength !== null && target.byteLength > cap.maxItemBytes) throw new ScannerError('Selected content exceeds the scanner limits.', 'too-large'); let lastProgress = 0; - const content = await (work.download - ? this.deps.read(target, cap.maxItemBytes, work.abort.signal, transferredBytes => { - if (!work.abort.signal.aborted && Date.now() - lastProgress >= 100) { - lastProgress = Date.now(); - work.download?.onProgress?.('downloading', { transferredBytes }); - } - }) - : this.deps.read(target, cap.maxItemBytes, work.abort.signal)); + let content: Buffer; + try { + content = await (work.download + ? this.deps.read(target, cap.maxItemBytes, work.abort.signal, transferredBytes => { + if (!work.abort.signal.aborted && Date.now() - lastProgress >= 100) { + lastProgress = Date.now(); + work.download?.onProgress?.('downloading', { transferredBytes }); + } + }) + : this.deps.read(target, cap.maxItemBytes, work.abort.signal)); + } catch (error) { + // The reader stops at the scanner's limit: a file over it is too large, which no retry changes. + if (isAttachmentSizeLimitError(error)) throw new ScannerError('Selected content exceeds the scanner limits.', 'too-large', { cause: error }); + // The mail server, not the scanner: nothing was sent yet. + throw new ScannerError('The attachment could not be read from the mail server.', 'read-failed', { cause: error }); + } held.push(content); - if (!content.length || content.length > cap.maxItemBytes || (total += content.length) > cap.maxTotalBytes) throw new Error('Selected content exceeds the scanner limits.'); + if (!content.length) throw new ScannerError('The attachment could not be read from the mail server.', 'read-failed'); + if (content.length > cap.maxItemBytes || (total += content.length) > cap.maxTotalBytes) throw new ScannerError('Selected content exceeds the scanner limits.', 'too-large'); if (work.download) { work.download.content = Buffer.from(content); work.download.onProgress?.('downloading', { transferredBytes: content.length, totalBytes: content.length }); @@ -441,6 +611,8 @@ export class AntivirusScanService implements ExtensionSecurityBackend { ticket.items.length !== bindings.length || !['awaiting_upload', 'queued', 'scanning', 'completed', 'failed', 'cancelled', 'expired'].includes(ticket.status)) { throw new Error('The scanner returned a mismatched ticket.'); } + // Each item's verdict and the scanner's reason code for it, for the failure record. + const verdicts: Array<{ verdict: string; code: string } | undefined> = []; const mapped = bindings.map((binding, index) => { const matches = ticket.items.filter((entry: any) => entry.itemId === binding.itemId && entry.clientItemId === binding.clientItemId); if (matches.length !== 1) throw new Error('The scanner returned missing or duplicate results.'); @@ -473,6 +645,7 @@ export class AntivirusScanService implements ExtensionSecurityBackend { if (result.verdict === 'threat_detected' && (!result.signatures.length || reason.code !== 'signature_match')) throw new Error('The scanner omitted its detection signature.'); if (['incomplete', 'error'].includes(result.verdict) && result.fullCoverage !== false) throw new Error('The scanner returned inconsistent coverage.'); local.status = ({ no_threat_detected: 'no-threat-detected', threat_detected: 'threat-detected', incomplete: 'incomplete', error: 'error' } as const)[result.verdict as 'no_threat_detected']; + verdicts[index] = { verdict: result.verdict, code: reason.code }; const reasons: Record = { scan_completed: 'ClamAV found no threat within the evaluated scan limits.', signature_match: 'ClamAV detected a threat. Avoid opening this item.', encrypted_archive: 'An encrypted archive could not be fully inspected.', scan_limit: 'A scanner processing limit prevented a complete scan.', coverage_unknown: 'Full scanner coverage could not be established.', @@ -490,7 +663,18 @@ export class AntivirusScanService implements ExtensionSecurityBackend { const expires = timestamp(ticket.resultExpiresAt); if (expires <= this.now() || expires > this.now() + cap.resultLifetimeSeconds * 1000 + 5000) throw new Error('The scanner returned an invalid result expiry.'); work.job.expiresAt = ticket.resultExpiresAt; - this.touch(work, ({ completed: 'completed', failed: 'error', cancelled: 'cancelled', expired: 'expired' } as const)[ticket.status as 'completed']); + // A ticket the scanner cancelled is its failure, not the user's cancel: the + // user's cancel stops polling, so it is never observed here. + this.touch(work, ({ completed: 'completed', failed: 'error', cancelled: 'error', expired: 'expired' } as const)[ticket.status as 'completed']); + if (ticket.status === 'cancelled') work.job.error = 'The scanner cancelled this scan.'; + if (work.job.state === 'error' || work.job.state === 'expired') { + // The scanner itself gave up on the ticket (failed, cancelled or expired on its side). + this.failWork(work, 'scanner-error'); + } else { + // Completed, but an item could not be cleared: say why, by the scanner's own reason code. + const failed = work.job.items.findIndex(item => item.status === 'error' || item.status === 'incomplete'); + if (failed >= 0) this.failWork(work, verdictFailure(verdicts[failed])); + } break; } this.touch(work, ticket.status === 'scanning' ? 'scanning' : 'queued'); @@ -507,6 +691,8 @@ export class AntivirusScanService implements ExtensionSecurityBackend { this.touch(work, work.abort.signal.aborted ? 'cancelled' : 'error'); work.job.error = safeError(error); work.job.items = work.job.items.map(item => ({ ...item, status: 'error', reason: 'No usable verdict is available.' })); + // A cancellation is the user's choice (or a setup change that cancels work), not a failure. + if (work.job.state === 'error') this.failWork(work, scanFailureReason(error), error); } } finally { for (const buffer of held) buffer.fill(0); @@ -540,6 +726,8 @@ export class AntivirusScanService implements ExtensionSecurityBackend { this.generations.set(extensionId, this.generation(extensionId) + 1); await this.cancelExtensionWork(extensionId); this.contexts.delete(extensionId); + this.lastFailures.delete(extensionId); + this.rejectedSignIns.delete(extensionId); for (const [id, p] of this.probes) if (p.extensionId === extensionId) this.probes.delete(id); for (const [id, work] of this.jobs) if (work.extensionId === extensionId) this.jobs.delete(id); await this.deps.writeConfiguration(extensionId, undefined); diff --git a/apps/desktop/electron/services/antivirus-transport.ts b/apps/desktop/electron/services/antivirus-transport.ts index d57a9a4d..03b1d05b 100644 --- a/apps/desktop/electron/services/antivirus-transport.ts +++ b/apps/desktop/electron/services/antivirus-transport.ts @@ -1,6 +1,8 @@ import { createHash } from 'node:crypto'; -import { isBareOrigin, isLoopbackHost } from '@sarvinbox/core'; +import { isBareOrigin, isCertificateUntrustedError, isLoopbackHost } from '@sarvinbox/core'; + +import type { ScanFailureReason } from '../../src/utils/attachment-scan-failures'; export interface ScannerCapabilities { protocolVersion: 1; @@ -15,6 +17,49 @@ export interface ScannerCapabilities { authenticationRetentionSeconds?: number; } +/** + * A scanner failure that knows why it happened. The message stays what the + * setup dialog and the extension panel already show; `reason` is what the + * download path turns into its own message, and `status` the HTTP status the + * scanner answered (read by `errorDiagnostic` for the log line). Anything else + * thrown on the way to a verdict is classified as `scanner-error`. + */ +export class ScannerError extends Error { + readonly status?: number; + /** What failed underneath (a fetch error), for the log's one-word diagnosis only. */ + readonly cause?: unknown; + constructor(message: string, readonly reason: ScanFailureReason, options: { status?: number; cause?: unknown } = {}) { + super(message); + this.name = 'ScannerError'; + if (options.status !== undefined) this.status = options.status; + if (options.cause !== undefined) this.cause = options.cause; + } +} + +/** The reason a scan step failed: a `ScannerError`'s own, else the scanner's answer could not be used. */ +export function scanFailureReason(error: unknown): ScanFailureReason { + return error instanceof ScannerError ? error.reason : 'scanner-error'; +} + +/** + * Statuses the scanner protocol names (docs/antivirus/scan-api.openapi.json), + * with the message and reason each one carries. Only 401 says the credential + * itself is bad; 403 is an accepted credential that operator policy refuses. + */ +const STATUS_FAILURES: Record = { + 401: ['Scanner credential is invalid or expired.', 'sign-in-rejected'], + 403: ['Scanner permission denied.', 'forbidden-by-policy'], + 404: ['Scan ticket expired or is unavailable.', 'scanner-error'], + 408: ['Scanner upload timed out.', 'unreachable'], + 410: ['Scan ticket expired.', 'scanner-error'], + 413: ['Selected content exceeds the scanner limit.', 'too-large'], + 429: ['Scanner quota reached. Try again later.', 'scanner-unavailable'], + // A gateway in front of the scanner answering for it: the scanner is down or overloaded. + 502: ['Scanner is busy or unavailable.', 'scanner-unavailable'], + 503: ['Scanner is busy or unavailable.', 'scanner-unavailable'], + 504: ['Scanner is busy or unavailable.', 'scanner-unavailable'], +}; + export function scannerOrigin(value: string, allowDevelopmentLoopback = false): string { let url: URL; try { url = new URL(value); } catch { throw new Error('Enter a valid scanner HTTPS URL.'); } @@ -66,9 +111,9 @@ export function validateEngine(value: unknown, policy?: string, now = Date.now() signaturesUpdatedAt: text(engine.signaturesUpdatedAt, 40), scanPolicyVersion: text(engine.scanPolicyVersion) }; const updated = timestamp(result.signaturesUpdatedAt); if (updated > now + 300_000 || now - updated > 48 * 60 * 60 * 1000) { - throw new Error('Scanner definitions are stale or their update time is invalid.'); + throw new ScannerError('Scanner definitions are stale or their update time is invalid.', 'outdated-definitions'); } - if (policy && result.scanPolicyVersion !== policy) throw new Error('The scan policy changed. Review scanner setup again.'); + if (policy && result.scanPolicyVersion !== policy) throw new ScannerError('The scan policy changed. Review scanner setup again.', 'policy-changed'); return result; } @@ -107,7 +152,12 @@ export function opaqueId(value: unknown): string { return value; } -/** No redirects, custom TLS bypass, arbitrary returned URLs, or unbounded responses. */ +/** + * No redirects, custom TLS bypass, arbitrary returned URLs, or unbounded responses. + * A redirect is never followed (`redirect: 'manual'`): it is refused as an + * untrusted answer, which `redirect: 'error'` could only report as an + * undifferentiated network failure. + */ export class ScannerTransport { constructor(readonly origin: string, private credential: string, private requestFetch: typeof fetch = fetch) { if (!credential || credential.length > 8192 || /\s/.test(credential) || hasControlCharacters(credential)) throw new Error('Enter a valid scanner API credential.'); @@ -126,16 +176,27 @@ export class ScannerTransport { headers: { Authorization: 'Bearer ' + this.credential, ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), ...(body === undefined ? {} : { 'Content-Type': typeof body === 'string' ? 'application/json' : 'application/octet-stream' }) }, - redirect: 'error', signal: combined, cache: 'no-store' }); - } catch { - throw new Error(signal?.aborted ? 'Scan cancelled.' : 'The scanner connection failed or timed out.'); + redirect: 'manual', signal: combined, cache: 'no-store' }); + } catch (error) { + if (signal?.aborted) throw new Error('Scan cancelled.'); + // A certificate that fails verification is settled and security-relevant, + // not a blip: told apart by its code (Node's, in the cause chain). + if (isCertificateUntrustedError(error)) { + throw new ScannerError('The scanner certificate could not be verified.', 'untrusted-connection', { cause: error }); + } + // The cause is kept for the log's one-word diagnosis (ECONNREFUSED, a + // timeout); its message never reaches the user. + throw new ScannerError('The scanner connection failed or timed out.', 'unreachable', { cause: error }); + } + // A browser-style fetch reports a manual redirect as `opaqueredirect`; Node's as the 3xx itself. + if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) { + await response.body?.cancel().catch(() => {}); + throw new ScannerError('The scanner answered with a redirect, which is never followed.', 'untrusted-connection', { status: response.status }); } if (!accepted.includes(response.status)) { await response.body?.cancel().catch(() => {}); - const messages: Record = { 401: 'Scanner credential is invalid or expired.', 403: 'Scanner permission denied.', - 404: 'Scan ticket expired or is unavailable.', 408: 'Scanner upload timed out.', 410: 'Scan ticket expired.', - 413: 'Selected content exceeds the scanner limit.', 429: 'Scanner quota reached. Try again later.', 503: 'Scanner is busy or unavailable.' }; - throw new Error(messages[response.status] ?? 'The scanner could not complete this request.'); + const [message, reason] = STATUS_FAILURES[response.status] ?? ['The scanner could not complete this request.', 'scanner-error']; + throw new ScannerError(message, reason, { status: response.status }); } if (response.status === 204) return null; const reader = response.body?.getReader(); @@ -148,7 +209,12 @@ export class ScannerTransport { if (size > 256 * 1024) { await reader.cancel(); throw new Error('The scanner response exceeded the limit.'); } chunks.push(part.value); } - } catch { throw new Error('The scanner response was incomplete or exceeded the limit.'); } + } catch (error) { + if (signal?.aborted) throw new Error('Scan cancelled.'); + // A body that stopped arriving before the deadline is the connection's + // fault; one that was too large or broken is the scanner's. + throw new ScannerError('The scanner response was incomplete or exceeded the limit.', timeout.aborted ? 'unreachable' : 'scanner-error', { cause: error }); + } try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Error('The scanner returned no usable result.'); } } diff --git a/apps/desktop/electron/services/assistant-mailbox-download.ts b/apps/desktop/electron/services/assistant-mailbox-download.ts index 7f468161..83d01296 100644 --- a/apps/desktop/electron/services/assistant-mailbox-download.ts +++ b/apps/desktop/electron/services/assistant-mailbox-download.ts @@ -8,6 +8,7 @@ import { getIsQuitting, getSystemSuspended } from '../shared'; import { requireAccountStorage, requireTargetAccountId, resolveNamedOrActiveAccountTarget } from './account-target'; import { readRegistryAccounts } from './accounts-registry'; +import { applyCertificatePin } from './certificate-trust'; import { attachImapBearer, getAccessTokenForMailHost } from './oauth-service'; import { narrowSavedTransport, resolveVaultPassword, vaultIdCandidates, vaultRefusalMessage, @@ -53,8 +54,12 @@ async function credentials(accountId: string, signal: AbortSignal): Promise<{ co config = applied.config; saved = vaulted; } - // Core owns certificate/encryption checks. OAuth's refresh closure retains - // the same host binding for subsequent reconnects and pool connections. + // Core owns certificate/encryption checks; the certificate this account + // approved for its server (or none) is main's, never the registry's. OAuth's + // refresh closure retains the same host binding for subsequent reconnects and + // pool connections. No approval question from here: an agent's download is not + // the user reconnecting, so an untrusted certificate just fails it. + config = await waitForAbortableOperation(applyCertificatePin(config, 'imap', vaultIdCandidates(accountId, config.username, config.host)), signal); return { config: attachImapBearer(config), saved }; } diff --git a/apps/desktop/electron/services/attachment-cache.ts b/apps/desktop/electron/services/attachment-cache.ts index 5e809bfe..3f7884c8 100644 --- a/apps/desktop/electron/services/attachment-cache.ts +++ b/apps/desktop/electron/services/attachment-cache.ts @@ -17,7 +17,7 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; -import { resolveAccountTarget } from './account-target'; +import { resolveNamedOrActiveAccountTarget } from './account-target'; import { getDbEncryptionKey } from './db-key-store'; const logger = createLogger('attachment-cache'); @@ -624,7 +624,7 @@ export async function resolveAttachmentFile( throw new AttachmentError('Invalid attachment request', 400); } - const { storage, syncEngine, accountId: owner } = await resolveAccountTarget(accountId); + const { storage, syncEngine, accountId: owner } = await resolveNamedOrActiveAccountTarget(accountId); const email = await storage.getEmail(emailId); if (!email) throw new AttachmentError('Email not found', 404); diff --git a/apps/desktop/electron/services/attachment-download-protection.ts b/apps/desktop/electron/services/attachment-download-protection.ts index 0fbc01af..ce5a12e3 100644 --- a/apps/desktop/electron/services/attachment-download-protection.ts +++ b/apps/desktop/electron/services/attachment-download-protection.ts @@ -3,7 +3,9 @@ import { createReadStream } from 'node:fs'; import * as fs from 'node:fs/promises'; import path from 'node:path'; -import { waitForAbortableOperation, type ExtensionManager } from '@sarvinbox/core'; +import { TimeoutError, waitForAbortableOperation, type ExtensionManager } from '@sarvinbox/core'; + +import type { AttachmentScannerSummary, ScanFailureRecord } from '../../src/utils/attachment-scan-failures'; import { markDownloadedFromInternet } from './mark-downloaded'; @@ -71,6 +73,31 @@ export function attachmentScanRequired(manager?: ExtensionManager | null): boole return downloadScanners(manager).some((extension) => extension.enabled && extension.scanner); } +/** + * The scanner extensions that are turned on, for Security → Attachment + * scanning: the same set the download gate scans with (`downloadScanners`), + * whether each can be used, and its last failed scan this session. + */ +export function enabledScannerSummaries( + manager: ExtensionManager | null | undefined, + lastFailure: (extensionId: string) => ScanFailureRecord | null +): AttachmentScannerSummary[] { + if (!manager) return []; + const registry = manager.getRegistry(); + return downloadScanners(manager) + .filter((extension) => extension.enabled && extension.scanner) + .map((extension) => { + const name = registry.getLoaded(extension.id)?.manifest.name; + return { + extensionId: extension.id, + name: typeof name === 'string' && name.trim() ? name.trim().slice(0, 80) : extension.id, + available: isScannerExtensionAvailable(manager, extension.id), + granted: extension.granted, + lastFailure: lastFailure(extension.id), + }; + }); +} + export interface ProtectedDownloadContent { content: Buffer; assertCurrent(): Promise; @@ -205,8 +232,9 @@ export class AttachmentOperationProtection { const controller = new AbortController(); const { signal } = controller; this.requests.set(requestId, controller); + // A TimeoutError, so the scanner can tell its deadline from the user's cancel. const timer = setTimeout( - () => controller.abort(new Error('Attachment download timed out.')), + () => controller.abort(new TimeoutError('Attachment download timed out.')), this.deps.timeoutMs ?? 300_000 ); timer.unref?.(); diff --git a/apps/desktop/electron/services/certificate-trust.ts b/apps/desktop/electron/services/certificate-trust.ts new file mode 100644 index 00000000..9b17e0a7 --- /dev/null +++ b/apps/desktop/electron/services/certificate-trust.ts @@ -0,0 +1,562 @@ +/** + * Which certificate a password account's mail server may present (CASA 4.1.2). + * + * Every mail connection verifies its certificate (resolveTlsOptions in core). + * A server with its own certificate — self-signed, or from a private CA — is + * reachable only once the user has approved that exact certificate, and then + * ONLY that certificate is accepted for that account, transport, host and port: + * a pin. This module owns the pins on the main-process side: + * + * - `applyCertificatePin` puts the account's pin (or none) on a connect config + * right before it is dialled, replacing whatever the config arrived with — + * the window cannot supply or change a pin. + * - The trust question is NEVER asked automatically. A focus/online + * reconnect, a background sync, the pool or the Inbox Agent meeting an + * untrusted certificate gets the refusal at once (the window shows a banner + * pointing to Settings → Accounts). Otherwise anyone on a café network could + * make "Trust this certificate?" pop up unprompted, and one click would hand + * them the password on the retry. + * - Only a connect the USER just started asks: the window arms it with + * `certificates:review` (`armCertificateReview`) right before the connect — + * the add-account test, Settings → Reconnect / Save / Verify, the + * re-enter-password dialog, the onboarding submit. An arm is bound to one + * account and transport, is used by the next connect of that pair, lapses + * after a minute, and is rate-limited so a compromised window cannot raise + * the dialog over and over. The dialog is main's own and native: the window + * cannot click it. + * - The dialog shows the certificate the server presents (fetched by main), the + * account (from main's registry) and why it asks (from main's vault — an + * account saved with the retired "allow self-signed" switch is told so). An + * expired or not-yet-valid certificate cannot be approved. "Trust" stores the + * pin with the account's saved credentials (a write that fails loudly) and + * dials once more — for the same account, or not at all. + * - OAuth connections never use pins and never ask. + * + * A vault that cannot be read gives no pin (the connection verifies against the + * system trust store, which refuses the self-signed server) and approves nothing. + * + * Logs name the account (accountLogLabel), the transport and the outcome — never + * a host, a fingerprint or anything from the certificate. + */ +import { + accountLogLabel, + CERTIFICATE_UNTRUSTED, + CertificateInspectionError, + certificateOutsideValidity, + createLogger, + failureCause, + inspectServerCertificate, + normalizeFingerprint, + type CertificateInspection, + type CertificatePin, + type ConnectionSecurity, + type PresentedCertificate, +} from '@sarvinbox/core'; +import { BrowserWindow, dialog, type MessageBoxOptions, type WebContents } from 'electron'; + +import { readRegistryAccounts } from './accounts-registry'; +import { + getAccountSecrets, + removeAccountCertificatePin, + setAccountCertificatePin, + type CertificateKind, + type CertificatePinRecord, +} from './secure-credential-store'; +import { normalizeHost } from './vault-credentials'; + +const logger = createLogger('certificate-trust'); + +/** The parts of an IMAP/SMTP config a pin is bound to and applied on. */ +export interface PinnableConfig { + host: string; + port: number; + authMethod?: string; + certificatePin?: CertificatePin; +} + +const hasUsablePin = (pin: CertificatePinRecord | undefined): pin is CertificatePinRecord => + !!pin && !!normalizeFingerprint(pin.sha256) && typeof pin.pem === 'string' && !!pin.pem; + +/** + * The certificate approved for this connection — account (any of `ids`), + * transport, host and port all matching — or null. Throws when the vault + * cannot be read, so a caller can never mistake "unreadable" for "none". + */ +export async function findCertificatePin( + ids: readonly string[], + kind: CertificateKind, + host: string, + port: number, +): Promise { + const wanted = normalizeHost(host); + if (!wanted) return null; + for (const id of new Set(ids)) { + if (!id) continue; + const pin = (await getAccountSecrets(id))?.certificates?.[kind]; + if (!hasUsablePin(pin) || normalizeHost(pin.host) !== wanted || pin.port !== port) continue; + return pin; + } + return null; +} + +/** Any certificate this account approved for `kind`, whatever its server. Throws when the vault cannot be read. */ +async function anyCertificatePin(ids: readonly string[], kind: CertificateKind): Promise { + for (const id of new Set(ids)) { + if (!id) continue; + const pin = (await getAccountSecrets(id))?.certificates?.[kind]; + if (pin) return pin; + } + return null; +} + +/** + * `config` with exactly the pin main has for it: the stored one for a password + * account's host and port, else none. A pin the config arrived with (from the + * window) is always dropped, and OAuth never gets one. A vault that cannot be + * read gives none — normal verification, which refuses any certificate the + * system does not trust — never "trusted". + */ +export async function applyCertificatePin(config: C, kind: CertificateKind, ids: readonly string[]): Promise { + const { certificatePin: _fromTheWindow, ...rest } = config; + if (config.authMethod === 'oauth2') return rest as C; + let pin: CertificatePinRecord | null = null; + try { + pin = await findCertificatePin(ids, kind, config.host, config.port); + } catch (error) { + logger.warn(`[Certificates] approved certificates unreadable for a ${kind} connection of ${accountLogLabel(ids[0])} (${failureCause(error)}); verifying against the system trust store only`); + } + return (pin ? { ...rest, certificatePin: { sha256: pin.sha256, pem: pin.pem } } : rest) as C; +} + +export interface CertificateTrustRequest { + kind: CertificateKind; + /** The account's vault ids; a new pin is stored under the first, and the review arm is matched on it. */ + ids: readonly string[]; + host: string; + port: number; + security: ConnectionSecurity; + /** The window that asked; the dialog is modal to it. May be null. */ + window?: BrowserWindow | null; +} + +export type CertificateTrustOutcome = + /** Something changed (a certificate was approved, or a pin removed): dial again. */ + | { outcome: 'retry' } + | { outcome: 'refused'; message: string; retryable: boolean }; + +const KIND_LABEL: Record = { imap: 'incoming mail (IMAP)', smtp: 'outgoing mail (SMTP)' }; + +/** The user chose Cancel: the account stays refused until they review it from the settings. */ +export function certificateDeclinedMessage(host: string, port: number): string { + return `Sarv Inbox did not connect to ${host}:${port} because the certificate it presents has not been approved. ` + + 'To review the certificate again, open Settings → Accounts and reconnect the account.'; +} + +function certificateDateMessage(host: string, port: number, problem: 'expired' | 'not-yet-valid'): string { + return problem === 'expired' + ? `The certificate ${host}:${port} presents has expired, so it cannot be trusted. Ask the server's administrator to renew it.` + : `The certificate ${host}:${port} presents is not valid yet, so it cannot be trusted. Check this computer's date and time, or ask the server's administrator.`; +} + +function certificateUnavailableMessage(host: string, port: number): string { + return `Sarv Inbox could not fetch the certificate ${host}:${port} presents, so it cannot be reviewed right now. Try reconnecting the account again.`; +} + +function certificateNotSavedMessage(host: string, port: number): string { + return `Sarv Inbox could not save the certificate you approved for ${host}:${port}, so it is not trusted yet. Try again.`; +} + +/** The retry after an approval would not reach the account that asked. */ +export const ACCOUNT_CHANGED_DURING_REVIEW = 'The account on screen changed while the certificate was being reviewed, so Sarv Inbox did not connect. Reconnect the account to try again.'; + +/** What main's own records say about the account asking: its address (registry) and whether it used the retired switch (vault). */ +interface AccountFacts { + label: string | null; + legacyInsecureTLS: boolean; +} + +async function accountFacts(ids: readonly string[], kind: CertificateKind): Promise { + let label: string | null = null; + try { + label = readRegistryAccounts().find((account) => ids.includes(account.id))?.email || null; + } catch { /* wording only: no account line */ } + let legacyInsecureTLS = false; + try { + for (const id of new Set(ids)) { + if (id && (await getAccountSecrets(id))?.[kind]?.allowInsecureTLS === true) { + legacyInsecureTLS = true; + break; + } + } + } catch { /* wording only */ } + return { label, legacyInsecureTLS }; +} + +const describeLines = (req: CertificateTrustRequest, leaf: PresentedCertificate, facts: AccountFacts): string[] => [ + ...(facts.label ? [`Account: ${facts.label}`] : []), + `Server: ${req.host}:${req.port} (${KIND_LABEL[req.kind]})`, + `Issued to: ${oneLine(leaf.subject)}`, + `Issued by: ${oneLine(leaf.issuer)}`, + `Valid from: ${leaf.validFrom}`, + `Valid until: ${leaf.validTo}`, + 'SHA-256 fingerprint:', + leaf.sha256, +]; + +/** A certificate's distinguished name (Node prints one field per line) on one line. */ +function oneLine(name: string): string { + return name.split('\n').map((part) => part.trim()).filter(Boolean).join(', '); +} + +const NO_FACTS: AccountFacts = { label: null, legacyInsecureTLS: false }; + +/** + * The approval dialog: Cancel is the default, and the only other choice trusts + * exactly this certificate. `replacing` is ANY certificate the account already + * trusts for this transport: trusting a new one replaces it, so the dialog says + * so — "CHANGED" when it is the same server, the old server otherwise. + */ +export function trustDialogOptions( + req: CertificateTrustRequest, + leaf: PresentedCertificate, + replacing: CertificatePinRecord | null, + facts: AccountFacts = NO_FACTS, +): MessageBoxOptions { + const sameServer = !!replacing && normalizeHost(replacing.host) === normalizeHost(req.host) && replacing.port === req.port; + const intro = replacing + ? (sameServer + ? `The certificate for ${req.host} has CHANGED since you approved it.` + : `This account already trusts a certificate for ${replacing.host}:${replacing.port}. Trusting this one REPLACES it.`) + + ' If you did not expect this, someone may be intercepting the connection — choose Cancel.' + : facts.legacyInsecureTLS + ? `This account was set to accept any certificate from its server. Sarv Inbox now accepts only a certificate you approve, so it asks you once.` + : `${req.host} presented a certificate that your system does not trust.`; + return { + type: 'warning', + title: 'Untrusted certificate', + message: replacing ? `Trust the new certificate for ${req.host}?` : `Trust the certificate for ${req.host}?`, + detail: [ + intro, + '', + ...describeLines(req, leaf, facts), + ...(replacing ? ['', `Currently trusted (${replacing.host}:${replacing.port}):`, replacing.sha256] : []), + '', + 'Trust it only if you know this server uses its own certificate and the fingerprint matches the one your administrator gave you. ' + + 'Sarv Inbox will then accept exactly this certificate for this server, and refuse every other one.', + ].join('\n'), + buttons: ['Trust this certificate', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }; +} + +/** For a certificate that cannot be approved: no trust button at all. */ +export function untrustableDialogOptions(req: CertificateTrustRequest, leaf: PresentedCertificate, problem: 'expired' | 'not-yet-valid', facts: AccountFacts = NO_FACTS): MessageBoxOptions { + return { + type: 'error', + title: 'Certificate cannot be trusted', + message: problem === 'expired' ? `The certificate for ${req.host} has expired.` : `The certificate for ${req.host} is not valid yet.`, + detail: [ + `${certificateDateMessage(req.host, req.port, problem)} Sarv Inbox did not connect and did not send your password.`, + '', + ...describeLines(req, leaf, facts), + ].join('\n'), + buttons: ['OK'], + defaultId: 0, + cancelId: 0, + noLink: true, + }; +} + +/** For a pin that now blocks a certificate the system trusts. */ +export function systemTrustedDialogOptions(req: CertificateTrustRequest, leaf: PresentedCertificate, facts: AccountFacts = NO_FACTS): MessageBoxOptions { + return { + type: 'warning', + title: 'Certificate changed', + message: `${req.host} now presents a certificate your system trusts.`, + detail: [ + 'It is not the certificate you approved for this account, so Sarv Inbox refused it. If the server has switched to a certificate from a public authority, ' + + 'stop using the approved certificate and Sarv Inbox will check this server like any other.', + '', + ...describeLines(req, leaf, facts), + ].join('\n'), + buttons: ['Stop using the approved certificate', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }; +} + +/** The window an IPC request came from — the approval dialog's parent — or null. */ +export function requestingWindow(event: unknown): BrowserWindow | null { + const sender = (event as { sender?: unknown } | null | undefined)?.sender; + if (!sender) return null; + try { + return BrowserWindow.fromWebContents(sender as WebContents) ?? null; + } catch { + return null; + } +} + +/** Test seam: the network inspection, the dialog and the clock. */ +export interface CertificateTrustDeps { + inspect: typeof inspectServerCertificate; + showMessageBox: (window: BrowserWindow | null, options: MessageBoxOptions) => Promise<{ response: number }>; + now: () => number; +} + +const defaultDeps: CertificateTrustDeps = { + inspect: (target) => inspectServerCertificate(target), + showMessageBox: (window, options) => (window && !window.isDestroyed() ? dialog.showMessageBox(window, options) : dialog.showMessageBox(options)), + now: () => Date.now(), +}; +let deps: CertificateTrustDeps = defaultDeps; + +/** Replace the inspection / dialog / clock for a test; returns a restore function. */ +export function setCertificateTrustDepsForTest(overrides: Partial): () => void { + deps = { ...defaultDeps, ...overrides }; + return () => { deps = defaultDeps; }; +} + +// ===== The review arm: only a connect the user just started may ask ========== + +/** How long an arm waits for its connect. */ +export const REVIEW_ARM_TTL_MS = 60_000; +/** One arm per account+transport per this long: the window cannot raise the dialog over and over. */ +export const REVIEW_ARM_INTERVAL_MS = 10_000; +/** And at most this many arms a minute across all accounts (fabricated ids included). */ +export const REVIEW_ARMS_PER_MINUTE = 10; + +const armKey = (accountId: string, kind: CertificateKind): string => `${accountId}\u0000${kind}`; +const armedUntil = new Map(); +const lastArmedAt = new Map(); +let recentArms: number[] = []; + +/** + * The user just asked to (re)connect this account's `kind` server from a form: + * its next connect may ask about an untrusted certificate. Refused ('too-soon') + * within REVIEW_ARM_INTERVAL_MS of the last arm for the same pair, or past the + * per-minute cap. + */ +export function armCertificateReview(accountId: string, kind: CertificateKind): 'armed' | 'too-soon' { + const now = deps.now(); + recentArms = recentArms.filter((at) => at > now - 60_000); + for (const [key, at] of lastArmedAt) if (at <= now - REVIEW_ARM_TTL_MS) lastArmedAt.delete(key); + for (const [key, until] of armedUntil) if (until < now) armedUntil.delete(key); + const key = armKey(accountId, kind); + const last = lastArmedAt.get(key); + if ((last !== undefined && now - last < REVIEW_ARM_INTERVAL_MS) || recentArms.length >= REVIEW_ARMS_PER_MINUTE) { + logger.info(`[Certificates] ${kind} review for ${accountLogLabel(accountId)}: not armed (too soon after the last one)`); + return 'too-soon'; + } + lastArmedAt.set(key, now); + recentArms.push(now); + armedUntil.set(key, now + REVIEW_ARM_TTL_MS); + return 'armed'; +} + +/** Use up the arm for this account+transport: true when the user armed it and it has not lapsed. */ +export function takeCertificateReview(accountId: string | undefined, kind: CertificateKind): boolean { + if (!accountId) return false; + const key = armKey(accountId, kind); + const until = armedUntil.get(key); + armedUntil.delete(key); + return until !== undefined && until >= deps.now(); +} + +// ===== The question ========================================================== + +const keyOf = (owner: string, kind: CertificateKind, host: string, port: number): string => [owner, kind, normalizeHost(host), port].join('\u0000'); + +/** Questions on screen or about to be, per account+transport+host+port: concurrent armed connects share one. */ +const inFlight = new Map>(); + +/** + * Ask the user whether to trust the certificate this server presents, after + * an ARMED connect was refused over it. Only `withCertificateApproval` calls + * this, and only for a connect that took a review arm. + */ +export function requestCertificateTrust(req: CertificateTrustRequest): Promise { + const owner = req.ids[0] ?? ''; + const key = keyOf(owner, req.kind, req.host, req.port); + const running = inFlight.get(key); + if (running) return running; + const decision = decide(req, owner).finally(() => inFlight.delete(key)); + inFlight.set(key, decision); + return decision; +} + +async function decide(req: CertificateTrustRequest, owner: string): Promise { + const label = `${req.kind} certificate for ${accountLogLabel(owner)}`; + let inspection: CertificateInspection; + try { + inspection = await deps.inspect({ host: req.host, port: req.port, security: req.security, protocol: req.kind }); + } catch (error) { + const reason = error instanceof CertificateInspectionError ? error.reason : failureCause(error); + logger.warn(`[Certificates] ${label}: could not be fetched for review (${reason})`); + return { outcome: 'refused', message: certificateUnavailableMessage(req.host, req.port), retryable: true }; + } + const { leaf } = inspection; + + let exact: CertificatePinRecord | null; + let anyForKind: CertificatePinRecord | null; + try { + exact = await findCertificatePin(req.ids, req.kind, req.host, req.port); + anyForKind = exact ?? await anyCertificatePin(req.ids, req.kind); + } catch (error) { + // Nothing can be approved into a store that cannot be read. + logger.warn(`[Certificates] ${label}: approved certificates unreadable (${failureCause(error)}); not asking`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + const facts = await accountFacts(req.ids, req.kind); + + const dateProblem = certificateOutsideValidity(leaf, deps.now()); + if (dateProblem) { + logger.warn(`[Certificates] ${label}: presented certificate is ${dateProblem}; cannot be approved`); + await deps.showMessageBox(req.window ?? null, untrustableDialogOptions(req, leaf, dateProblem, facts)); + return { outcome: 'refused', message: certificateDateMessage(req.host, req.port, dateProblem), retryable: false }; + } + + if (inspection.systemTrusted) { + if (!exact) { + // The certificate verifies now: the refusal was for a certificate this + // server no longer presents. Dial again; nothing to approve. + logger.info(`[Certificates] ${label}: now verified by the system trust store; retrying without a question`); + return { outcome: 'retry' }; + } + const { response } = await deps.showMessageBox(req.window ?? null, systemTrustedDialogOptions(req, leaf, facts)); + if (response !== 0) { + logger.info(`[Certificates] ${label}: kept the approved certificate; refused the system-trusted one`); + return { outcome: 'refused', message: certificateDeclinedMessage(req.host, req.port), retryable: false }; + } + try { + await removeAccountCertificatePin(req.ids, req.kind); + } catch (error) { + logger.warn(`[Certificates] ${label}: could not remove the approved certificate (${failureCause(error)})`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + logger.info(`[Certificates] ${label}: approved certificate removed; the system trust store decides`); + return { outcome: 'retry' }; + } + + // Any certificate already trusted for this transport is named as replaced, + // never silently overwritten (a re-approval of the very same one is not a change). + const replacing = anyForKind && (anyForKind.sha256 !== leaf.sha256 || !exact) ? anyForKind : null; + const { response } = await deps.showMessageBox(req.window ?? null, trustDialogOptions(req, leaf, replacing, facts)); + if (response !== 0) { + logger.info(`[Certificates] ${label}: declined${facts.legacyInsecureTLS ? ' (account had accepted any certificate before)' : ''}`); + return { outcome: 'refused', message: certificateDeclinedMessage(req.host, req.port), retryable: false }; + } + try { + await setAccountCertificatePin(owner, req.kind, { + host: normalizeHost(req.host), + port: req.port, + sha256: leaf.sha256, + pem: leaf.pem, + approvedAt: deps.now(), + subject: leaf.subject, + issuer: leaf.issuer, + validFrom: leaf.validFrom, + validTo: leaf.validTo, + }); + } catch (error) { + logger.warn(`[Certificates] ${label}: approved, but could not be saved (${failureCause(error)})`); + return { outcome: 'refused', message: certificateNotSavedMessage(req.host, req.port), retryable: true }; + } + logger.info(`[Certificates] ${label}: approved${replacing ? ' (replaced the earlier one)' : ''}${facts.legacyInsecureTLS ? ' (account had accepted any certificate before)' : ''}`); + return { outcome: 'retry' }; +} + +/** What a connect handler answers: success, or a failure that may carry the certificate code. */ +export interface ConnectAnswer { + success: boolean; + error?: string; + code?: string; + retryable?: boolean; +} + +export interface ApprovalOptions { + /** + * What the retry must still be connecting for — e.g. the account on screen, + * whose engine or SMTP client the handler resolves when it runs. Read right + * after the first attempt and again before the retry; if it changed (the user + * switched accounts while the dialog was open), there is no retry. + */ + sameTarget?: () => unknown; +} + +/** + * Run a connect. The review arm for its account+transport is used up FIRST + * (whether or not anything goes wrong), so only the connect the user started + * can ask. When it was refused over the certificate: + * - not armed (every automatic path), or OAuth (`request` null): the refusal + * is returned at once — no inspection, no dialog; + * - armed: main asks, and on approval runs the connect once more, for the + * same target (`options.sameTarget`) or not at all. A second certificate + * refusal is returned as it is (the server changed its certificate between + * the question and the retry: no second question). + */ +export async function withCertificateApproval( + attempt: () => Promise, + request: () => CertificateTrustRequest | null, + options: ApprovalOptions = {}, +): Promise { + const req = request(); + const armed = req ? takeCertificateReview(req.ids[0], req.kind) : false; + const first = await attempt(); + if (first.success || first.code !== CERTIFICATE_UNTRUSTED || !req || !armed) return first; + const target = options.sameTarget?.(); + const decision = await requestCertificateTrust(req); + if (decision.outcome === 'refused') { + return { success: false, error: decision.message, retryable: decision.retryable, code: CERTIFICATE_UNTRUSTED }; + } + if (options.sameTarget && options.sameTarget() !== target) { + logger.warn(`[Certificates] ${req.kind} review for ${accountLogLabel(req.ids[0])}: the account changed during the question; not retrying`); + return { success: false, error: ACCOUNT_CHANGED_DURING_REVIEW, retryable: true, code: CERTIFICATE_UNTRUSTED }; + } + return attempt(); +} + +/** What the account settings show about an approved certificate (no PEM). */ +export interface CertificatePinSummary { + host: string; + port: number; + sha256: string; + approvedAt: number; + subject: string; + issuer: string; + validTo: string; +} + +/** The approved certificates of one account, per transport. Throws when the vault cannot be read. */ +export async function listAccountCertificates(accountId: string): Promise>> { + const certificates = (await getAccountSecrets(accountId))?.certificates ?? {}; + const out: Partial> = {}; + for (const kind of ['imap', 'smtp'] as const) { + const pin = certificates[kind]; + if (!pin) continue; + out[kind] = { host: pin.host, port: pin.port, sha256: pin.sha256, approvedAt: pin.approvedAt, subject: pin.subject, issuer: pin.issuer, validTo: pin.validTo }; + } + return out; +} + +/** + * Stop trusting the approved certificate for `kind` of this account. Automatic + * reconnects then meet the refusal (no question); reconnecting from the account + * settings asks again. Answers whether one was removed; throws when the vault + * cannot be read or written. + */ +export async function removeAccountCertificate(accountId: string, kind: CertificateKind): Promise { + const removed = await removeAccountCertificatePin([accountId], kind); + logger.info(`[Certificates] ${kind} certificate for ${accountLogLabel(accountId)}: ${removed ? 'removed by the user' : 'nothing to remove'}`); + return removed; +} + +/** Test seam: forget every question and arm. */ +export function resetCertificateTrustForTest(): void { + inFlight.clear(); + armedUntil.clear(); + lastArmedAt.clear(); + recentArms = []; +} diff --git a/apps/desktop/electron/services/core-db.ts b/apps/desktop/electron/services/core-db.ts index 53f04706..1ec019b1 100644 --- a/apps/desktop/electron/services/core-db.ts +++ b/apps/desktop/electron/services/core-db.ts @@ -225,15 +225,25 @@ export function getBlob(key: string): Buffer | null { } } +/** + * Store a blob. THROWS when the store cannot be written, which `setBlob` only + * logs. A writer that tells the user something was saved (an approved + * certificate) writes with this, so a failed write is reported, not believed. + */ +export function writeBlob(key: string, data: Buffer): void { + if (!key) throw new Error('A blob needs a key'); + getCoreDb() + .prepare( + `INSERT INTO core_blobs (key, data, updated_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at`, + ) + .run(key, data, Date.now()); +} + export function setBlob(key: string, data: Buffer): void { if (!key) return; try { - getCoreDb() - .prepare( - `INSERT INTO core_blobs (key, data, updated_at) VALUES (?, ?, ?) - ON CONFLICT(key) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at`, - ) - .run(key, data, Date.now()); + writeBlob(key, data); } catch (e) { logger.error('[CoreDB] setBlob failed:', key, e); } diff --git a/apps/desktop/electron/services/db-compact.ts b/apps/desktop/electron/services/db-compact.ts index da7bf6dd..f8158617 100644 --- a/apps/desktop/electron/services/db-compact.ts +++ b/apps/desktop/electron/services/db-compact.ts @@ -28,6 +28,7 @@ import { Worker } from 'node:worker_threads'; import { accountLogLabel, + errorDiagnostic, compactionEstimate, formatBytes, hasCompactionHeadroom, @@ -38,7 +39,7 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; -import { getAccountRuntime } from '../shared'; +import { getAccountRuntime, getCurrentAccountId, setCurrentAccount } from '../shared'; import type { CompactWorkerResult } from '../workers/db-compact.worker'; import { @@ -50,6 +51,7 @@ import { releaseAccountMaintenance, } from './accounts-runtime'; import { getDbEncryptionKey } from './db-key-store'; +import { rebindOutboxStorage } from './outbox-service'; @@ -209,6 +211,9 @@ export async function compactAccountDatabase(accountId: string): Promise { + let reopened = false; + for (let attempt = 0; ; attempt++) { + try { + reopened = !!(await ensureAccountRuntime(accountId)); + break; + } catch (error) { + const delay = REOPEN_RETRY_DELAYS_MS[attempt]; + logger.error( + `[Compact] FAILED to reopen ${accountLogLabel(accountId)} after compaction ` + + `(attempt ${attempt + 1} of ${REOPEN_RETRY_DELAYS_MS.length + 1})`, + errorDiagnostic(error), + ); + if (delay === undefined) return; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + if (reopened && wasActive && getCurrentAccountId() === null) { + setCurrentAccount(accountId); try { - await ensureAccountRuntime(accountId); + rebindOutboxStorage(); } catch (error) { - logger.error(`[Compact] FAILED to reopen ${accountLogLabel(accountId)} after compaction`, error); + logger.warn(`[Compact] rebinding the outbox of ${accountLogLabel(accountId)} failed`, errorDiagnostic(error)); } + logger.info(`[Compact] ${accountLogLabel(accountId)} is active again`); } } diff --git a/apps/desktop/electron/services/external-link-gate.ts b/apps/desktop/electron/services/external-link-gate.ts new file mode 100644 index 00000000..2646fed1 --- /dev/null +++ b/apps/desktop/electron/services/external-link-gate.ts @@ -0,0 +1,360 @@ +/** + * The external-link gate: the ONE way the main process hands a URL the app did + * not write to the operating system (CASA 5.1.2 — "a warning is displayed when + * redirecting to untrusted content"). + * + * Every path that opens an address from outside the app comes through here: + * a link clicked in a message (the renderer's `app:openExternal`, from the + * standard view, the chat view and its "Open link"), a frame navigating to a + * web page (the navigation guards' `external` verdict), a window-open request + * (an email's `target="_blank"` link, an extension's homepage), and a sender's + * unsubscribe page. It runs in MAIN, so a compromised renderer cannot skip it. + * + * What it decides, in order: + * 1. Only http:, https: and mailto: leave the app. Anything else (file:, smb:, + * an OS-registered custom protocol) is refused outright — email content is + * attacker-controlled. + * 2. mailto: opens at once. It loads no web content; it starts a message. + * 3. A link the app wrote (`isAppLink`, the app-links allowlist in core) opens + * at once. + * 4. A host the user chose "Don't ask again" for opens at once — exact + * hostname, never a subdomain. A store that cannot be read means ASK: an + * unreadable store and an empty one are the same value and opposite facts, + * and "trusted" is the wrong default for both. Never for a link through a + * known forwarder (`isLinkWrapper`: Safe Links, google.com/url, Translate, + * shorteners, click trackers): trusting the first hop would trust every + * destination behind it, so those always ask and offer no checkbox. + * 5. Everything else gets a native warning naming the host (punycode, so a + * look-alike Unicode host shows as xn--…) and the address — and, for a + * forwarder that says where it goes, the destination's host too. Cancel is + * the default. Nothing opens unless the user chooses "Open link". + * + * One warning at a time per window: a request that arrives while one is open + * in that window is dropped, and only their number is logged when it closes. + * The email body runs no scripts, but a frame can still fire navigations. + * + * Logging: never the URL, its host or its path (they are the mail's). Only the + * scheme (`urlSchemeForLog`), booleans, counts and `errorDiagnostic`. + */ +import { + createLogger, + errorDiagnostic, + isAppLink, + isLinkWrapper, + truncateMiddle, + unwrappedDestination, + urlSchemeForLog, +} from '@sarvinbox/core'; +import { BrowserWindow, dialog, shell, type MessageBoxOptions, type MessageBoxReturnValue } from 'electron'; + +import { deleteBlob, readBlob, setBlob } from './core-db'; + +const logger = createLogger('external-link-gate'); + +/** The only schemes handed to the OS. */ +export const OPENABLE_SCHEMES: ReadonlySet = new Set(['http:', 'https:', 'mailto:']); + +/** How many "Don't ask again" hosts are kept; the oldest is dropped past it. */ +export const MAX_REMEMBERED_HOSTS = 500; + +/** How much of an address the warning shows; the middle of a longer one is cut. */ +export const MAX_SHOWN_URL_CHARS = 200; + +/** + * The longest host the warning shows whole. A DNS name is at most 253 + * characters, so any real host is shown exactly; a longer one (the URL parser + * does not enforce DNS lengths) keeps its END, which names the domain. + */ +export const MAX_SHOWN_HOST_CHARS = 253; + +/** The core-DB blob holding the remembered hosts, oldest first. */ +export const REMEMBERED_HOSTS_BLOB_KEY = 'external-link-hosts'; + +export const OPEN_BUTTON = 0; +export const CANCEL_BUTTON = 1; + +/** + * - `opened` handed to the OS + * - `cancelled` the user said no (or closed the warning) + * - `refused` not a URL, or a scheme that never leaves the app + * - `busy` dropped: a warning was already open in that window + * - `failed` the warning could not be shown, or the OS could not open it + */ +export type ExternalLinkOutcome = 'opened' | 'cancelled' | 'refused' | 'busy' | 'failed'; + +/** Where "Don't ask again" hosts are kept. */ +export interface RememberedHostStore { + /** The hosts, oldest first. THROWS when the store cannot be read. */ + read(): string[]; + write(hosts: readonly string[]): void; + clear(): void; +} + +export interface ExternalLinkGateDeps { + openExternal(url: string): Promise; + /** Show the warning, attached to `parent` when there is one. */ + showWarning(parent: W | null, options: MessageBoxOptions): Promise>; + store: RememberedHostStore; +} + +export interface ExternalLinkGate { + /** Open `url` if the rules above allow it. Never rejects. */ + open(url: unknown, parent: W | null): Promise; + /** + * Open an address MAIN built itself from fixed parts (the Translate page), + * without the warning. Still http/https/mailto only. Never rejects. + */ + openAppBuilt(url: URL): Promise; + /** How many hosts open without asking. THROWS when the store cannot be read. */ + rememberedHostCount(): number; + /** Forget every remembered host; the next link to any of them asks again. */ + forgetRememberedHosts(): void; +} + +/** A URL the gate may hand to the OS, parsed; null for anything else. */ +function parseOpenable(url: unknown): URL | null { + if (typeof url !== 'string') return null; + try { + const parsed = new URL(url); + return OPENABLE_SCHEMES.has(parsed.protocol) ? parsed : null; + } catch { + return null; + } +} + +/** The host as the warning shows it: exactly, unless it is longer than any DNS name. */ +function shownHost(hostname: string): string { + return hostname.length <= MAX_SHOWN_HOST_CHARS + ? hostname + : `…${hostname.slice(hostname.length - (MAX_SHOWN_HOST_CHARS - 1))}`; +} + +/** + * The warning for one web link. `parsed.hostname` and `parsed.href` are the + * URL parser's ASCII forms: a Unicode host is punycode (`xn--…`) and anything + * else non-ASCII in the address is percent-encoded, so neither line can hide a + * look-alike character or a direction override. + * + * A link through a known forwarder gets no "Don't ask again" (see + * LINK_WRAPPERS) and, when it carries its destination as a URL parameter, a + * second host line naming where it goes on to — parsed the same way, shown + * only, never opened in place of the link. + */ +export function linkWarningOptions(parsed: URL): MessageBoxOptions { + const host = shownHost(parsed.hostname); + const forwarder = isLinkWrapper(parsed); + const destination = forwarder ? unwrappedDestination(parsed) : null; + const lines = [host]; + if (destination) lines.push(`It goes on to: ${shownHost(destination.hostname)}`); + lines.push('', truncateMiddle(parsed.href, MAX_SHOWN_URL_CHARS, '…')); + if (parsed.protocol === 'http:') lines.push('', 'This link is not secure (http).'); + if (forwarder) lines.push('', 'This site forwards links to other sites, so its links always ask.'); + return { + type: 'warning', + title: 'Open link', + message: 'Open this link in your browser?', + detail: lines.join('\n'), + buttons: ['Open link', 'Cancel'], + defaultId: CANCEL_BUTTON, + cancelId: CANCEL_BUTTON, + // No checkbox at all for a forwarder: remembering it would trust every + // site it forwards to. + ...(forwarder ? {} : { checkboxLabel: `Don't ask again for ${host}`, checkboxChecked: false }), + // Windows: keep the two buttons as buttons, not "command links". + noLink: true, + }; +} + +/** A host as stored: the parser's lower-case ASCII hostname, nothing else. */ +function isStorableHost(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= 1024 + && value === value.toLowerCase() && !/\s/.test(value); +} + +export function createExternalLinkGate(deps: ExternalLinkGateDeps): ExternalLinkGate { + /** The window a warning is open in (or NO_WINDOW), and what was dropped meanwhile. */ + const asking = new Map(); + const NO_WINDOW = {}; + + const isRemembered = (host: string): boolean => { + try { + return deps.store.read().includes(host); + } catch (error) { + logger.warn('[ExternalLink] The sites that open without asking could not be read, so this link asks:', errorDiagnostic(error)); + return false; + } + }; + + /** Write the host down; true only when reading the list back shows it there. */ + const remember = (host: string): boolean => { + let hosts: string[]; + try { + hosts = deps.store.read(); + } catch (error) { + // Never overwrite a list that could not be read: writing [host] over it + // would forget every other site the user chose. + logger.warn('[ExternalLink] The sites that open without asking could not be read; this one is not remembered:', errorDiagnostic(error)); + return false; + } + const next = [...hosts.filter((stored) => stored !== host), host].slice(-MAX_REMEMBERED_HOSTS); + try { + deps.store.write(next); + // Read back: the core-DB write logs and swallows its own failures, so + // only the list as stored says whether the next link will skip the warning. + return deps.store.read().includes(host); + } catch (error) { + logger.warn('[ExternalLink] The site could not be remembered:', errorDiagnostic(error)); + return false; + } + }; + + const launch = async (parsed: URL): Promise => { + try { + // The parsed form, so what opens is exactly what the warning showed. + await deps.openExternal(parsed.href); + return 'opened'; + } catch (error) { + logger.warn(`[ExternalLink] The browser could not open a ${parsed.protocol} link:`, errorDiagnostic(error)); + return 'failed'; + } + }; + + const open = async (url: unknown, parent: W | null): Promise => { + const parsed = parseOpenable(url); + if (!parsed) { + // The scheme only: the URL is typically a link clicked in a message. + logger.warn('[ExternalLink] Refused a link with an unsupported scheme:', urlSchemeForLog(url)); + return 'refused'; + } + + const key = parent ?? NO_WINDOW; + const pending = asking.get(key); + if (pending) { + pending.dropped += 1; + return 'busy'; + } + + // A forwarder's remembered entry is never honoured: it would trust every + // destination behind it (Safe Links: all mail in the tenant). + const forwarder = isLinkWrapper(parsed); + if (parsed.protocol === 'mailto:' || isAppLink(parsed.href) || (!forwarder && isRemembered(parsed.hostname))) { + return launch(parsed); + } + + const state = { dropped: 0 }; + asking.set(key, state); + let answer: Pick; + try { + answer = await deps.showWarning(parent, linkWarningOptions(parsed)); + } catch (error) { + logger.warn('[ExternalLink] The link warning could not be shown, so nothing opened:', errorDiagnostic(error)); + return 'failed'; + } finally { + asking.delete(key); + if (state.dropped > 0) { + logger.info(`[ExternalLink] Dropped ${state.dropped} more link request(s) while a warning was open`); + } + } + + const confirmed = answer.response === OPEN_BUTTON; + // The forwarder check again, not only the missing checkbox: a forwarder is + // never written down, whatever the dialog answered. + const remembered = confirmed && !forwarder && answer.checkboxChecked === true && remember(parsed.hostname); + // `remembered`: the host is in the list now, not merely that the box was ticked. + logger.info( + `[ExternalLink] Warned before a ${parsed.protocol} link: opened=${confirmed}, remembered=${remembered}, forwarder=${forwarder}`, + ); + if (!confirmed) return 'cancelled'; + return launch(parsed); + }; + + const openAppBuilt = async (url: URL): Promise => { + const parsed = parseOpenable(url instanceof URL ? url.href : undefined); + if (!parsed) { + logger.warn('[ExternalLink] Refused an app-built link with an unsupported scheme:', urlSchemeForLog(url instanceof URL ? url.href : url)); + return 'refused'; + } + return launch(parsed); + }; + + return { + open, + openAppBuilt, + rememberedHostCount: () => deps.store.read().length, + forgetRememberedHosts: () => deps.store.clear(), + }; +} + +/** + * The remembered hosts in the core DB (encrypted at rest), as JSON + * `{ "hosts": [...] }`, oldest first. Read with `readBlob`, which THROWS when + * the store cannot be read; a value that is not that shape throws too — both + * mean "ask", and neither is ever overwritten by a remember. "Forget all" + * deletes the blob, which also clears a damaged one. + */ +export const coreDbRememberedHostStore: RememberedHostStore = { + read() { + const blob = readBlob(REMEMBERED_HOSTS_BLOB_KEY); + if (!blob) return []; + const value = JSON.parse(blob.toString('utf8')) as { hosts?: unknown }; + if (!value || !Array.isArray(value.hosts)) throw new TypeError('remembered hosts: not a host list'); + return value.hosts.filter(isStorableHost); + }, + write(hosts) { + setBlob(REMEMBERED_HOSTS_BLOB_KEY, Buffer.from(JSON.stringify({ hosts }), 'utf8')); + }, + clear() { + deleteBlob(REMEMBERED_HOSTS_BLOB_KEY); + }, +}; + +const gate = createExternalLinkGate({ + openExternal: (url) => shell.openExternal(url), + showWarning: (parent, options) => + parent && !parent.isDestroyed() ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options), + store: coreDbRememberedHostStore, +}); + +/** + * Open a URL the app did not write — a link from a message, a frame, a + * window-open request, a sender's header — in the user's browser or mail + * handler, warning first when its host is not one the app or the user trusts. + * `parent` is the window the warning attaches to (null: none). Never rejects. + */ +export function openExternalUrl(url: unknown, parent: BrowserWindow | null): Promise { + return gate.open(url, parent); +} + +/** + * Open an address MAIN assembled itself from fixed parts — today only the + * Translate menu item's page (`translationUrl`) — without the warning: the + * user chose the app's own command, and the renderer named only what to + * translate, never where to go. NEVER pass a URL that came from mail, a + * header, the renderer, an extension, a provider or configuration; those go + * through `openExternalUrl`. `external-link-paths.test.ts` pins the callers. + */ +export function openAppBuiltUrl(url: URL): Promise { + return gate.openAppBuilt(url); +} + +/** How many sites open without asking. THROWS when the store cannot be read. */ +export function rememberedLinkHostCount(): number { + return gate.rememberedHostCount(); +} + +/** Forget every "Don't ask again" site. */ +export function forgetRememberedLinkHosts(): void { + gate.forgetRememberedHosts(); +} + +/** + * The window an IPC request came from, for the warning to attach to; null when + * there is none (or the sender is already gone). + */ +export function windowOfSender(event: { sender?: Electron.WebContents } | null | undefined): BrowserWindow | null { + try { + return event?.sender ? BrowserWindow.fromWebContents(event.sender) : null; + } catch { + return null; + } +} diff --git a/apps/desktop/electron/services/filter-ai-skip.ts b/apps/desktop/electron/services/filter-ai-skip.ts new file mode 100644 index 00000000..90572da2 --- /dev/null +++ b/apps/desktop/electron/services/filter-ai-skip.ts @@ -0,0 +1,28 @@ +/** + * Whether a user filter keeps the background AI away from an email (the + * filter's "Skip AI checks" option). The one check both AI paths run — the + * per-email pipeline (categorizing, priority, the AI's spam verdict, automatic + * actions and drafted replies) and the bulk categorizer — read from the + * email's own account, so a filter on one account never affects another. + * + * Three answers, because an unreadable store and an empty one are opposite + * facts: `unknown` (the rules could not be read) must neither send the email + * to the AI nor mark it handled. The caller leaves it pending and the next + * pass asks again. + */ +import { errorDiagnostic, filterSkipsAI, logger, type EmailRecord, type FilterRule } from '@sarvinbox/core'; + +export type FilterAiVerdict = 'skip' | 'run' | 'unknown'; + +interface FilterRuleSource { getEnabledFilterRules(): Promise } + +export async function filterAiVerdict(storage: FilterRuleSource, email: EmailRecord): Promise { + let rules: FilterRule[]; + try { + rules = await storage.getEnabledFilterRules(); + } catch (error) { + logger.warn('[Filters] could not read filter rules before AI processing; will retry', errorDiagnostic(error)); + return 'unknown'; + } + return filterSkipsAI(email, rules) ? 'skip' : 'run'; +} diff --git a/apps/desktop/electron/services/host-resolver.ts b/apps/desktop/electron/services/host-resolver.ts new file mode 100644 index 00000000..08727b64 --- /dev/null +++ b/apps/desktop/electron/services/host-resolver.ts @@ -0,0 +1,42 @@ +/** + * How Chromium (the window, `net.fetch`, the updater) turns a host name into an + * address: through the operating system's resolver, never by sending DNS + * packets itself. + * + * On macOS Electron enables Chromium's built-in resolver by default. It reads + * the system's DNS servers and queries them directly over UDP. On a network + * whose DNS server is a local address (an office router such as 10.x or + * 192.168.x), that is "local network" traffic, so macOS 15 and later stop the + * app with "Allow … to find devices on local networks?" — attributed to the + * network-service helper process, which is why it named "Electron" (see + * build/mac-helper-names.js). Declining it can break name lookups. + * + * Going through the system resolver (getaddrinfo, answered by mDNSResponder) + * needs no such permission and honours the same DNS settings, VPN and + * per-domain resolvers. Windows and Linux already default to it, so this + * changes nothing there; it is set on every platform so the behaviour is one + * fact, not three. + */ +import { errorDiagnostic } from '@sarvinbox/core'; + +type HostResolverApp = { configureHostResolver(options: { enableBuiltInResolver?: boolean }): void }; +type WarnLogger = { warn(message: string, ...details: unknown[]): void }; + +/** The options passed to `app.configureHostResolver`. */ +export const SYSTEM_HOST_RESOLVER = Object.freeze({ enableBuiltInResolver: false }); + +/** + * Switch Chromium to the system resolver. Must run after `ready` (Electron + * refuses it earlier) and before the first request. Never throws: if Electron + * refuses, the app still works, with the built-in resolver, and the log says so. + * Returns whether the setting took. + */ +export function useSystemHostResolver(app: HostResolverApp, log: WarnLogger): boolean { + try { + app.configureHostResolver({ ...SYSTEM_HOST_RESOLVER }); + return true; + } catch (error) { + log.warn('[Main] could not switch Chromium to the system DNS resolver', errorDiagnostic(error)); + return false; + } +} diff --git a/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts b/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts index f5b053f5..79b8684f 100644 --- a/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts +++ b/apps/desktop/electron/services/inbox-assistant-agent-setting-tools.ts @@ -24,7 +24,7 @@ import { const FIELDS: readonly FilterCondition['field'][] = ['from', 'to', 'cc', 'subject', 'body', 'domain']; const OPERATORS: readonly FilterCondition['operator'][] = ['contains', 'notContains', 'equals', 'startsWith', 'endsWith']; -const ACTION_TYPES: readonly FilterAction['type'][] = ['markRead', 'star', 'archive', 'delete', 'moveToSpam', 'moveToFolder', 'applyLabel']; +const ACTION_TYPES: readonly FilterAction['type'][] = ['markRead', 'star', 'archive', 'delete', 'moveToSpam', 'moveToFolder', 'applyLabel', 'skipAI']; /** At most one of these per filter: a message can only end up in one place. */ const PLACING = new Set(['archive', 'delete', 'moveToSpam', 'moveToFolder']); /** Existing mail a filter or block never touches: the user's own mail, and mail already gone. */ @@ -38,7 +38,7 @@ const CONDITION_SCHEMA = { type: 'object', additionalProperties: false, required field: { type: 'string', enum: [...FIELDS] }, operator: { type: 'string', enum: [...OPERATORS] }, value: { type: 'string' }, } }; const ACTION_SCHEMA = { type: 'object', additionalProperties: false, required: ['type'], properties: { - type: { type: 'string', enum: [...ACTION_TYPES], description: 'delete moves to Trash.' }, + type: { type: 'string', enum: [...ACTION_TYPES], description: 'delete moves to Trash. skipAI keeps the background AI (categorizing, priority, automatic actions, drafted replies) away from matching mail.' }, value: { type: 'string', description: 'moveToFolder: a folder from list_folders. applyLabel: the label name (created if missing).' }, } }; const RULE_PROPERTIES = { @@ -127,6 +127,8 @@ function mailActionFor(action: FilterAction, folders: FolderRecord[], checked: C case 'delete': return { action: 'trash' }; case 'applyLabel': return { action: 'add_label', labelName: action.value! }; case 'moveToFolder': return { action: 'move', folder: checked.folders.get(action.value!)! }; + // Nothing to change on existing mail: the AI checks the filter when it would run. + case 'skipAI': return undefined; case 'moveToSpam': { const spam = roleFolders(folders, 'spam')[0]; return spam ? { action: 'move', folder: spam } : undefined; diff --git a/apps/desktop/electron/services/inbox-assistant-agent-tools.ts b/apps/desktop/electron/services/inbox-assistant-agent-tools.ts index f98209a6..991e8580 100644 --- a/apps/desktop/electron/services/inbox-assistant-agent-tools.ts +++ b/apps/desktop/electron/services/inbox-assistant-agent-tools.ts @@ -59,6 +59,12 @@ export class InboxAgentRegistry { private resultCount = 0; /** Messages whose body (not just a list row) was read. */ readonly bodiesRead = new Set(); + /** + * Messages already counted in their account's "reviewed" total: read in + * full, sorted from an excerpt by classify_messages, or returned by deep + * search. Each counts once, however many tools looked at it. + */ + readonly reviewed = new Set(); /** The id for one email or attachment, created on first sight. Undefined once the run holds the maximum. */ source(key: string, create: () => Omit): string | undefined { @@ -264,6 +270,15 @@ export async function openAccount(context: InboxAgentToolContext, account: Inbox } } +/** Count one email as reviewed in its account's coverage, once per run. */ +function countReviewed(context: InboxAgentToolContext, source: Pick): void { + if (context.registry.reviewed.has(source.id)) return; + const account = context.accounts.find(item => item.id === source.accountId); + if (!account) return; + context.registry.reviewed.add(source.id); + coverageFor(context, account).reviewedMessages++; +} + export function coverageFor(context: Pick, account: InboxAssistantAccount): InboxAssistantAccountCoverage { let coverage = context.coverage.get(account.id); if (!coverage) { @@ -641,9 +656,9 @@ const readMessage: InboxAgentTool = { } if (!context.registry.bodiesRead.has(source.id)) { context.registry.bodiesRead.add(source.id); - coverage.reviewedMessages++; if (!body || unavailable) coverage.missingBodies++; } + countReviewed(context, source); const declared = await opened.mailbox.storage.getAttachments(email.id); const names = attachmentNames(email, declared); const header = `CC: ${addresses(email.ccAddress).join(', ')}\n`; @@ -777,7 +792,11 @@ const deepSearch: InboxAgentTool = { const block = inboxAssistantEvidenceText({ ...item, id }); if (used + block.length > INBOX_AGENT_LIMITS.deepSearchChars) break; used += block.length; - if (item.kind === 'message') context.registry.bodiesRead.add(id); + // Already in the coverage merged above: marked so no later tool counts it again. + if (item.kind === 'message') { + context.registry.bodiesRead.add(id); + context.registry.reviewed.add(id); + } context.registry.update(id, { text: item.text }); context.registry.show(id, block); blocks.push(block); @@ -859,6 +878,9 @@ const classifyMessages: InboxAgentTool = { for (let index = 0; index < batches.length; index += INBOX_AGENT_LIMITS.classifyParallel) { await Promise.all(batches.slice(index, index + INBOX_AGENT_LIMITS.classifyParallel).map(runBatch)); } + // An email the model judged was reviewed (from its excerpt), and the + // footer's "N of M reviewed" says so. One in a batch that failed was not. + for (const source of sources as InboxAssistantEvidence[]) if (verdicts.has(source.id)) countReviewed(context, source); const counts = new Map(labels.map(label => [label, 0])); const lines = ids.map(id => { const verdict = verdicts.get(id) ?? { label: UNSURE, reason: 'not classified' }; diff --git a/apps/desktop/electron/services/inbox-assistant-agent.ts b/apps/desktop/electron/services/inbox-assistant-agent.ts index 90efebb8..90a83a1d 100644 --- a/apps/desktop/electron/services/inbox-assistant-agent.ts +++ b/apps/desktop/electron/services/inbox-assistant-agent.ts @@ -15,6 +15,7 @@ import { inboxAssistantCoverageWarnings, jsonObject, MAX_FACT_QUOTES, MAX_FACT_SOURCES, verifyInboxAssistantFacts, } from './inbox-assistant-answer'; import { INBOX_AGENT_CHANGE_LIMITS } from './inbox-assistant-change-sets'; +import { INBOX_AGENT_HISTORY_MAX_CHARS } from './inbox-assistant-context'; import type { AssistantResearchDeps, InboxAssistantResearch } from './inbox-assistant-retrieval'; /** @@ -150,7 +151,7 @@ function earlierChanges(changes: InboxAgentChangeContext): string[] { function userPrompt(input: InboxAgentInput): string { return [ - input.historyContext ? `Earlier in this chat (context only, not evidence): ${JSON.stringify(input.historyContext.slice(0, 6_000))}` : '', + input.historyContext ? `Earlier in this chat (context only, not evidence): ${JSON.stringify(input.historyContext.slice(0, INBOX_AGENT_HISTORY_MAX_CHARS))}` : '', `User request: ${input.question.trim().slice(0, 4_000)}`, ].filter(Boolean).join('\n\n'); } diff --git a/apps/desktop/electron/services/inbox-assistant-context.ts b/apps/desktop/electron/services/inbox-assistant-context.ts index 21120f6e..3dea5728 100644 --- a/apps/desktop/electron/services/inbox-assistant-context.ts +++ b/apps/desktop/electron/services/inbox-assistant-context.ts @@ -116,6 +116,61 @@ function changesContentSubject(question: string, prior: string): boolean { } /** Rebuild context from persisted turns; prior answers are never treated as fresh mail evidence. */ +/** Longest the agent's chat history may be, as the JSON it is given. */ +export const INBOX_AGENT_HISTORY_MAX_CHARS = 12_000; +/** Most turns the agent is told about; older ones are counted, not shown. */ +const AGENT_HISTORY_TURNS = 12; +/** How much of an answer the agent sees: the newest ones in full, older ones in brief. */ +const RECENT_ANSWER_CHARS = 1_500; +const OLDER_ANSWER_CHARS = 400; +const RECENT_ANSWERS = 4; + +/** + * Everything earlier in THIS chat, for the agent: every question it was asked + * and what it answered, newest last. Sent with every question in the chat, so + * "find it from his signature", "yes" or "the second one" mean what the user + * meant. No guessing whether a question is a follow-up: the agent judges what + * is relevant, and the latest question always wins. + * + * Context only, never evidence: the agent is told to read the mail again + * before stating a fact. Bounded: the newest turns in full, older answers + * shortened, the oldest turns dropped (and counted) past + * {@link INBOX_AGENT_HISTORY_MAX_CHARS}. Undefined when nothing came before. + */ +export function buildInboxAgentChatHistory(history: InboxAssistantExchange[], request: InboxAssistantRequest): string | undefined { + const chat = history.filter(exchange => !exchange.chatId || exchange.chatId === request.chatId); + // Up to the exchange the question follows, when it names one (the rest + // came after it in a rewound chat). + const cut = request.previousExchangeId ? chat.findIndex(exchange => exchange.id === request.previousExchangeId) : chat.length - 1; + const earlier = chat.slice(0, cut + 1).filter(exchange => exchange.question.trim()); + if (!earlier.length) return undefined; + const shown = earlier.slice(-AGENT_HISTORY_TURNS); + const turns = shown.map((exchange, index) => { + // An answer from a different account selection may rest on an account + // the user has since deselected: its question is context, its answer is not sent. + if (!sameScope(exchange.accountIds, request.accountIds)) return { question: bounded(exchange.question, 600), otherAccounts: true as const }; + const answer = bounded(exchange.answer.text, index >= shown.length - RECENT_ANSWERS ? RECENT_ANSWER_CHARS : OLDER_ANSWER_CHARS); + return { question: bounded(exchange.question, 600), ...(answer ? { answer } : {}) }; + }); + const context = { + note: 'The earlier conversation in this chat, oldest first. Use it to understand what the latest request refers to (a person, an email, an offer you made). It is context only, not evidence: read the mail again before stating a fact. The latest request overrides earlier ones. otherAccounts: that turn used a different account selection, so its answer is left out.', + turns, + omittedEarlierTurns: earlier.length - shown.length, + }; + const size = () => JSON.stringify(context).length; + // Over the limit: shorten older answers first (never the newest one), then + // drop the oldest turns. + for (const turn of context.turns.slice(0, -1)) { + if (size() <= INBOX_AGENT_HISTORY_MAX_CHARS) break; + if ('answer' in turn && turn.answer && turn.answer.length > OLDER_ANSWER_CHARS) turn.answer = turn.answer.slice(0, OLDER_ANSWER_CHARS); + } + while (size() > INBOX_AGENT_HISTORY_MAX_CHARS && context.turns.length > 1) { + context.turns.shift(); + context.omittedEarlierTurns += 1; + } + return JSON.stringify(context); +} + export function buildInboxAssistantContext( history: InboxAssistantExchange[], request: InboxAssistantRequest, ): InboxAssistantConversationContext { diff --git a/apps/desktop/electron/services/inbox-assistant-service.ts b/apps/desktop/electron/services/inbox-assistant-service.ts index 8675a569..815e6eda 100644 --- a/apps/desktop/electron/services/inbox-assistant-service.ts +++ b/apps/desktop/electron/services/inbox-assistant-service.ts @@ -13,7 +13,7 @@ import type { InboxAgentChangeContext } from './inbox-assistant-agent-tools'; import { INBOX_ASSISTANT_OUTPUT_TOKENS, planInboxAssistantSearch } from './inbox-assistant-answer'; import type { InboxAgentChangeJournal } from './inbox-assistant-change-journal'; import { applyChangeSet, cancelChangeSet, changeCounts, INBOX_AGENT_CHANGE_LIMITS, openApprovalWindow, undoChangeSet, type HeldChangeSet, type InboxAgentEmailReader, type InboxAgentMailActions } from './inbox-assistant-change-sets'; -import { buildInboxAssistantContext } from './inbox-assistant-context'; +import { buildInboxAgentChatHistory, buildInboxAssistantContext } from './inbox-assistant-context'; import { inboxAssistantDegradedStages, inboxAssistantRunSummary } from './inbox-assistant-diagnostics'; import { generateInboxAssistantDraft } from './inbox-assistant-draft'; import type { InboxAssistantHistoryStore } from './inbox-assistant-history'; @@ -787,8 +787,12 @@ export class InboxAssistantService { if (request.previousExchangeId && !history.some(exchange => exchange.id === request.previousExchangeId)) { throw new Error('The previous message does not belong to this chat or is no longer available.'); } + // Search pinning (the planner keeps an earlier topic, people and sources) + // only for what reads as a follow-up; the conversation itself goes to the + // agent with every question in the chat. const context = buildInboxAssistantContext(history, request); const { historyContext } = context; + const chatHistory = buildInboxAgentChatHistory(history, request); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(Object.assign(new Error('Search took too long. Narrow the question or date range and try again.'), { code: 'ASSISTANT_TIMEOUT' })), 300_000); timeout.unref?.(); @@ -821,7 +825,7 @@ export class InboxAssistantService { const timeZone = researchTimeZone(this.deps); const nowMs = this.deps.now?.() ?? Date.now(); const identity = this.deps.providerIdentity?.() ?? 'default'; - if (historyContext) report({ stage: 'context', status: 'done', message: 'Loaded conversation context', detail: 'Earlier questions supply context; original emails and attachments are checked again for facts.' }); + if (chatHistory) report({ stage: 'context', status: 'done', message: 'Loaded conversation context', detail: 'Earlier questions and answers in this chat supply context; original emails and attachments are checked again for facts.' }); report({ stage: 'search', status: 'running', message: 'Working on your request', detail: `Using ${selected.length} selected ${selected.length === 1 ? 'account' : 'accounts'}.` }); const now = () => this.deps.now?.() ?? Date.now(); knownCards = this.cardExchanges(request.chatId); @@ -842,7 +846,7 @@ export class InboxAssistantService { } : undefined; if (changes) run.changes = changes; const result = await runInboxAgent({ - question: request.question, ...(historyContext ? { historyContext } : {}), accounts: selected, timeZone, nowMs, + question: request.question, ...(chatHistory ? { historyContext: chatHistory } : {}), accounts: selected, timeZone, nowMs, signal: controller.signal, protocol: this.agentProtocols.get(identity), diagnostics, ...(changes ? { changes } : {}), deps: { research: this.deps, diff --git a/apps/desktop/electron/services/inbox-assistant-setting-changes.ts b/apps/desktop/electron/services/inbox-assistant-setting-changes.ts index 018c5c48..b092e513 100644 --- a/apps/desktop/electron/services/inbox-assistant-setting-changes.ts +++ b/apps/desktop/electron/services/inbox-assistant-setting-changes.ts @@ -107,6 +107,7 @@ export function describeAction(action: FilterAction): string { case 'moveToSpam': return 'Move to Spam'; case 'moveToFolder': return `Move to ${action.value}`; case 'applyLabel': return `Label "${action.value}"`; + case 'skipAI': return 'Skip AI checks'; } } diff --git a/apps/desktop/electron/services/pgp-failure.ts b/apps/desktop/electron/services/pgp-failure.ts index 18062a36..310b272a 100644 --- a/apps/desktop/electron/services/pgp-failure.ts +++ b/apps/desktop/electron/services/pgp-failure.ts @@ -1,44 +1,67 @@ /** - * What a user may read about an OpenPGP failure, and what only the log may. + * How the main process handles an OpenPGP failure: what the log may say, and + * which causes the renderer may act on. * - * CASA 4.1.4: the user-facing message of a cryptographic failure is vague and - * the same whatever went wrong, so whoever crafted a ciphertext or a key - * learns nothing from the reply about how far the operation got. + * CASA 4.1.4: every OpenPGP failure the user can see reads exactly + * PGP_FAILURE_MESSAGE (`@sarvinbox/core/pgp`), whatever the cause, so whoever + * crafted a ciphertext or a key learns nothing from the reply about how far + * the operation got. Callers answer with that constant directly — never with + * a caught error's message, which for the library's (or the platform's) + * errors describes internal state. * - * Our own typed errors are fixed sentences — "no key", "locked", "the keychain - * is not available", PGP_DECRYPT_FAILED_MESSAGE — and keep their wording; the - * library reason some of them carry (`detail`) is logged here, locally. Any - * other error is the library's (or the platform's) own account of the failure: - * it is logged, and the user reads `fallback` instead. - * - * Never pass an error whose text could hold plaintext or key material: what - * is logged is the error's message as the library wrote it. + * The log keeps the cause as the error's class and code and nothing else: no + * library reason, no sentence of ours (one used to name the locked key's + * address), no stack. */ -import type { Logger } from '@sarvinbox/core'; -import { PgpKeyError, PgpOpenError, pgpFailureDetail } from '@sarvinbox/core/pgp'; +import { errorDiagnostic, parseAddresses, type Logger, type SendPgpRequest } from '@sarvinbox/core'; +import { PgpOpenError, type PgpFlowCode } from '@sarvinbox/core/pgp'; -import { PgpKeyringError } from './pgp-keyring'; -import { SealError } from './pgp-secret-seal'; +import { PgpKeyringError, type PgpKeyring } from './pgp-keyring'; -type OwnPgpError = PgpOpenError | PgpKeyError | PgpKeyringError | SealError; +/** + * Write one OpenPGP failure to the log: `context` (what was being done, with + * ids at most), then the error's class and code — `{ name: 'PgpOpenError', + * code: 'bad-data' }` — and never its message. + */ +export function logPgpFailure(log: Pick, context: string, error: unknown): void { + log.warn(context, errorDiagnostic(error)); +} -/** One of our own OpenPGP errors, whose message is ours and safe to show. */ -export const isOwnPgpError = (error: unknown): error is OwnPgpError => - error instanceof PgpOpenError || - error instanceof PgpKeyError || - error instanceof PgpKeyringError || - error instanceof SealError; +/** + * The prompt a failure calls for, when it is one: `locked` (unlock the key) + * or `passphrase-required` (ask for a passphrase). Undefined for every other + * cause, which the renderer must not tell apart. + */ +export function pgpFlowCode(error: unknown): PgpFlowCode | undefined { + if (error instanceof PgpOpenError && error.code === 'locked') return 'locked'; + if (error instanceof PgpKeyringError && (error.code === 'locked' || error.code === 'passphrase-required')) return error.code; + return undefined; +} /** - * The text a user may read for `error`. Logs the library's reason under - * `context` (one warn line, nothing when an own error carries no detail). + * Whether a send that asks to be signed must first unlock the sender's key: + * `locked`, or null. Asked when the composer hands a send over — before it is + * queued, because the send itself runs after the undo window, when the + * composer is gone — and again by the composer's unlock prompt, to tell + * whether the key it needs is open now (not merely whether some key opened). + * + * `locked` is the only answer (CASA 4.1.4: a prompt, decided from the + * keyring's state, not a failure of the cipher). Any other problem — no key + * for the address, a keyring or keychain that cannot be read — answers null + * and is left to the send, which fails with PGP_FAILURE_MESSAGE. */ -export function pgpUserMessage(error: unknown, fallback: string, log: Pick, context: string): string { - if (isOwnPgpError(error)) { - const detail = error instanceof PgpOpenError || error instanceof PgpKeyError ? error.detail : undefined; - if (detail) log.warn(`${context}: ${detail}`); - return error.message; +export async function lockedSigningKeyFor( + request: SendPgpRequest | undefined, + fromHeader: string, + keyringFor: () => Pick, +): Promise<'locked' | null> { + if (!request?.sign) return null; + const from = parseAddresses(fromHeader)[0]; + if (!from) return null; + try { + await keyringFor().signingKeyFor(from); + return null; + } catch (error) { + return pgpFlowCode(error) === 'locked' ? 'locked' : null; } - log.warn(`${context}: ${pgpFailureDetail(error)}`); - return fallback; } diff --git a/apps/desktop/electron/services/pgp-keyring.ts b/apps/desktop/electron/services/pgp-keyring.ts index 29558f16..039ba3de 100644 --- a/apps/desktop/electron/services/pgp-keyring.ts +++ b/apps/desktop/electron/services/pgp-keyring.ts @@ -25,6 +25,7 @@ import { generateKeyPair, inspectKey, parseAutocryptHeader, + PGP_FAILURE_MESSAGE, PgpKeyError, pickEncryptionKey, protectPrivateKey, @@ -59,14 +60,21 @@ export const FAILED_LOOKUP_TTL_MS = 5 * 60 * 1000; /** Source tiers, most trusted first. */ const SOURCE_ORDER: readonly PgpKeySource[] = ['manual', 'wkd', 'keyserver', 'autocrypt']; -export type PgpKeyringErrorCode = 'passphrase-required' | 'not-found' | 'locked' | 'address-mismatch'; +/** + * Why the keyring refused — for the caller's branch and the local log only: + * - `passphrase-required`: a passphrase is needed and none was given. + * - `not-found`: no such own key, or none for the address. + * - `locked`: the key needed is passphrase-protected and not unlocked this session. + */ +export type PgpKeyringErrorCode = 'passphrase-required' | 'not-found' | 'locked'; +/** + * A keyring refusal. Its message is always PGP_FAILURE_MESSAGE, whatever the + * cause (CASA 4.1.4) — it names no key and no address; the cause is the code. + */ export class PgpKeyringError extends Error { - constructor( - message: string, - public readonly code: PgpKeyringErrorCode, - ) { - super(message); + constructor(public readonly code: PgpKeyringErrorCode) { + super(PGP_FAILURE_MESSAGE); this.name = 'PgpKeyringError'; } } @@ -157,7 +165,7 @@ export class PgpKeyring { async generateOwnKey(input: { name: string; email: string; passphrase?: string }): Promise { const useKeychain = this.keychainAvailable(); if (!useKeychain && !input.passphrase) { - throw new PgpKeyringError('A passphrase is needed: this system has no keychain to protect the key', 'passphrase-required'); + throw new PgpKeyringError('passphrase-required'); } const generated = await generateKeyPair({ name: input.name, @@ -178,7 +186,7 @@ export class PgpKeyring { async importOwnKey(armored: string, passphrase?: string): Promise { const keys = (await readAllKeys(armored)).filter((key) => key.isPrivate()); if (keys.length === 0) { - throw new PgpKeyError('This is a public key; importing your own key needs the private key', 'not-private'); + throw new PgpKeyError('not-private'); } const useKeychain = this.keychainAvailable(); const imported: OwnKeySummary[] = []; @@ -186,16 +194,14 @@ export class PgpKeyring { const original = key.armor(); const protectedOnDisk = (await inspectKey(original)).isPassphraseProtected; if (protectedOnDisk && !passphrase) { - throw new PgpKeyringError('This key is protected by a passphrase', 'passphrase-required'); + throw new PgpKeyringError('passphrase-required'); } const unlocked = protectedOnDisk ? await unlockPrivateKey(original, passphrase as string) : original; if (useKeychain) { imported.push(await this.storeOwn(unlocked, null)); continue; } - if (!passphrase) { - throw new PgpKeyringError('A passphrase is needed: this system has no keychain to protect the key', 'passphrase-required'); - } + if (!passphrase) throw new PgpKeyringError('passphrase-required'); const lockedCopy = protectedOnDisk ? original : await protectPrivateKey(unlocked, passphrase); imported.push(await this.storeOwn(unlocked, lockedCopy)); } @@ -229,7 +235,7 @@ export class PgpKeyring { private requireOwn(fingerprint: string): OwnKeyRow { const row = this.deps.store.getOwnKey(fingerprint); - if (!row) throw new PgpKeyringError('No such key', 'not-found'); + if (!row) throw new PgpKeyringError('not-found'); return row; } @@ -255,10 +261,10 @@ export class PgpKeyring { /** A backup of an own key, protected with `passphrase` whatever it is protected with here. */ async exportOwnKey(fingerprint: string, passphrase: string): Promise { - if (!passphrase) throw new PgpKeyringError('A backup needs a passphrase', 'passphrase-required'); + if (!passphrase) throw new PgpKeyringError('passphrase-required'); const row = this.requireOwn(fingerprint); const privateKey = await this.openOwn(row); - if (!privateKey) throw new PgpKeyringError('Unlock this key before backing it up', 'locked'); + if (!privateKey) throw new PgpKeyringError('locked'); return protectPrivateKey(privateKey.armor(), passphrase); } @@ -301,7 +307,7 @@ export class PgpKeyring { /** * The key to sign mail from `email` with. Null when the user has no key for * that address; THROWS `locked` when the only one is locked, so the send - * fails with "unlock your key" rather than going out unsigned. + * fails rather than going out unsigned. */ async signingKeyFor(email: string): Promise { const rows = await this.ownRowsFor(email); @@ -310,7 +316,7 @@ export class PgpKeyring { const key = await this.openOwn(row); if (key) return key; } - throw new PgpKeyringError(`The key for ${normalizeEmail(email)} is locked`, 'locked'); + throw new PgpKeyringError('locked'); } /** diff --git a/apps/desktop/electron/services/pgp-outgoing.ts b/apps/desktop/electron/services/pgp-outgoing.ts index 61b3abd2..e68f0768 100644 --- a/apps/desktop/electron/services/pgp-outgoing.ts +++ b/apps/desktop/electron/services/pgp-outgoing.ts @@ -12,9 +12,13 @@ * - When it asks for a signature, the key for the From address signs; a * missing or locked key refuses the send rather than sending it unsigned. * - * Refusals are `OutgoingMimeError(…, false)`: permanent for the outbox, which - * then surfaces the message instead of retrying something that cannot work - * until the user acts. + * Refusals are `OutgoingMimeError(PGP_FAILURE_MESSAGE, false)`: permanent for + * the outbox, which then surfaces the message instead of retrying something + * that cannot work until the user acts. Every refusal reads the same (CASA + * 4.1.4) — a recipient without a key, an openpgp.js error; the composer + * already names recipients without a key before the send, and the log keeps + * the cause as the error's class and code. The one exception is a key locked + * this session, a prompt: PGP_UNLOCK_THEN_RETRY_MESSAGE with code `locked`. */ import { OutgoingMimeError, @@ -23,19 +27,27 @@ import { type OutgoingMimeTransform, type SendPgpRequest, } from '@sarvinbox/core'; -import { buildAutocryptHeader, encryptOutgoingMime, pgpFailureDetail, signOutgoingMime, withHeader } from '@sarvinbox/core/pgp'; +import { + PGP_FAILURE_MESSAGE, + PGP_UNLOCK_THEN_RETRY_MESSAGE, + buildAutocryptHeader, + encryptOutgoingMime, + signOutgoingMime, + withHeader, +} from '@sarvinbox/core/pgp'; -import { pgpUserMessage } from './pgp-failure'; -import type { PgpKeyring } from './pgp-keyring'; +import { logPgpFailure, pgpFlowCode } from './pgp-failure'; +import { PgpKeyringError, type PgpKeyring } from './pgp-keyring'; const logger = createLogger('pgp-outgoing'); -/** - * The reason a send or a draft shows when OpenPGP itself failed (not one of our - * own refusals, which say what they mean). The library's reason is logged - * (CASA 4.1.4). - */ -export const PGP_OPERATION_FAILED_REASON = 'the OpenPGP operation failed'; +/** A send refused here before any OpenPGP runs. Its code is for the log; its message the one sentence. */ +class PgpSendRefusal extends Error { + constructor(readonly code: 'no-signing-key' | 'no-recipient-key') { + super(PGP_FAILURE_MESSAGE); + this.name = 'PgpSendRefusal'; + } +} export type OutgoingKeyring = Pick; @@ -57,7 +69,7 @@ async function withAutocrypt(keyring: OutgoingKeyring, raw: Buffer, from: string }); return withHeader(raw, 'Autocrypt', header); } catch (error) { - logger.warn(`Autocrypt header skipped: ${pgpFailureDetail(error)}`); + logPgpFailure(logger, 'Autocrypt header skipped', error); return raw; } } @@ -71,25 +83,26 @@ export function pgpOutgoingTransform(keyring: OutgoingKeyring, options: Outgoing try { const signingKey = sign ? await keyring.signingKeyFor(from) : null; - if (sign && !signingKey) { - throw new OutgoingMimeError(`No OpenPGP key for ${from || 'this sender'} to sign with`, false); - } + if (sign && !signingKey) throw new PgpSendRefusal('no-signing-key'); const signingKeys = signingKey ? [signingKey] : []; if (!encrypt) return await signOutgoingMime(withHeaderRaw, signingKeys); const recipients = parseAddresses(context.recipients.join(', ')); const { keys, missing } = await keyring.encryptionKeysFor(from, recipients); - if (missing.length > 0) { - throw new OutgoingMimeError(`No encryption key for ${missing.join(', ')} — import their key or send unencrypted`, false); - } + if (missing.length > 0) throw new PgpSendRefusal('no-recipient-key'); return await encryptOutgoingMime(withHeaderRaw, { encryptionKeys: keys, signingKeys }); } catch (error) { - if (error instanceof OutgoingMimeError) throw error; - // A locked key, an unreadable keyring, an openpgp failure: none of them - // clears up by retrying, so none of them may be retried into plaintext. - const verb = encrypt ? 'encrypt' : 'sign'; - const reason = pgpUserMessage(error, PGP_OPERATION_FAILED_REASON, logger, `Could not ${verb} an outgoing message`); - throw new OutgoingMimeError(`Could not ${verb} the message: ${reason}`, false); + // A recipient or sender without a key, an unreadable keyring, an + // openpgp failure: one sentence for all of them. None clears up by + // retrying, so none may be retried into plaintext. A key locked this + // session is the one cause the user can act on (a prompt, not a failure + // of the cipher): it says so, as the `locked` code, so the Outbox row + // tells them to unlock and retry. The composer refuses such a send before + // it is queued; this catches the ones already queued (a scheduled send + // after a restart, a retry). + logPgpFailure(logger, `Could not ${encrypt ? 'encrypt' : 'sign'} an outgoing message`, error); + if (pgpFlowCode(error) === 'locked') throw new OutgoingMimeError(PGP_UNLOCK_THEN_RETRY_MESSAGE, false, 'locked'); + throw new OutgoingMimeError(PGP_FAILURE_MESSAGE, false); } }; } @@ -98,15 +111,14 @@ export function pgpOutgoingTransform(keyring: OutgoingKeyring, options: Outgoing * A draft of an encrypted message, encrypted to the sender's own key alone — * a draft has one reader. Unsigned, so saving never needs a locked key. * - * Throws when there is no key for the address: the caller must then save - * nothing, because the only other thing it could save is the plaintext. + * Throws when there is no key for the address (`PgpKeyringError('not-found')`) + * or the keyring or openpgp.js fails: the caller must then save nothing, + * because the only other thing it could save is the plaintext. The caller + * answers PGP_FAILURE_MESSAGE and logs with `logPgpFailure` — never the + * thrown error's text, which for a library error is the library's. */ export async function encryptDraftMime(raw: Buffer, from: string, keyring: Pick): Promise { const own = from ? await keyring.ownPublicKeyFor(from) : null; - if (!own) throw new Error(`No OpenPGP key for ${from || 'this account'} to encrypt the draft with`); - try { - return await encryptOutgoingMime(raw, { encryptionKeys: [own] }); - } catch (error) { - throw new Error(pgpUserMessage(error, PGP_OPERATION_FAILED_REASON, logger, 'Could not encrypt a draft')); - } + if (!own) throw new PgpKeyringError('not-found'); + return encryptOutgoingMime(raw, { encryptionKeys: [own] }); } diff --git a/apps/desktop/electron/services/pgp-reader.ts b/apps/desktop/electron/services/pgp-reader.ts index 0b829ab1..6eb9c256 100644 --- a/apps/desktop/electron/services/pgp-reader.ts +++ b/apps/desktop/electron/services/pgp-reader.ts @@ -13,16 +13,15 @@ */ import { createLogger } from '@sarvinbox/core'; import { - PgpOpenError, + PGP_FAILURE_MESSAGE, openStoredPgp, readOpenedContent, type OpenedAttachment, type OpenedMessage, - type PgpOpenErrorCode, type PgpSignatureStatus, } from '@sarvinbox/core/pgp'; -import { pgpUserMessage } from './pgp-failure'; +import { logPgpFailure, pgpFlowCode } from './pgp-failure'; import { normalizeEmail } from './pgp-key-store'; import type { PgpKeyring } from './pgp-keyring'; @@ -31,13 +30,6 @@ const logger = createLogger('pgp-reader'); /** How many opened messages stay in memory. Small: plaintext is kept only for the one being read. */ export const OPENED_CACHE_SIZE = 8; -/** - * What the reader says when opening fails for a reason that is not one of our - * own (the keychain's or the library's error). The reason is logged; the user - * reads this, whatever it was (CASA 4.1.4). - */ -export const PGP_OPEN_FAILED_MESSAGE = 'The message could not be opened. Try again.'; - export interface PgpSignatureView { status: PgpSignatureStatus; signerFingerprint?: string; @@ -58,6 +50,27 @@ export interface PgpViewAttachment { size: number; } +/** + * Why a message did not open, as the renderer may know it: `locked` asks for + * the key's passphrase; every other cause — no key, a damaged or tampered + * ciphertext, a keychain that will not open, a source that cannot be fetched — + * is `failed`, and they cannot be told apart (CASA 4.1.4). + */ +export type PgpOpenFailureCode = 'locked' | 'failed'; + +/** A message that did not open. `error` is always PGP_FAILURE_MESSAGE. */ +export interface PgpOpenFailure { + ok: false; + code: PgpOpenFailureCode; + error: typeof PGP_FAILURE_MESSAGE; +} + +export const pgpOpenFailure = (code: PgpOpenFailureCode = 'failed'): PgpOpenFailure => ({ + ok: false, + code, + error: PGP_FAILURE_MESSAGE, +}); + export type PgpViewResult = | { ok: true; @@ -67,7 +80,7 @@ export type PgpViewResult = body: string; attachments: PgpViewAttachment[]; } - | { ok: false; code: PgpOpenErrorCode | 'unavailable'; error: string }; + | PgpOpenFailure; /** * An encrypted draft, opened back into the composer. Unlike a view, its @@ -85,7 +98,7 @@ export interface PgpDraftAttachment { export type PgpDraftResult = | { ok: true; contentType: 'html' | 'text'; body: string; attachments: PgpDraftAttachment[] } - | Extract; + | PgpOpenFailure; /** The stored message a view is opened from. */ export interface StoredSource { @@ -111,14 +124,19 @@ export class PgpReader { try { source = await this.deps.source(emailId, accountId); } catch (error) { - return { ok: false, code: 'unavailable', error: `Could not load the message: ${(error as Error).message}` }; + // The fetch's own text can quote a server's reply; the user reads the one sentence. + logPgpFailure(logger, `Could not load the source of OpenPGP message ${emailId}`, error); + return pgpOpenFailure(); + } + if (!source) { + logger.warn(`OpenPGP message ${emailId} has no source to open`); + return pgpOpenFailure(); } - if (!source) return { ok: false, code: 'unavailable', error: 'The message source is not available' }; try { const keys = await this.deps.keyring().openingKeys(source.fromAddress); const result = await openStoredPgp(Buffer.from(source.raw, 'latin1'), keys); - // The verdict is all the renderer gets; why it failed stays in the local log. - if (result.signature.detail) logger.warn(`OpenPGP signature on ${emailId} did not verify: ${result.signature.detail}`); + // The verdict is all the renderer gets, and all the log gets: the library's reason is not kept. + if (result.signature.status === 'invalid') logger.warn(`OpenPGP signature on ${emailId} did not verify`); const content = await readOpenedContent(result.content); this.remember(cacheKey(emailId, accountId), content); const from = source.fromAddress ? normalizeEmail(source.fromAddress) : null; @@ -137,8 +155,9 @@ export class PgpReader { attachments: content.attachments.map(({ name, contentType, size }, index) => ({ index, name, contentType, size })), }; } catch (error) { - const message = pgpUserMessage(error, PGP_OPEN_FAILED_MESSAGE, logger, `Could not open OpenPGP message ${emailId}`); - return { ok: false, code: error instanceof PgpOpenError ? error.code : 'unavailable', error: message }; + // One answer for every cause; which one it was is the logged class and code. + logPgpFailure(logger, `Could not open OpenPGP message ${emailId}`, error); + return pgpOpenFailure(pgpFlowCode(error) === 'locked' ? 'locked' : 'failed'); } } diff --git a/apps/desktop/electron/services/pgp-secret-seal.ts b/apps/desktop/electron/services/pgp-secret-seal.ts index 98c51403..72937be0 100644 --- a/apps/desktop/electron/services/pgp-secret-seal.ts +++ b/apps/desktop/electron/services/pgp-secret-seal.ts @@ -14,6 +14,7 @@ * because whoever copies the profile directory would then read the user's mail. */ import { createLogger, errorClassName } from '@sarvinbox/core'; +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp'; import { safeStorage } from 'electron'; import { isOsBackedEncryption } from './os-encryption'; @@ -25,15 +26,6 @@ const logger = createLogger('pgp-secret-seal'); const MAGIC_KEYCHAIN = 'ENC1:'; const MAGIC_PASSPHRASE = 'LOCK1:'; -/** - * What opening a keychain-sealed key says when the keychain is there but will - * not decrypt it: macOS Keychain access denied, a locked or re-created Linux - * keyring, a profile copied from another machine or user. The user can act on - * this; the platform's own error text is neither actionable nor theirs to read. - */ -export const KEYCHAIN_REFUSED_MESSAGE = - 'This key is sealed by the OS keychain, which would not open it. Unlock the keychain or allow Sarv Inbox to use it, then try again.'; - /** The keychain operations sealing needs — injectable so tests run without Electron. */ export interface Keychain { /** A real OS key store protects what we seal now (never Linux `basic_text`). */ @@ -62,19 +54,22 @@ export type SealedSecret = | { protection: 'keychain'; armoredPrivateKey: string } | { protection: 'passphrase'; armoredProtectedKey: string }; +/** + * A private key that cannot be sealed or opened. Its message is always + * PGP_FAILURE_MESSAGE, like every other key failure (CASA 4.1.4); the cause is + * the code: `keychain-unavailable` (no keychain, or one that refused to open + * this key), `unknown-format` (not one of our envelopes). + */ export class SealError extends Error { - constructor( - message: string, - public readonly code: 'keychain-unavailable' | 'unknown-format', - ) { - super(message); + constructor(public readonly code: 'keychain-unavailable' | 'unknown-format') { + super(PGP_FAILURE_MESSAGE); this.name = 'SealError'; } } /** Keychain-seal an UNPROTECTED armored key. Throws when there is no keychain. */ export function sealWithKeychain(keychain: Keychain, armoredPrivateKey: string): Buffer { - if (!keychain.isAvailable()) throw new SealError('The OS keychain is not available', 'keychain-unavailable'); + if (!keychain.isAvailable()) throw new SealError('keychain-unavailable'); return Buffer.concat([Buffer.from(MAGIC_KEYCHAIN, 'utf8'), keychain.encrypt(armoredPrivateKey)]); } @@ -90,7 +85,7 @@ const hasMagic = (sealed: Buffer, magic: string): boolean => export function protectionOf(sealed: Buffer): OwnKeyProtection { if (hasMagic(sealed, MAGIC_KEYCHAIN)) return 'keychain'; if (hasMagic(sealed, MAGIC_PASSPHRASE)) return 'passphrase'; - throw new SealError('Unknown private-key envelope', 'unknown-format'); + throw new SealError('unknown-format'); } /** @@ -104,19 +99,18 @@ export function unseal(keychain: Keychain, sealed: Buffer): SealedSecret { return { protection: 'passphrase', armoredProtectedKey: sealed.subarray(MAGIC_PASSPHRASE.length).toString('utf8') }; } if (!(keychain.canOpen ? keychain.canOpen() : keychain.isAvailable())) { - throw new SealError('This key is sealed by the OS keychain, which is not available', 'keychain-unavailable'); + throw new SealError('keychain-unavailable'); } // `canOpen` only says a keychain exists; whether it will decrypt THIS key is // known only by asking. A refusal is the same fact as a missing keychain — - // the key is there and cannot be read — so it throws the same typed error, - // whose sentence reaches the user (pgpUserMessage keeps our own wording). + // the key is there and cannot be read — so it throws the same typed error. let armoredPrivateKey: string; try { armoredPrivateKey = keychain.decrypt(sealed.subarray(MAGIC_KEYCHAIN.length)); } catch (error) { // The class only: safeStorage's message is the platform's, and nothing of a key is ever logged. logger.warn(`The OS keychain would not open an OpenPGP private key (${errorClassName(error)})`); - throw new SealError(KEYCHAIN_REFUSED_MESSAGE, 'keychain-unavailable'); + throw new SealError('keychain-unavailable'); } return { protection: 'keychain', armoredPrivateKey }; } diff --git a/apps/desktop/electron/services/pgp-service.ts b/apps/desktop/electron/services/pgp-service.ts index 3473a677..955ef764 100644 --- a/apps/desktop/electron/services/pgp-service.ts +++ b/apps/desktop/electron/services/pgp-service.ts @@ -12,9 +12,10 @@ import { type OutgoingMimeTransform, type SendPgpRequest, } from '@sarvinbox/core'; -import { readPgpPrefs, type PgpPrefs } from '@sarvinbox/core/pgp'; +import { PGP_FAILURE_MESSAGE, readPgpPrefs, type PgpPrefs } from '@sarvinbox/core/pgp'; import { readAppSetting } from './core-db'; +import { logPgpFailure } from './pgp-failure'; import { lookupPublicKey } from './pgp-key-lookup'; import { getPgpKeyStore } from './pgp-key-store'; import { PgpKeyring } from './pgp-keyring'; @@ -62,10 +63,10 @@ export function sendTransformFor( try { ring = (deps.keyring ?? getPgpKeyring)(); } catch (error) { - logger.warn(`OpenPGP keyring unavailable for this send: ${(error as Error).message}`); + logPgpFailure(logger, 'OpenPGP keyring unavailable for this send', error); if (!wantsPgp) return undefined; return async () => { - throw new OutgoingMimeError('The OpenPGP keyring could not be opened, so the message was not sent', false); + throw new OutgoingMimeError(PGP_FAILURE_MESSAGE, false); }; } let preferEncrypt = false; diff --git a/apps/desktop/electron/services/secure-credential-store.ts b/apps/desktop/electron/services/secure-credential-store.ts index f1117a7a..4b9d5d41 100644 --- a/apps/desktop/electron/services/secure-credential-store.ts +++ b/apps/desktop/electron/services/secure-credential-store.ts @@ -21,7 +21,7 @@ import { join } from 'path'; import { createLogger } from '@sarvinbox/core'; import { app } from 'electron'; -import { getBlob, setBlob } from './core-db'; +import { readBlob, setBlob, writeBlob } from './core-db'; import { isOsBackedEncryption } from './os-encryption'; import { sealJson, openJson, type EnvelopeErrors } from './safe-storage-envelope'; import { createWriteQueue } from './write-queue'; @@ -32,29 +32,60 @@ const BLOB_KEY = 'secure-credentials'; /** * One credential kind. `host` is the server the secret was saved FOR: main only - * ever sends the secret to that host (see vault-credentials.ts). The two - * transport relaxations are the ones the user chose WITH the secret: main only - * sends it over a connection that is at least that strict. Entries written - * before either binding lack those fields and are bound on first use. + * ever sends the secret to that host (see vault-credentials.ts). The transport + * relaxation is the one the user chose WITH the secret: main only sends it over + * a connection that is at least that strict. Entries written before either + * binding lack those fields and are bound on first use. */ export interface VaultCredential { password?: string; accessToken?: string; refreshToken?: string; host?: string; - /** Accept a certificate nobody vouches for (a self-signed server). */ + /** + * RETIRED "accept any certificate" switch, still present on entries saved + * before certificate pinning (CASA 4.1.2). Never written, never obeyed: read + * only so the approval dialog can tell the user why it is asking once. + */ allowInsecureTLS?: boolean; /** Connect without requiring encryption (security 'none'). */ allowPlaintext?: boolean; } /** The relaxations a vault entry may record. */ -export type VaultTransportField = 'allowInsecureTLS' | 'allowPlaintext'; -const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowInsecureTLS', 'allowPlaintext']; +export type VaultTransportField = 'allowPlaintext'; +const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowPlaintext']; + +/** + * A certificate the user approved, in main's own dialog, for one server of this + * account (CASA 4.1.2). Bound to the transport (the `certificates` key), host + * and port: it is used only for a connection to exactly that host and port, and + * then that connection accepts exactly this certificate. Written only by main's + * approval flow (certificate-trust.ts) — `setAccountSecrets`, which the window + * reaches, never copies it. + */ +export interface CertificatePinRecord { + host: string; + port: number; + /** SHA-256 of the leaf's DER, Node's fingerprint256 form. */ + sha256: string; + /** The approved leaf certificate, PEM. */ + pem: string; + /** When the user approved it (epoch ms). */ + approvedAt: number; + subject: string; + issuer: string; + validFrom: string; + validTo: string; +} + +export type CertificateKind = 'imap' | 'smtp'; export interface AccountSecrets { imap?: VaultCredential; smtp?: VaultCredential; + /** Approved certificates, per transport. */ + certificates?: Partial>; } type Vault = Record; @@ -100,7 +131,12 @@ async function migrateLegacyFile(): Promise { } async function readVault(): Promise { - const blob = getBlob(BLOB_KEY); + // The LOUD read (readBlob): a core DB that cannot be read throws here rather + // than reading as "no vault". Writes are read-modify-write of the whole + // vault, so an unreadable store taken for an empty one would be overwritten + // with just the new entry — every other account's password and approved + // certificate gone. Readers already treat a throw as "not readable yet". + const blob = readBlob(BLOB_KEY); if (blob) { // A present-but-undecryptable vault must NOT read as empty (that would let a // later write clobber every other account's secret) — deserialize throws. @@ -111,7 +147,7 @@ async function readVault(): Promise { // Re-check: a concurrent call may have migrated + renamed the file between our // getBlob and here — don't conclude "empty vault" (which a later write would // then persist, clobbering the real secrets). - const blob2 = getBlob(BLOB_KEY); + const blob2 = readBlob(BLOB_KEY); return blob2 ? (deserialize(blob2) || {}) : {}; } @@ -119,11 +155,16 @@ async function readVault(): Promise { // (read-modify-write on the whole vault). const writeQueue = createWriteQueue(); -async function writeVault(mutate: (vault: Vault) => void): Promise { +/** + * Read-modify-write the whole vault, serialised. `strict` writes with the + * throwing `writeBlob`, for a change the user is told was saved (an approved or + * removed certificate): `setBlob` only logs a failed write. + */ +async function writeVault(mutate: (vault: Vault) => void, { strict = false }: { strict?: boolean } = {}): Promise { return writeQueue.enqueue(async () => { const vault = await readVault(); mutate(vault); - setBlob(BLOB_KEY, serialize(vault)); + (strict ? writeBlob : setBlob)(BLOB_KEY, serialize(vault)); }); } @@ -145,9 +186,11 @@ export async function setAccountSecrets(accountId: string, secrets: AccountSecre // The host travels WITH a secret, never alone: a call carrying only a host // must not be able to re-point an existing password at another server. if (typeof o.host === 'string' && o.host.trim()) out.host = o.host.trim(); - // So do the transport relaxations, and always as booleans: a call carrying - // only "allow self-signed" must not loosen how an existing password is - // sent, and a new secret is bound to exactly what was chosen with it. + // So does the transport relaxation, and always as a boolean: a call + // carrying only "None" must not loosen how an existing password is sent, + // and a new secret is bound to exactly what was chosen with it. The retired + // "allow self-signed" switch is never copied, and neither is a certificate + // pin: only main's own approval dialog writes one (setAccountCertificatePin). for (const k of TRANSPORT_FIELDS) out[k] = o[k] === true; return out; }; @@ -156,7 +199,8 @@ export async function setAccountSecrets(accountId: string, secrets: AccountSecre if (!imap && !smtp) return; await writeVault((v) => { const existing = v[accountId] ?? {}; - // Only overwrite the kind(s) actually supplied; keep the other kind intact. + // Only overwrite the kind(s) actually supplied; keep the other kind intact, + // and the approved certificates (each is bound to its own host and port). v[accountId] = { ...existing, ...(imap ? { imap } : {}), @@ -247,9 +291,50 @@ export async function deleteAccountSecrets(accountId: string): Promise { } /** True if we have any secret on file for this account (renderer can skip a - * re-login prompt when secrets already live in the vault). */ + * re-login prompt when secrets already live in the vault). An approved + * certificate alone is not a secret to sign in with. */ export async function hasAccountSecrets(accountId: string): Promise { - return (await getAccountSecrets(accountId)) !== null; + const secrets = await getAccountSecrets(accountId); + return !!(secrets?.imap || secrets?.smtp); +} + +/** + * Store the certificate the user approved for `kind` of this account, + * replacing any earlier one for that transport. MAIN ONLY — called by the + * approval flow after the user chose "Trust this certificate" in main's own + * dialog. Throws when the vault cannot be read OR written (a strict write: + * nothing is then trusted, and the user is told it was not saved). + */ +export async function setAccountCertificatePin(accountId: string, kind: CertificateKind, pin: CertificatePinRecord): Promise { + if (!accountId) throw new Error('No account to store the approved certificate for'); + await writeVault((v) => { + const account = v[accountId] ?? {}; + account.certificates = { ...account.certificates, [kind]: { ...pin } }; + // The retired "accept any certificate" switch has done its last job (it + // worded the dialog); drop it so nothing reads it again. + if (account[kind]) delete account[kind]!.allowInsecureTLS; + v[accountId] = account; + }, { strict: true }); +} + +/** + * Forget the approved certificate for `kind` under each of `accountIds`. + * Answers whether one was removed. Throws when the vault cannot be read. + */ +export async function removeAccountCertificatePin(accountIds: readonly string[], kind: CertificateKind): Promise { + let removed = false; + await writeVault((v) => { + for (const id of accountIds) { + const certificates = v[id]?.certificates; + if (!certificates?.[kind]) continue; + delete certificates[kind]; + if (!Object.keys(certificates).length) delete v[id]!.certificates; + // An entry that held only certificates leaves no empty shell behind. + if (!Object.keys(v[id]!).length) delete v[id]; + removed = true; + } + }, { strict: true }); + return removed; } /** True if the legacy secure-credentials.json (or its rename) still exists — diff --git a/apps/desktop/electron/services/unified-pipeline-service.ts b/apps/desktop/electron/services/unified-pipeline-service.ts index dbfb0799..113a60f4 100644 --- a/apps/desktop/electron/services/unified-pipeline-service.ts +++ b/apps/desktop/electron/services/unified-pipeline-service.ts @@ -69,6 +69,7 @@ import { isAIEndpointRefusedError, prepareAIProviderConfig, reportAIConfigRefuse import { runClassificationMutation } from './classification-actions'; import { refreshContactClassifications, startContactClassificationRefresh, stopContactClassificationRefresh } from './contact-classification-service'; import { getMeta, setMeta } from './core-db'; +import { filterAiVerdict } from './filter-ai-skip'; import { ensureGmailLabelColor, renameGmailLabel, deleteGmailLabelsUnder } from './gmail-label-api'; import { chromiumFetch } from './net-fetch'; import { notifyNewMail } from './notification-service'; @@ -336,7 +337,7 @@ async function isStoredSpam(storage: any, email: any): Promise { return isSpamProtectedEmail(email, folder, await storage.getFolders?.()); } -function propagateCategoriesToLinkedAccounts(messageId: string | undefined, categories: string[], sourceStorage: any, priority?: PropagatePriority): void { +async function propagateCategoriesToLinkedAccounts(messageId: string | undefined, categories: string[], sourceStorage: any, priority?: PropagatePriority): Promise { if (!messageId || categories.length === 0) return; const now = Math.floor(Date.now() / 1000); const cats = categories.map((slug) => ({ slug, confidence: 0.9 })); @@ -357,6 +358,11 @@ function propagateCategoriesToLinkedAccounts(messageId: string | undefined, cate // let a propagation clobber categories that copy already had. const ownCategorySlugs = extractCategorySlugs(row.tags || '', getCategorySlugSet(rt.storage)); if (ownCategorySlugs.length > 0) continue; + // A filter in THIS copy's account with "Skip AI checks" keeps the AI's + // verdict off it too, even one reached in another account. Unreadable + // rules: leave the copy to its own pipeline, which asks again. + const linkedEmail = await (rt.storage as any).getEmail?.(row.id); + if (!linkedEmail || await filterAiVerdict(rt.storage as any, linkedEmail) !== 'run') continue; const oRepos = (rt.storage as any).getRepositories(); // Back-fill this copy AND mark it done — even if it's still unread + pending. // A dual-delivered message is identical content, so it must be categorized @@ -1018,6 +1024,17 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi return; } + // A filter with "Skip AI checks" keeps every AI step below away from this + // email: categorizing, priority, the AI's spam verdict, automatic actions + // and drafted replies. Marked handled so neither trigger returns to it; + // unreadable rules leave it pending for the next pass. + const filterVerdict = await filterAiVerdict(storage, email); + if (filterVerdict === 'unknown') return; + if (filterVerdict === 'skip') { + (storage as any).getRepositories()?.agent?.markAgentGaveUp?.(emailId, {}); + return; + } + // Skip emails without body — can't categorize or score content without it const hasBody = (email.cleanBody && email.cleanBody.length > 0) || (email.rawBody && email.rawBody.length > 0); if (!hasBody) { @@ -1260,7 +1277,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // Copy this categorization to the same message in other accounts, so a // dual-delivered mail shows the same badge everywhere — free. if (categories.length > 0) { - propagateCategoriesToLinkedAccounts((email as any).messageId, categories, storage, { + await propagateCategoriesToLinkedAccounts((email as any).messageId, categories, storage, { priorityScore, priorityTier, priorityReasoning, recommendedAction, }); } @@ -2989,7 +3006,7 @@ function startPollingTrigger(): void { )?.all() as Array<{ mid: string; aiCategories: string | null }> | undefined; for (const r of rows || []) { const cats = mirrorableCategories(r.aiCategories, slugs); - if (cats?.length) propagateCategoriesToLinkedAccounts(r.mid, cats, storage); + if (cats?.length) await propagateCategoriesToLinkedAccounts(r.mid, cats, storage); // Yield to the event loop periodically — a large sweep is up to // accounts×500 propagations, each a synchronous scan of every // account's DB, so without this it blocks the main thread in one diff --git a/apps/desktop/electron/services/vault-credentials.ts b/apps/desktop/electron/services/vault-credentials.ts index 277d7492..252cd0f1 100644 --- a/apps/desktop/electron/services/vault-credentials.ts +++ b/apps/desktop/electron/services/vault-credentials.ts @@ -9,16 +9,22 @@ * the user's real password. Each vault entry therefore carries the host it was * saved for, and a password is only ever injected for that exact host. * - * The same goes for HOW it is sent. A self-signed server needs certificate - * checks off ("allow self-signed"), and a server without encryption needs - * connection security 'none'. Either one hands the password to anyone on the - * network path, and both used to come in with the config. So each entry also - * records the relaxations the user chose when typing that password, and main - * sends it over a connection at least that strict: a config may tighten them, - * never loosen them (a looser one is refused with "re-enter your password"). - * When a stricter connection works, the relaxations it did without are - * switched off for good. OAuth needs none of this: core always verifies an - * OAuth connection and never sends a token unencrypted. + * The same goes for HOW it is sent. A server without encryption needs + * connection security 'none', which hands the password to anyone on the + * network path, and that used to come in with the config. So each entry also + * records the relaxation the user chose when typing that password, and main + * sends it over a connection at least that strict: a config may tighten it, + * never loosen it (a looser one is refused with "re-enter your password"). + * When a stricter connection works, the relaxation it did without is switched + * off for good. OAuth needs none of this: core always verifies an OAuth + * connection and never sends a token unencrypted. + * + * Certificates are not a relaxation any more (CASA 4.1.2): every connection + * verifies, and a server with its own certificate is trusted only for the + * certificate the user approved in main, stored with these credentials and + * applied by certificate-trust.ts. `withSavedPassword` drops any certificate a + * config arrives with, so a saved password never goes out under a pin the + * window chose. * * Entries saved before either binding existed lack those fields. They are bound * on first use, from what main's account registry recorded for that account @@ -60,10 +66,16 @@ export type VaultCredentialKind = 'imap' | 'smtp'; export interface VaultPasswordFound { status: 'found'; password: string; - /** The relaxations saved with it — the most a connection using it may have. */ + /** The relaxation saved with it — the most a connection using it may have. */ transport: TransportOptIns; /** The vault id it was found under. */ id: string; + /** + * The entry still carries the retired "accept any certificate" switch: the + * account was set up for a self-signed server before pinning. Only words the + * approval dialog ("asked once"); it relaxes nothing. + */ + legacyInsecureTLS?: boolean; } export type VaultPasswordResult = @@ -79,7 +91,7 @@ export type VaultPasswordResult = | { status: 'none' }; /** Lower-cased, trimmed, one trailing root dot removed. */ -function normalizeHost(host: string | undefined | null): string { +export function normalizeHost(host: string | undefined | null): string { const h = (host ?? '').trim().toLowerCase(); return h.endsWith('.') ? h.slice(0, -1) : h; } @@ -228,7 +240,7 @@ function legacyHostDecision(id: string, kind: VaultCredentialKind, wanted: strin return sameSite ? { outcome: 'bind', because: `same site as ${sameSite} in the account registry` } : { outcome: 'unknown-server' }; } -const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowInsecureTLS', 'allowPlaintext']; +const TRANSPORT_FIELDS: readonly VaultTransportField[] = ['allowPlaintext']; /** * The relaxations an entry saved before transport binding should be bound to: what @@ -250,16 +262,15 @@ function legacyTransportFor(id: string, kind: VaultCredentialKind, host: string) /** The relaxations saved with `entry`, binding a legacy entry on first use. */ async function savedTransport(id: string, kind: VaultCredentialKind, entry: VaultCredential, host: string): Promise { if (TRANSPORT_FIELDS.every((k) => typeof entry[k] === 'boolean')) { - return { allowInsecureTLS: entry.allowInsecureTLS === true, allowPlaintext: entry.allowPlaintext === true }; + return { allowPlaintext: entry.allowPlaintext === true }; } const legacy = legacyTransportFor(id, kind, host); if (!legacy) return undefined; const bound: TransportOptIns = { - allowInsecureTLS: typeof entry.allowInsecureTLS === 'boolean' ? entry.allowInsecureTLS : legacy.allowInsecureTLS, allowPlaintext: typeof entry.allowPlaintext === 'boolean' ? entry.allowPlaintext : legacy.allowPlaintext, }; await bindAccountSecretTransport(id, kind, bound); - logger.info(`[Vault] bound how the saved ${kind} password for ${accountLogLabel(id)} is sent: self-signed ${bound.allowInsecureTLS ? 'allowed' : 'refused'}, unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); + logger.info(`[Vault] bound how the saved ${kind} password for ${accountLogLabel(id)} is sent: unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); return bound; } @@ -307,7 +318,7 @@ export async function resolveVaultPassword( } const transport = await savedTransport(id, kind, entry, wanted); if (!transport) continue; - return { status: 'found', password: entry.password, transport, id }; + return { status: 'found', password: entry.password, transport, id, ...(entry.allowInsecureTLS === true ? { legacyInsecureTLS: true } : {}) }; } if (mismatch) { logger.warn(`[Vault] refused the saved ${kind} password for host "${wanted}" — it was saved for "${mismatch}"`); @@ -336,27 +347,28 @@ export function vaultRefusalMessage(kind: VaultCredentialKind, host: string, res } /** User-facing reason a connect could not use the saved password the way it asked to. */ -export function transportMismatchMessage(kind: VaultCredentialKind, host: string, beyond: 'insecure-tls' | 'plaintext'): string { +export function transportMismatchMessage(kind: VaultCredentialKind, host: string, _beyond: 'plaintext'): string { const what = kind === 'imap' ? 'mailbox' : 'sending'; - return beyond === 'insecure-tls' - ? `Your saved ${what} password was saved for a connection that checks ${host}'s certificate. Re-enter your password to connect without checking it.` - : `Your saved ${what} password was saved for an encrypted connection to ${host}. Re-enter your password to connect without encryption.`; + return `Your saved ${what} password was saved for an encrypted connection to ${host}. Re-enter your password to connect without encryption.`; } /** * `config` with the saved password in it, sent no more loosely than it was * saved for — or, when the config asks for a relaxation the password was not * saved with, the message telling the user to re-enter it. Never dial on a - * refusal: retrying can't change it. + * refusal: retrying can't change it. Any certificate pin the config carries is + * dropped: only main's own store supplies one (applyCertificatePin), so a + * caller that forgets to apply it gets normal verification, never the window's. */ -export function withSavedPassword( +export function withSavedPassword( config: C, kind: VaultCredentialKind, saved: VaultPasswordFound, ): { config: C } | { refusal: string } { const beyond = transportOptInBeyond(transportOptInsOf(config), saved.transport); if (beyond) return { refusal: transportMismatchMessage(kind, config.host, beyond) }; - return { config: limitTransport({ ...config, password: saved.password }, saved.transport) }; + const { certificatePin: _fromTheWindow, ...rest } = config; + return { config: limitTransport({ ...rest, password: saved.password } as C, saved.transport) }; } /** diff --git a/apps/desktop/electron/shared.ts b/apps/desktop/electron/shared.ts index 2faafaf6..c14c647c 100644 --- a/apps/desktop/electron/shared.ts +++ b/apps/desktop/electron/shared.ts @@ -187,9 +187,12 @@ export function rekeyRuntime(oldId: string, newId: string): void { * Does NOT decide DB ownership — the caller (accounts handler) claims the * default sarvinbox.db slot only for the persisted PRIMARY account, so a * secondary account active on restart never grabs the primary's database. + * + * `null` points back at the pre-account default slot — what an activation that + * failed halfway restores when no account was active before it. */ -export function setCurrentAccount(accountId: string): AccountRuntime { - currentAccountId = accountId; +export function setCurrentAccount(accountId: string | null): AccountRuntime { + currentAccountId = accountId ?? DEFAULT_SLOT; return currentRuntime(); } diff --git a/apps/desktop/electron/utils/navigation-guards.ts b/apps/desktop/electron/utils/navigation-guards.ts index 8c6e192e..e8716e66 100644 --- a/apps/desktop/electron/utils/navigation-guards.ts +++ b/apps/desktop/electron/utils/navigation-guards.ts @@ -16,9 +16,15 @@ * For a subframe the frame guard also passes where the navigation comes from: * the frame's current URL and the URL of the frame that started it. Only the * extension-panel rule reads them (see isPanelNavigationAllowed). + * + * The window-open guard sits here too: a `window.open` / `target="_blank"` + * request never opens an Electron window, and its address goes to the same + * `openExternal` dependency. main.ts passes the external-link gate as that + * dependency for both, so every web address leaving the window — however it + * was asked for — is checked and, when untrusted, warned about first. */ -import { urlSchemeForLog } from '@sarvinbox/core'; +import { errorDiagnostic, urlSchemeForLog } from '@sarvinbox/core'; import { classifyNavigation, @@ -44,10 +50,16 @@ export interface GuardedNavigation { } export interface NavigationGuardDeps { - openExternal: (url: string) => Promise; + /** Hands a web address to the OS. main.ts passes the external-link gate. */ + openExternal: (url: string) => Promise; warn: (message: string, ...args: unknown[]) => void; } +/** The slice of a WebContents the window-open guard needs. */ +export interface WindowOpenGuardTarget { + setWindowOpenHandler(handler: (details: { url: string }) => { action: 'deny' }): void; +} + /** * A WebFrameMain's URL, or undefined when there is none to read. Electron's * WebFrameMain getters throw once the frame is disposed, and a throw here would @@ -84,7 +96,8 @@ export function installNavigationGuards( if (verdict === 'allow') return; event.preventDefault(); if (verdict === 'external') { - deps.openExternal(url).catch((err) => deps.warn('[Main] openExternal failed:', err)); + // The failure's kind only: its message can quote the address. + deps.openExternal(url).catch((err) => deps.warn('[Main] openExternal failed:', errorDiagnostic(err))); } else { // The scheme only: a frame navigation starts inside an email body, so // the rest of the URL is the mail's (its host, path and query). @@ -103,3 +116,18 @@ export function installNavigationGuards( // the renderer did not anticipate cannot get past. contents.on('will-frame-navigate', (event) => apply(event, event.isMainFrame ? 'top' : 'frame')); } + +/** + * Every `window.open` / `target="_blank"` request in the window: no Electron + * window ever opens, and the address goes to `deps.openExternal` (the + * external-link gate, which refuses anything but http, https and mailto and + * warns before an untrusted host). An email's links are rewritten to + * `target="_blank"` (forceLinksExternal), so this is the path a link click + * takes whenever the frame's click listener has not attached yet. + */ +export function installWindowOpenGuard(contents: WindowOpenGuardTarget, deps: NavigationGuardDeps): void { + contents.setWindowOpenHandler(({ url }) => { + deps.openExternal(url).catch((err) => deps.warn('[Main] openExternal failed:', errorDiagnostic(err))); + return { action: 'deny' }; + }); +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 92c4e2af..e173104b 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -81,7 +81,7 @@ "react": "^19.2.0", "react-dom": "^19.2.0", "sanitize-filename": "^1.6.4", - "tar": "^7.5.22", + "tar": "^8.1.0", "tldts": "^7.4.15", "turndown": "^7.2.4", "uniqolor": "^1.1.1", @@ -98,12 +98,14 @@ "@types/node": "^22.20.5", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", + "@types/semver": "^7.7.1", "@vitejs/plugin-react": "^6.1.1", "autoprefixer": "^10.6.1", "electron": "44.9.3", "electron-builder": "^26.17.0", "happy-dom": "^21.0.4", "parse5": "^8.0.1", + "semver": "^7.7.3", "tailwindcss": "^3.4.1", "typescript": "^6.0.0", "vite": "^8.3.2", @@ -182,6 +184,9 @@ "entitlements": "build/entitlements.mac.plist", "entitlementsInherit": "build/entitlements.mac.plist", "notarize": false, + "extendInfo": { + "NSLocalNetworkUsageDescription": "Sarv Inbox checks the senders of your email, for example against spam blocklists, by asking your network's DNS server. On some networks that server is a device on your local network." + }, "protocols": [ { "name": "Sarv Inbox email", diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 1a8d6b23..c56294bd 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -72,6 +72,7 @@ import { setImageTrustAccount } from './utils/remote-images'; // provider here, and a provider's error can carry its response body, which can // quote that mail. Lines name the request and the failure's class, never text. const aiBridgeLog = createLogger('AIBridge'); +const connectionLog = createLogger('Connection'); function App() { const attachmentActions = useAttachmentActions(); @@ -590,14 +591,17 @@ function App() { useEmailStore.setState({ needsReauth: true }); }); } - // The server stopped encrypting a STARTTLS account mid-session (CASA M-5): + // The server stopped encrypting a STARTTLS account mid-session (CASA M-5), + // or now presents a certificate the account does not trust (CASA 4.1.2): // reconnects stopped. Show what to change — NOT the re-auth prompt, the // password was never sent or rejected. if (window.electronAPI?.imap?.onSecurityError) { - window.electronAPI.imap.onSecurityError((message) => { - console.warn('[App] IMAP server would not encrypt a STARTTLS account'); + window.electronAPI.imap.onSecurityError((message, code) => { + connectionLog.warn(code === 'CERTIFICATE_UNTRUSTED' + ? 'IMAP server presented a certificate the account does not trust' + : 'IMAP server would not encrypt a STARTTLS account'); useEmailStore.getState().handleDisconnection?.(); - useEmailStore.setState({ connectionSecurityIssue: message }); + useEmailStore.setState({ connectionSecurityIssue: message, connectionSecurityCode: code ?? 'STARTTLS_UNAVAILABLE' }); }); } diff --git a/apps/desktop/src/components/AdvancedSearchPanel.tsx b/apps/desktop/src/components/AdvancedSearchPanel.tsx index 8e5bfd9d..b26718b9 100644 --- a/apps/desktop/src/components/AdvancedSearchPanel.tsx +++ b/apps/desktop/src/components/AdvancedSearchPanel.tsx @@ -3,7 +3,7 @@ import { Filter as FilterIcon, Paperclip, X } from 'lucide-react'; import { useState, useEffect, useRef, useCallback } from 'react'; import { useEmailStore } from '../store/email-store'; -import { setPendingFilterDraft } from '../utils/filter-draft-bridge'; +import { openFilterEditor } from '../utils/filter-draft-bridge'; interface Contact { id: string; @@ -316,8 +316,7 @@ export function AdvancedSearchPanel({ isOpen, onClose, onSearch, initialQuery = // Turn the current criteria into a new filter: stash a pre-filled draft and // deep-link to Settings → Filters, where the user picks the actions and saves. const handleCreateFilter = () => { - setPendingFilterDraft({ name: '', matchType: 'all', conditions: buildFilterConditions() }); - document.dispatchEvent(new CustomEvent('sarvinbox:open-settings', { detail: { tab: 'filters' } })); + openFilterEditor({ name: '', matchType: 'all', conditions: buildFilterConditions() }); onClose(); }; diff --git a/apps/desktop/src/components/AppSidebar.tsx b/apps/desktop/src/components/AppSidebar.tsx index 70a7a9ef..9bcc7d02 100644 --- a/apps/desktop/src/components/AppSidebar.tsx +++ b/apps/desktop/src/components/AppSidebar.tsx @@ -1,3 +1,4 @@ +import { SARV_HOME_URL } from '@sarvinbox/core/app-links'; import { Mail, Bot, @@ -49,7 +50,7 @@ export function AppSidebar({ activeSection, onSectionChange }: AppSidebarProps) pinned at 12px in both states, so the extra pixel spills harmlessly into the row's right padding. */} + {error &&

{error}

} + + ); +} + +/** "Your key is locked", fixed guidance, and the passphrase form — the reader's prompt and the composer's. */ +export function PgpUnlockPrompt({ detail, ...form }: PgpUnlockFormProps & { detail: string }) { + return ( + + + + ); +} + +/** + * The composer's unlock prompt, for a composer reopened because main refused + * its send: the send asked to be signed with a key still locked this session + * (the `locked` code — the only cause main names). It closes once main says + * the key for `fromEmail` — the address this composer sends as — is open; + * then the user presses Send again. + */ +export function PgpSendUnlockPrompt({ fromEmail, onUnlocked }: { fromEmail: string | undefined; onUnlocked: () => void }) { + const recheck = async () => { + const locked = await window.electronAPI.pgp.signingKeyLocked(fromEmail ?? ''); + return locked.success && locked.data === false; + }; + return ( +
+ +
+ ); +} diff --git a/apps/desktop/src/components/SmtpConfigForm.tsx b/apps/desktop/src/components/SmtpConfigForm.tsx index 78c6c108..cd529081 100644 --- a/apps/desktop/src/components/SmtpConfigForm.tsx +++ b/apps/desktop/src/components/SmtpConfigForm.tsx @@ -6,6 +6,7 @@ import { useState } from 'react'; import { defaultPort } from '../config/email-providers'; import { useEmailStore } from '../store/email-store'; import { deriveSmtpFromImap, accountIdFor } from '../store/helpers'; +import { allowCertificateReview } from '../utils/certificate-review'; import { ConnectionSecuritySelect } from './ConnectionSecuritySelect'; import { VaultPasswordField } from './VaultPasswordField'; @@ -50,7 +51,6 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con // `secure` only, so None came back as STARTTLS and was never kept). const [security, setSecurity] = useState(initial ? resolveConnectionSecurity(initial) : 'ssl'); const [port, setPort] = useState(String(initial?.port ?? 465)); - const [allowInsecure, setAllowInsecure] = useState(!!initial?.allowInsecureTLS); const [username, setUsername] = useState(initial?.username ?? accountEmail); // The SMTP password lives in the vault; the field starts empty and is revealed // only on an explicit OS-authenticated request (VaultPasswordField handles the @@ -77,9 +77,10 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con from: accountEmail || username.trim(), authMethod: imapConfig?.authMethod, oauthProvider: imapConfig?.oauthProvider, - // OAuth always verifies (core resolveTlsOptions), so it never asks. - allowInsecureTLS: (!isOAuth && allowInsecure) || undefined, }; + // The user asked to verify: this connect (only) may ask about an + // untrusted certificate, in main's dialog. Not for OAuth: never asks. + if (!isOAuth) allowCertificateReview(vaultAccountId, 'smtp'); await connectSmtp(config); // verifies via nodemailer transporter.verify() markSmtpConfigured(true); onVerified(); @@ -128,17 +129,12 @@ export function SmtpConfigForm({ onVerified, onBack, submitLabel = 'Verify & Con className={inputCls} /> - {/* Not offered for OAuth: the provider's certificate is always checked. */} + {/* There is no "allow self-signed" switch any more (CASA 4.1.2): a server + with its own certificate is shown to the user, by main, to approve. */} {!isOAuth && ( - +

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

)} {error && ( diff --git a/apps/desktop/src/components/ThreadSummary.tsx b/apps/desktop/src/components/ThreadSummary.tsx index 8c1d3d88..ab2479da 100644 --- a/apps/desktop/src/components/ThreadSummary.tsx +++ b/apps/desktop/src/components/ThreadSummary.tsx @@ -13,9 +13,17 @@ const CAPABILITY_THREAD_SUMMARIZE = 'thread.summarize'; interface ThreadSummaryProps { threadId: string; emails: EmailRecord[]; + /** + * The account that owns the thread (All Inboxes shows other accounts' + * threads). The cache is keyed by thread id, which repeats across accounts, + * so it is read from and written to this account only. Omitted: the active + * account. + */ + accountId?: string | null; } -export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { +export function ThreadSummary({ threadId, emails, accountId }: ThreadSummaryProps) { + const ownerAccountId = accountId ?? undefined; const [summary, setSummary] = useState(null); const [loading, setLoading] = useState(false); const [expanded, setExpanded] = useState(false); @@ -30,7 +38,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { const loadCachedSummary = async () => { try { - const result = await window.electronAPI.ai.getThreadSummary(threadId); + const result = await window.electronAPI.ai.getThreadSummary(threadId, ownerAccountId); if (result.success && result.data) { // Check if summary is still valid (email count matches) if (result.data.emailCount === emails.length) { @@ -56,7 +64,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { }; loadCachedSummary(); - }, [threadId, emails.length]); + }, [threadId, emails.length, ownerAccountId]); const generateSummary = async () => { if (loading || emails.length < 2) return; @@ -146,7 +154,7 @@ export function ThreadSummary({ threadId, emails }: ThreadSummaryProps) { emailCount: emails.length, processedAt: Math.floor(Date.now() / 1000), modelUsed: getDefaultProvider()?.model || 'unknown', - }); + }, ownerAccountId); } else { setError('Failed to generate summary'); } diff --git a/apps/desktop/src/components/TrustedCertificate.tsx b/apps/desktop/src/components/TrustedCertificate.tsx new file mode 100644 index 00000000..8d4aba0c --- /dev/null +++ b/apps/desktop/src/components/TrustedCertificate.tsx @@ -0,0 +1,122 @@ +import { ShieldCheck } from 'lucide-react'; +import { useEffect, useState } from 'react'; + +import { formatFingerprint } from '../utils/certificate-review'; + +type Kind = 'imap' | 'smtp'; + +interface ApprovedCertificate { + host: string; + port: number; + sha256: string; + approvedAt: number; + validTo: string; +} + +interface TrustedCertificateProps { + /** The account whose approved certificate to show. */ + accountId: string | null | undefined; + kind: Kind; + /** The server the account uses now; a certificate approved for another host or port is not shown. */ + host?: string; + port?: number; +} + +/** Lower-cased, trimmed, one trailing root dot removed — main's own host rule. */ +const normalizeHost = (host: string): string => { + const h = host.trim().toLowerCase(); + return h.endsWith('.') ? h.slice(0, -1) : h; +}; +const sameHost = (a: string, b: string): boolean => normalizeHost(a) === normalizeHost(b); + +/** + * The certificate the user approved for this account's server (CASA 4.1.2): + * its SHA-256 fingerprint and when it was approved, with Remove. Shows nothing + * when there is none — the server is then checked against the system's trusted + * authorities like any other. Approving happens only in main's own dialog, + * during a connect; removing one here stops trusting it at once (main closes + * the connections that used it), and the next reconnect from the account + * settings asks again. + */ +export function TrustedCertificate({ accountId, kind, host, port }: TrustedCertificateProps) { + const [certificate, setCertificate] = useState(null); + const [removing, setRemoving] = useState(false); + const [removed, setRemoved] = useState(false); + const [error, setError] = useState(''); + + useEffect(() => { + let cancelled = false; + setCertificate(null); + setRemoved(false); + setError(''); + if (!accountId) return; + void (async () => { + try { + const res = await window.electronAPI?.certificates?.list(accountId); + if (cancelled || !res?.success) return; + const found = res.data?.[kind]; + const matches = found && (!host || sameHost(found.host, host)) && (port === undefined || found.port === port); + setCertificate(matches ? found : null); + } catch { + // Nothing to show: the server is then checked like any other. + } + })(); + return () => { cancelled = true; }; + }, [accountId, kind, host, port]); + + const remove = async () => { + if (!accountId) return; + setRemoving(true); + setError(''); + try { + const res = await window.electronAPI.certificates.remove(accountId, kind); + if (!res?.success) throw new Error(res?.error || 'The approved certificate could not be removed.'); + setCertificate(null); + setRemoved(true); + } catch (err) { + setError((err as Error).message); + } finally { + setRemoving(false); + } + }; + + if (removed) { + return ( +

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

+ ); + } + if (!certificate) return null; + + const approved = new Date(certificate.approvedAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); + return ( +
+
+ ); +} diff --git a/apps/desktop/src/components/antivirus/AntivirusSetupModal.tsx b/apps/desktop/src/components/antivirus/AntivirusSetupModal.tsx index bdcd592f..d3b6c924 100644 --- a/apps/desktop/src/components/antivirus/AntivirusSetupModal.tsx +++ b/apps/desktop/src/components/antivirus/AntivirusSetupModal.tsx @@ -17,6 +17,8 @@ export function AntivirusSetupDialog({ extensionId, onClose }: { extensionId: st const [challenge, setChallenge] = useState(null); const [oauthAccountId, setOAuthAccountId] = useState(null); const [savedCredentialsLocked, setSavedCredentialsLocked] = useState(false); + // The scanner refused the saved credential this session (main's answer, not a guess). + const [savedSignInRejected, setSavedSignInRejected] = useState(false); const [selectedAccounts, setSelectedAccounts] = useState([]); const [allowBody, setAllowBody] = useState(false); const [attachmentConsent, setAttachmentConsent] = useState(false); @@ -32,7 +34,8 @@ export function AntivirusSetupDialog({ extensionId, onClose }: { extensionId: st const oauthGeneration = useRef(0); const api = window.electronAPI?.antivirus; const sessionOnly = setup?.credentialStorage === 'session'; - const canRecoverWithSarv = savedCredentialsLocked && extensionId === 'clamav-scan' && (!endpoint.trim() || endpoint.trim() === 'https://av.sarv.com'); + const canRecoverWithSarv = (savedCredentialsLocked || savedSignInRejected) && extensionId === 'clamav-scan' && + (!endpoint.trim() || endpoint.trim() === 'https://av.sarv.com'); useEffect(() => { activeRef.current = true; @@ -60,6 +63,7 @@ export function AntivirusSetupDialog({ extensionId, onClose }: { extensionId: st if (!response.success || !response.data) throw new Error(response.error || 'Could not load scanner setup'); setSetup(response.data); setSavedCredentialsLocked(Boolean(response.data.savedCredentialsLocked)); + setSavedSignInRejected(Boolean(response.data.signInRejected)); setEndpoint(response.data.endpoint || (response.data.savedCredentialsLocked && extensionId === 'clamav-scan' ? 'https://av.sarv.com' : '')); setSelectedAccounts(response.data.allowedAccountIds); setAllowBody(response.data.allowBody); @@ -223,6 +227,7 @@ export function AntivirusSetupDialog({ extensionId, onClose }: { extensionId: st
{savedCredentialsLocked &&

Saved scanner sign-in is locked. Sign in again for this session, or unlock the system keychain. Your saved scanner settings will be kept.

} + {!savedCredentialsLocked && savedSignInRejected &&

The scanner no longer accepts the saved sign-in, so attachments cannot be scanned. Sign in again, or enter a new credential and verify the scanner.

} {sessionOnly &&

Scanner sign-in lasts for this session

Without system-keychain storage, your scanner credential stays only in app memory and is never saved to disk. Sign in again after quitting Inbox.

@@ -255,8 +260,10 @@ export function AntivirusSetupDialog({ extensionId, onClose }: { extensionId: st {canRecoverWithSarv &&
-

Choose exactly one mailbox below, then sign in again and review scanner sharing. Your locked saved sign-in will be kept.

- +

{savedCredentialsLocked + ? 'Choose exactly one mailbox below, then sign in again and review scanner sharing. Your locked saved sign-in will be kept.' + : 'Choose exactly one mailbox below, then sign in again and review scanner sharing. The new sign-in replaces the one the scanner refused.'}

+ {busy === 'connecting' && } {oauthAccountId && <>

This sign-in is limited to {setup?.accounts?.find(account => account.id === oauthAccountId)?.email || 'the selected mailbox'}. Email body scanning stays off.

}
} diff --git a/apps/desktop/src/components/attachment-viewer/useAttachmentActions.ts b/apps/desktop/src/components/attachment-viewer/useAttachmentActions.ts index faa2eddd..98cc6197 100644 --- a/apps/desktop/src/components/attachment-viewer/useAttachmentActions.ts +++ b/apps/desktop/src/components/attachment-viewer/useAttachmentActions.ts @@ -2,6 +2,7 @@ import { createLogger } from '@sarvinbox/core/logger'; import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { AttachmentDownloadPhase } from '../../../electron/preload'; +import { SCAN_FAILURE_DOWNLOAD_MESSAGES } from '../../utils/attachment-scan-failures'; import { AttachmentActionsContext } from './attachment-actions-context'; import type { AttachmentTransfer } from './attachment-transfer-types'; @@ -59,11 +60,10 @@ export interface AttachmentActions { // reveal credentials, internal paths, or remote response bodies in the renderer. const SAFE_ATTACHMENT_ERRORS = new Set([ 'Download blocked: ClamAV detected a threat.', - 'Download blocked: the attachment could not be fully scanned.', - 'Download blocked: scanning failed. Try again when the scanner is available.', - 'Configure ClamAV Scan before downloading attachments.', + // Why a scan gave no verdict, one message per reason (busy, sign-in + // rejected, unreachable…), from the table main words them with. + ...Object.values(SCAN_FAILURE_DOWNLOAD_MESSAGES), 'This account is not approved for attachment scanning. Review scanner setup.', - 'Download blocked: scanner settings changed. Review scanner setup and try again.', 'Download blocked: this attachment is unavailable or exceeds the scanner limits.', 'Download blocked: attachment details timed out. Reconnect this account and try again.', 'Download blocked: attachment details are unavailable. Reopen this email and try again.', diff --git a/apps/desktop/src/components/email-detail/EmailDetail.tsx b/apps/desktop/src/components/email-detail/EmailDetail.tsx index ddde1ead..13d74c96 100644 --- a/apps/desktop/src/components/email-detail/EmailDetail.tsx +++ b/apps/desktop/src/components/email-detail/EmailDetail.tsx @@ -178,6 +178,7 @@ export function EmailDetail(options: EmailReaderOptions = {}) { )}
diff --git a/apps/desktop/src/components/email-detail/PgpMessageView.tsx b/apps/desktop/src/components/email-detail/PgpMessageView.tsx index 8d27949b..1eda3c8d 100644 --- a/apps/desktop/src/components/email-detail/PgpMessageView.tsx +++ b/apps/desktop/src/components/email-detail/PgpMessageView.tsx @@ -1,20 +1,16 @@ -import { Download, Loader2, Lock, LockKeyhole, RotateCw, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'; -import { useEffect, useState, type FormEvent, type ReactNode } from 'react'; +import { PGP_FAILURE_MESSAGE } from '@sarvinbox/core/pgp-failure'; +import { Download, Loader2, Lock, RotateCw, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'; +import { useEffect, useState, type ReactNode } from 'react'; import { messageAccountOf } from '../../utils/pane-account'; import { remoteImageFactsOf } from '../../utils/remote-images'; import { UnscannedAttachmentNotice } from '../attachment-viewer/AttachmentDownloadStatus'; import { formatSize } from '../attachment-viewer/AttachmentViewer'; +import { PgpNotice, PgpUnlockForm } from '../PgpUnlockPrompt'; import { SandboxedEmailBody } from '../SandboxedEmailBody'; import { Tooltip } from '../Tooltip'; -import { - pgpBadge, - pgpFailureView, - unlockLockedKeys, - type PgpBadge, - type PgpViewResult, -} from './pgp-view-model'; +import { pgpBadge, pgpFailureView, type PgpBadge, type PgpViewResult } from './pgp-view-model'; export interface PgpMessageViewProps { email: { @@ -56,54 +52,6 @@ function PgpBadgeChip({ badge, encrypted }: { badge: PgpBadge; encrypted: boolea ); } -function UnlockForm({ onUnlocked }: { onUnlocked: () => void }) { - const [passphrase, setPassphrase] = useState(''); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - - const submit = async (event: FormEvent) => { - event.preventDefault(); - if (!passphrase || busy) return; - setBusy(true); - setError(null); - try { - const unlocked = await unlockLockedKeys(window.electronAPI.pgp, passphrase); - if (unlocked > 0) { - setPassphrase(''); - onUnlocked(); - } else { - setError('That passphrase did not unlock any of your keys.'); - } - } catch (caught) { - setError((caught as Error).message); - } finally { - setBusy(false); - } - }; - - return ( -
- setPassphrase(event.target.value)} - placeholder="Key passphrase" - aria-label="Key passphrase" - className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm" - /> - - {error &&

{error}

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

{failure.detail}

- {failure.canUnlock && setAttempt((n) => n + 1)} />} - {failure.canRetry && ( - - )} -
-
-
+ + {failure.canUnlock && } + {failure.canRetry && ( + + )} + ); } diff --git a/apps/desktop/src/components/email-detail/UnsubscribeButton.tsx b/apps/desktop/src/components/email-detail/UnsubscribeButton.tsx index de6f42f6..65452643 100644 --- a/apps/desktop/src/components/email-detail/UnsubscribeButton.tsx +++ b/apps/desktop/src/components/email-detail/UnsubscribeButton.tsx @@ -90,6 +90,9 @@ export function UnsubscribeButton({ emailId, accountId, listUnsubscribe, listUns setError(null); try { const result = await window.electronAPI.unsubscribe.run(emailId, route, accountId); + // The reader chose Cancel on the link warning that names the sender's + // page: nothing opened and nothing failed, so the button simply stays. + if (result?.cancelled) return; if (!result?.success) { setError(result?.error || 'The unsubscribe request failed'); return; diff --git a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts index e7a0d4b0..f27992f9 100644 --- a/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts +++ b/apps/desktop/src/components/email-detail/hooks/useEmailDetail.ts @@ -1,5 +1,5 @@ import { hasGlobalDomParser } from '@sarv-in/email-chat-view/transform'; -import type { EmailRecord } from '@sarvinbox/core'; +import type { EmailRecord, SendPgpRequest } from '@sarvinbox/core'; import { compareConversationOrder, conversationFoldersOf, @@ -26,10 +26,12 @@ import { useEmailStore } from '../../../store/email-store'; import type { LocalCalendarAvailability } from '../../../types/local-calendar'; import { needsAttachmentMetadata } from '../../../utils/attachment-metadata'; import { collapseDuplicateMessages } from '../../../utils/duplicate-messages'; +import { filterDraftFromSender, openFilterEditor } from '../../../utils/filter-draft-bridge'; import { toForwardSource } from '../../../utils/forward-quote'; import { paneAccountOf } from '../../../utils/pane-account'; import { savedDraftContent } from '../../../utils/saved-draft-content'; import { isDraftEmail } from '../../../utils/thread-utils'; +import { openTranslation } from '../../../utils/translate'; import { composeAiTurns, firstEmailFacts } from '../ai-view-compose'; import { polishEntriesOf, threadTurns } from '../chat-message-adapter'; import { chatViewRulesFor } from '../chat-view-rules'; @@ -209,13 +211,13 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon // written for. Composers get it only on that message (see inlineReplyDraft // below); moving the composer elsewhere does NOT drop it, so coming back to // that message brings the draft (and its stored Message-ID) back with it. - const [inlineReplySeed, setInlineReplySeed] = useState | undefined>(undefined); + const [inlineReplySeed, setInlineReplySeed] = useState | undefined>(undefined); const inlineReplyHandlerRef = useRef<(mode: 'reply' | 'replyAll') => void>(() => { }); const consumedReplyRequestRef = useRef(null); const [showInlineForward, setShowInlineForward] = useState(false); const [forwardingEmail, setForwardingEmail] = useState(null); // The forward's seed (what Undo send restored), on the same terms as the reply's. - const [inlineForwardSeed, setInlineForwardSeed] = useState | undefined>(undefined); + const [inlineForwardSeed, setInlineForwardSeed] = useState | undefined>(undefined); const inlineForwardHandlerRef = useRef<() => void>(() => { }); // What each open composer is handed: its seed, only when the seed was written // for the message that composer is open on — never another message's. @@ -1125,6 +1127,8 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon draftMessageId: restoreDraft.draftMessageId, unsaved: restoreDraft.unsaved, ...(restoreDraft.calendarAvailability ? { calendarAvailability: restoreDraft.calendarAvailability } : {}), + // A send refused for a locked signing key reopens with the unlock prompt. + ...(restoreDraft.pgpUnlock ? { pgpUnlock: restoreDraft.pgpUnlock } : {}), }); setShowInlineReply(true); setShowInlineForward(false); @@ -1140,6 +1144,7 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon draftMessageId: restoreDraft.draftMessageId, unsaved: restoreDraft.unsaved, ...(restoreDraft.calendarAvailability ? { calendarAvailability: restoreDraft.calendarAvailability } : {}), + ...(restoreDraft.pgpUnlock ? { pgpUnlock: restoreDraft.pgpUnlock } : {}), }); setShowInlineForward(true); setShowInlineReply(false); @@ -1560,18 +1565,16 @@ export function useEmailDetail(options: EmailReaderOptions = {}): EmailDetailCon } }; + // Open Settings → Filters with a new filter for this sender, "Skip AI + // checks" ticked; the user picks any other action and saves. const handleFilterLikeThis = (email: any) => { - if (!email) return; - alert(`Create filter for emails from: ${email.fromAddress}\n\nThis feature will be available in a future update.`); + const draft = filterDraftFromSender(email?.fromAddress); + if (draft) openFilterEditor(draft); }; - const handleTranslate = (email: any) => { - if (!email) return; - const text = email.cleanBody || email.rawBody || ''; - const truncatedText = text.substring(0, 5000); - const url = `https://translate.google.com/?sl=auto&tl=en&text=${encodeURIComponent(truncatedText)}`; - window.open(url, '_blank'); - }; + // Main builds and opens the Translate address (no link warning: the user + // chose the app's own command); only the text and language cross over. + const handleTranslate = (email: any) => openTranslation(email); const handleDetectSignature = async (email: any) => { if (!email) return; diff --git a/apps/desktop/src/components/email-detail/pgp-view-model.ts b/apps/desktop/src/components/email-detail/pgp-view-model.ts index 4def9ebc..8aa1c761 100644 --- a/apps/desktop/src/components/email-detail/pgp-view-model.ts +++ b/apps/desktop/src/components/email-detail/pgp-view-model.ts @@ -56,35 +56,43 @@ export function pgpBadge(wasEncrypted: boolean, signature: PgpSignatureView): Pg export type PgpOpenFailureCode = Extract['code']; +/** + * The unlock prompt's fixed words — the reader's (a message encrypted to a + * locked key) and the composer's (a send that must be signed with one). They + * never vary with why an unlock failed: that is always PGP_FAILURE_MESSAGE. + */ +export const PGP_LOCKED_TITLE = 'Your key is locked'; +export const PGP_UNLOCK_TO_READ = 'Enter the passphrase of your OpenPGP key to read this message. It stays unlocked until you quit.'; +export const PGP_UNLOCK_TO_SIGN = 'Enter the passphrase of your OpenPGP key to sign this message, then send it again. It stays unlocked until you quit.'; + +/** + * The one line of guidance under EVERY failure to open, whatever the cause — + * so the user is still pointed at the fix for a key they have not added, + * without the screen telling that cause apart from the others. + */ +export const PGP_FAILURE_HINT = "If it was encrypted to a key you haven't added, import that key in Settings → Encryption."; + export interface PgpFailureView { title: string; detail: string; + /** Fixed guidance under the sentence, the same for every failure. */ + hint?: string; /** Unlock with a passphrase. */ canUnlock: boolean; canRetry: boolean; } +/** + * What the reader shows for a message that did not open. A locked key is a + * prompt, with fixed guidance; every other failure looks exactly the same — + * the same title, main's one sentence (PGP_FAILURE_MESSAGE), the same line of + * guidance and a retry — whether the key was missing, the ciphertext damaged + * or tampered with, or the source unreachable (CASA 4.1.4: what the user sees + * must not tell causes apart). + */ export function pgpFailureView(code: PgpOpenFailureCode, error: string): PgpFailureView { - switch (code) { - case 'locked': - return { - title: 'Your key is locked', - detail: 'Enter the passphrase of your OpenPGP key to read this message. It stays unlocked until you quit.', - canUnlock: true, - canRetry: false, - }; - case 'no-key': - return { - title: 'None of your keys can open this message', - detail: 'It was encrypted to a key you do not have here. Import that key in Settings → Encryption.', - canUnlock: false, - canRetry: false, - }; - case 'bad-data': - return { title: 'This encrypted message is damaged', detail: error, canUnlock: false, canRetry: false }; - case 'unavailable': - return { title: 'The encrypted message could not be loaded', detail: error, canUnlock: false, canRetry: true }; - } + if (code === 'locked') return { title: PGP_LOCKED_TITLE, detail: PGP_UNLOCK_TO_READ, canUnlock: true, canRetry: false }; + return { title: 'Encrypted message', detail: error, hint: PGP_FAILURE_HINT, canUnlock: false, canRetry: true }; } /** The two bridge calls unlocking needs — injected so the loop is tested without Electron. */ @@ -97,11 +105,15 @@ export interface PgpUnlockApi { * Try the passphrase on every locked own key. The reader does not know which * key a message was encrypted to until one opens it, and asking the user to * pick a fingerprint is asking them a question they cannot answer. - * Resolves to how many keys it unlocked. + * + * Says nothing about success: whether the key a message or a send NEEDS is + * open now is for the caller to check afterwards. Counting keys got both + * wrong — a key unlocked elsewhere left nothing locked (read as failure: a + * dead end), and the passphrase of some other key read as success (the + * prompt closed, and the send was refused again). */ -export async function unlockLockedKeys(api: PgpUnlockApi, passphrase: string): Promise { +export async function unlockLockedKeys(api: PgpUnlockApi, passphrase: string): Promise { const listed = await api.listOwnKeys(); const locked = (listed.data ?? []).filter((key) => !key.unlocked); - const results = await Promise.all(locked.map((key) => api.unlock(key.fingerprint, passphrase))); - return results.filter((result) => result.success).length; + await Promise.allSettled(locked.map((key) => api.unlock(key.fingerprint, passphrase))); } diff --git a/apps/desktop/src/components/email-detail/types.ts b/apps/desktop/src/components/email-detail/types.ts index a1df5789..552f1be9 100644 --- a/apps/desktop/src/components/email-detail/types.ts +++ b/apps/desktop/src/components/email-detail/types.ts @@ -1,5 +1,5 @@ import type { ChatMessage } from '@sarv-in/email-chat-view'; -import type { EmailRecord } from '@sarvinbox/core'; +import type { EmailRecord, SendPgpRequest } from '@sarvinbox/core'; import type { SignatureDetectionResult } from '../../services/ai-service'; @@ -65,6 +65,8 @@ export interface EmailDetailContext { isAIDraft?: boolean; aiReasoning?: string; agentDecisionId?: string; + /** Reopened because main refused its send for a locked signing key (RestoreDraft.pgpUnlock). */ + pgpUnlock?: SendPgpRequest; }; showInlineForward: boolean; forwardingEmail: any | null; @@ -76,6 +78,7 @@ export interface EmailDetailContext { attachments: any[]; draftMessageId?: string; unsaved?: boolean; + pgpUnlock?: SendPgpRequest; }; /** The reader's chat-view setting for this email (auto setting, or the toggle). */ chatViewEnabled: boolean; diff --git a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx index 7bd1302f..a3e2a88b 100644 --- a/apps/desktop/src/components/onboarding/EmailSetupStep.tsx +++ b/apps/desktop/src/components/onboarding/EmailSetupStep.tsx @@ -7,7 +7,8 @@ import { EMAIL_PROVIDERS, defaultPort, type ConnectionSecurity } from '../../con import { getOnboardingEmailProgress, isOnboardingPending } from '../../services/onboarding-progress'; import { requestConfirm } from '../../store/confirm-service'; import { useEmailStore } from '../../store/email-store'; -import { findAccountByEmailHost } from '../../store/helpers'; +import { connectAccountId, findAccountByEmailHost } from '../../store/helpers'; +import { allowCertificateReview } from '../../utils/certificate-review'; import { GmailPrivacyNotice } from '../GmailPrivacyNotice'; import { Tooltip } from '../Tooltip'; @@ -49,9 +50,12 @@ interface FormValues { smtpHost: string; smtpPort: string; smtpSecurity: ConnectionSecurity; - allowInsecure: boolean; skipSending: boolean; } +/** The id these settings are (or will be) saved under — addAccount's own rule. */ +const accountIdOf = (config: { username: string; host: string }): string => + connectAccountId(useEmailStore.getState().accounts, config.username, config.host); + interface ConnectedEmail { result: EmailSetupResult; smtp: SMTPConfig; @@ -92,11 +96,12 @@ function savedForm(connection: ConnectedEmail): FormValues { smtpHost: connection.smtp.host, smtpPort: String(connection.smtp.port), // The saved choice, None included (resolveConnectionSecurity). smtpSecurity: resolveConnectionSecurity(connection.smtp), - allowInsecure: Boolean(imap?.allowInsecureTLS), }; } const EMAIL_CHOICES = ['sarv', 'gmail', 'outlook', 'yahoo', 'other']; +/** A switch to the connected account that the app refused (main stayed on another mailbox). */ +const SWITCH_REFUSED = 'This mailbox could not be opened right now. Try again in a moment.'; const inputClass = 'w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-60'; const primaryClass = 'inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50'; const textButtonClass = 'rounded-md px-2 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50'; @@ -108,7 +113,7 @@ function initialForm(providerId: string): FormValues { imapPort: String(preset?.imapPort ?? 993), imapSecurity: preset?.imapSecurity ?? 'ssl', smtpHost: preset?.smtpHost ?? '', smtpPort: String(preset?.smtpPort ?? 465), smtpSecurity: preset?.smtpSecurity ?? 'ssl', - allowInsecure: false, skipSending: false, + skipSending: false, }; } @@ -242,6 +247,9 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp } setLoading('sending'); try { + // Reached only from the user's Connect / Retry: the sending check may ask + // (in main) about an untrusted certificate. OAuth never asks. + if (connection.smtp.authMethod !== 'oauth2') allowCertificateReview(connection.result.accountId, 'smtp'); await useEmailStore.getState().connectSmtp(connection.smtp); if (!isCurrent(id)) return; if (useEmailStore.getState().activeAccountId !== connection.result.accountId) throw new Error('The active email account changed. Retry the sending check.'); @@ -264,7 +272,9 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp if (purpose === 'add-account') { // Probe in isolation before replacing a working account. OAuth identity // alone does not prove that the receiving server accepts its token. - const probe = await window.electronAPI.imap.probeCredentials(config as IMAPConfig); + // For the account these settings will be saved as: the certificate + // approved for it (main asks during the probe) is the one it dials with. + const probe = await window.electronAPI.imap.probeCredentials(config as IMAPConfig, accountIdOf(config)); if (!isCurrent(id)) return; if (!probe.success) throw new Error(probe.error || 'Receiving authentication failed. Check your connection details and retry.'); const existing = findAccountByEmailHost(useEmailStore.getState().accounts, config.username, config.host); @@ -356,14 +366,18 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp host: form.smtpHost.trim(), port: form.skipSending ? Number(form.smtpPort) || defaultPort('smtp', form.smtpSecurity) : validPort(form.smtpPort), security: form.smtpSecurity, secure: form.smtpSecurity === 'ssl', username: email, from: email, // Password whitespace can be meaningful. Never silently rewrite it. - password: form.password, authMethod: 'password', allowInsecureTLS: form.allowInsecure || undefined, + password: form.password, authMethod: 'password', }; if (!form.skipSending && !smtp.host) throw new Error('Enter the sending server or choose to set up sending later.'); - await connectMailbox({ + const imap: MailConfig = { host: form.imapHost.trim(), port: validPort(form.imapPort), security: form.imapSecurity, secure: form.imapSecurity === 'ssl', username: form.username.trim() || email, password: form.password, - authMethod: 'password', allowInsecureTLS: form.allowInsecure || undefined, - }, smtp, id, form.skipSending); + authMethod: 'password', + }; + // The user asked to connect: this test (only) may ask, in main's dialog, + // about an untrusted certificate; this form never approves one. + allowCertificateReview(accountIdOf(imap), 'imap'); + await connectMailbox(imap, smtp, id, form.skipSending); } catch (failure) { if (isCurrent(id)) setError(errorMessage(failure)); } finally { @@ -389,6 +403,7 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp try { if (useEmailStore.getState().activeAccountId !== connected.result.accountId) { await useEmailStore.getState().selectAccount(connected.result.accountId); + if (useEmailStore.getState().activeAccountId !== connected.result.accountId) throw new Error(SWITCH_REFUSED); } if (isCurrent(id)) complete({ ...connected, smtp: { ...connected.smtp, password: '' } }); } catch (failure) { if (isCurrent(id)) setError(errorMessage(failure)); } @@ -402,7 +417,12 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp try { const account = useEmailStore.getState().accounts.find((item) => item.id === connected.result.accountId); if (!account) throw new Error('This saved account is unavailable. Choose your provider and connect again.'); - if (useEmailStore.getState().activeAccountId !== account.id) await useEmailStore.getState().selectAccount(account.id); + // A refused switch leaves another mailbox active: connecting now would + // run this account's sign-in on that mailbox's connection. + if (useEmailStore.getState().activeAccountId !== account.id) { + await useEmailStore.getState().selectAccount(account.id); + if (useEmailStore.getState().activeAccountId !== account.id) throw new Error(SWITCH_REFUSED); + } if (!isCurrent(id)) return; // Reconnect uses the saved native vault credentials and starts background // sync. It does not add, delete or replace the existing account. @@ -463,7 +483,7 @@ export function EmailSetupStep({ stage, active, onStageChange, onConnected, purp

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

- +

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

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

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

{error && (
diff --git a/apps/desktop/src/components/security/AttachmentScanningTab.tsx b/apps/desktop/src/components/security/AttachmentScanningTab.tsx new file mode 100644 index 00000000..26f7be56 --- /dev/null +++ b/apps/desktop/src/components/security/AttachmentScanningTab.tsx @@ -0,0 +1,209 @@ +import type { AntivirusSetupStatus } from '@sarvinbox/core'; +import { formatDistanceStrict } from 'date-fns'; +import { Loader2, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'; +import { useCallback, useEffect, useRef, useState } from 'react'; + +import { + SCAN_FAILURE_DESCRIPTIONS, + type AttachmentScannerSummary, + type ScanFailureRecord, + type ScannerConnectionTest, +} from '../../utils/attachment-scan-failures'; +import { AntivirusSetupDialog } from '../antivirus/AntivirusSetupModal'; + +/** + * Security → Attachment scanning: one card per scanner extension that is + * turned on. It shows what the saved setup is (never its credential), checks + * it against the scanner without changing it, opens the one setup dialog the + * app has, and says why the last scan failed. Shown only while such an + * extension is on (see `Security`). + */ +export function AttachmentScanningTab({ scanners, onChanged }: { + scanners: AttachmentScannerSummary[]; + /** Ask main again: setup or the last failure may have changed. */ + onChanged: () => void; +}) { + return ( +
+

+ Attachments from the accounts you approve are sent to the scanner before you can view, open or save them. + Check the scanner here, sign in again, or change which accounts it may scan. +

+ {scanners.map((scanner) => ( + + ))} +
+ ); +} + +const transientNote = (transient: boolean) => (transient + ? 'This usually clears on its own. Try again in a moment.' + : 'This needs your attention before scanning can work.'); + +function statusOf(setup: AntivirusSetupStatus): { label: string; tone: 'ok' | 'warn' | 'none' } { + if (setup.savedCredentialsLocked) return { label: 'Saved sign-in is locked', tone: 'warn' }; + if (setup.signInRejected) return { label: 'The scanner refused the saved sign-in', tone: 'warn' }; + if (setup.configured) return { label: 'Set up', tone: 'ok' }; + return { label: 'Not set up', tone: 'none' }; +} + +function credentialLabel(setup: AntivirusSetupStatus): string { + if (setup.savedCredentialsLocked) return 'In the system keychain, which is locked. Unlock it, or sign in again for this session.'; + if (setup.credentialStorage === 'os-keychain') return 'In the system keychain'; + if (setup.credentialStorage === 'session') return 'In memory for this session only. Sign in again after quitting Inbox.'; + return 'Unknown'; +} + +function TestResult({ result }: { result: ScannerConnectionTest }) { + if (!result.ok) { + return ( +

+ {SCAN_FAILURE_DESCRIPTIONS[result.reason]} {transientNote(result.transient)} +

+ ); + } + const updated = Date.parse(result.engine.signaturesUpdatedAt); + const age = Number.isFinite(updated) ? formatDistanceStrict(updated, result.checkedAt, { addSuffix: true }) : null; + return ( +

+ Connected. {result.engine.name} {result.engine.version}, virus definitions {result.engine.signatureVersion} + {age ? ` updated ${age}` : ''}. +

+ ); +} + +function LastFailure({ failure }: { failure: ScanFailureRecord | null }) { + if (!failure) return

No failed scans since Inbox started.

; + return ( +

+ Last failed scan, {new Date(failure.at).toLocaleString()}:{' '} + {SCAN_FAILURE_DESCRIPTIONS[failure.reason]}{' '} + {transientNote(failure.transient)} +

+ ); +} + +function ScannerCard({ scanner, onChanged }: { scanner: AttachmentScannerSummary; onChanged: () => void }) { + const [setup, setSetup] = useState(null); + const [loadError, setLoadError] = useState(''); + const [test, setTest] = useState(null); + const [testError, setTestError] = useState(''); + const [testing, setTesting] = useState(false); + const [setupOpen, setSetupOpen] = useState(false); + const mounted = useRef(true); + const usable = scanner.available && scanner.granted; + + useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); + + const load = useCallback(async () => { + if (!usable) return; + try { + const response = await window.electronAPI.antivirus.getSetup(scanner.extensionId); + if (!mounted.current) return; + if (!response.success || !response.data) throw new Error('unavailable'); + setSetup(response.data); + setLoadError(''); + } catch { + if (mounted.current) setLoadError('Scanner setup could not be read. Try again.'); + } + }, [scanner.extensionId, usable]); + + useEffect(() => { void load(); }, [load]); + + const runTest = async () => { + if (testing) return; + setTesting(true); setTestError(''); setTest(null); + try { + const response = await window.electronAPI.antivirus.testConnection(scanner.extensionId); + if (!mounted.current) return; + if (!response.success || !response.data) throw new Error('unavailable'); + setTest(response.data); + // A refused sign-in changes what setup offers (Sarv sign-in again). + void load(); + } catch { + if (mounted.current) setTestError('The connection test could not run. Try again.'); + } finally { + if (mounted.current) setTesting(false); + } + }; + + const closeSetup = () => { + setSetupOpen(false); + setTest(null); + void load(); + onChanged(); + }; + + const status = setup ? statusOf(setup) : null; + const StatusIcon = status?.tone === 'ok' ? ShieldCheck : status?.tone === 'warn' ? ShieldAlert : ShieldQuestion; + const approved = setup ? (setup.accounts ?? []).filter((account) => setup.allowedAccountIds.includes(account.id)) : []; + + return ( +
+

{scanner.name}

+ {!usable ? ( +

+ {scanner.granted + ? 'This extension is turned on but could not be loaded, so attachments cannot be scanned. Reinstall it, or turn it off in Settings → Extensions.' + : 'This extension is turned on but does not have permission to scan attachments. Review it in Settings → Extensions.'} +

+ ) : !setup ? ( +

{loadError || 'Loading scanner setup…'}

+ ) : ( + <> +
+
+
Status
+
+
+
+
+
Scanner address
+
{setup.endpoint || 'None'}
+
+
+
Accounts it may scan
+
+ {approved.length ? approved.map((account) => account.name || account.email).join(', ') : 'None approved yet'} +
+
+
+
Sign-in kept
+
+ {setup.configured || setup.savedCredentialsLocked ? credentialLabel(setup) : 'Nothing saved'} +
+
+
+
+ + +
+
+ {test && } + {testError &&

{testError}

} +
+ + )} + + {setupOpen && } +
+ ); +} diff --git a/apps/desktop/src/components/security/RememberedLinkSites.tsx b/apps/desktop/src/components/security/RememberedLinkSites.tsx new file mode 100644 index 00000000..1dc27ad3 --- /dev/null +++ b/apps/desktop/src/components/security/RememberedLinkSites.tsx @@ -0,0 +1,88 @@ +import { ExternalLink } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; + +/** What the section knows: still asking main, a count, or that main could not read the list. */ +type SitesState = { kind: 'loading' } | { kind: 'count'; count: number } | { kind: 'unreadable' }; + +type SitesAnswer = { success: boolean; data?: { count: number }; error?: string } | undefined; + +function stateOf(answer: SitesAnswer): SitesState { + return answer?.success && typeof answer.data?.count === 'number' + ? { kind: 'count', count: answer.data.count } + : { kind: 'unreadable' }; +} + +function describe(state: SitesState): string { + if (state.kind === 'loading') return 'Checking…'; + if (state.kind === 'unreadable') return "The list of sites couldn't be read, so every link asks before it opens."; + if (state.count === 0) return 'None. Every link to another site asks before it opens in your browser.'; + return `${state.count.toLocaleString()} site${state.count === 1 ? '' : 's'} you chose “Don't ask again” for. Their links open in your browser without asking.`; +} + +/** + * Security → Trusted & blocked links: the sites the link warning was told not + * to ask about again, as a count, and a way to take that back. + * + * Main keeps the list (the external-link gate) and only ever answers how many + * there are: the hosts are where the user has been, and the renderer has no + * use for them. "Forget all" stays available when the list could not be read, + * because forgetting is also how a damaged list is cleared. + */ +export function RememberedLinkSites() { + const [state, setState] = useState({ kind: 'loading' }); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let live = true; + void (async () => { + let answer: SitesAnswer; + try { + answer = await window.electronAPI.security?.getRememberedLinkSites?.(); + } catch { + answer = undefined; + } + if (live) setState(stateOf(answer)); + })(); + return () => { live = false; }; + }, []); + + const forget = useCallback(async () => { + setBusy(true); + try { + setState(stateOf(await window.electronAPI.security?.forgetRememberedLinkSites?.())); + } catch { + setState({ kind: 'unreadable' }); + } finally { + setBusy(false); + } + }, []); + + const nothingToForget = state.kind === 'loading' || (state.kind === 'count' && state.count === 0); + + return ( +
+

+ Sites that open without asking +

+
+ +
+

{describe(state)}

+

+ Any other web link shows a warning that names the site before it opens, except the app's own + links (such as sarv.com). Links through a redirect or link-checking service, such as Safe Links, + always ask. Links to email addresses open without asking. +

+
+ +
+
+ ); +} diff --git a/apps/desktop/src/components/security/Security.tsx b/apps/desktop/src/components/security/Security.tsx index 3609227f..84b4cac7 100644 --- a/apps/desktop/src/components/security/Security.tsx +++ b/apps/desktop/src/components/security/Security.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useId, useMemo, useState } from 'react'; import { useEmailStore } from '../../store/email-store'; import { accountDisplayLabel } from '../../store/helpers'; +import type { AttachmentScannerSummary } from '../../utils/attachment-scan-failures'; import { LEVEL_COPY, type SecurityLevel } from '../../utils/email-security'; import { forgetImagesAllowed, @@ -21,11 +22,13 @@ import { useConfirm } from '../ConfirmDialog'; import { BlockedSendersPanel } from '../settings/BlockedSendersPanel'; import { Tooltip } from '../Tooltip'; +import { AttachmentScanningTab } from './AttachmentScanningTab'; import { BlocklistsTab } from './BlocklistsTab'; import { CredentialStorageStatus } from './CredentialStorageStatus'; +import { RememberedLinkSites } from './RememberedLinkSites'; import { TrustedSendersPanel } from './TrustedSendersPanel'; -type SecurityTab = 'overview' | 'links' | 'senders' | 'images' | 'identity' | 'blocklists' | 'spam'; +type SecurityTab = 'overview' | 'links' | 'senders' | 'images' | 'identity' | 'blocklists' | 'spam' | 'scanning'; const tabs: { id: SecurityTab; label: string }[] = [ { id: 'overview', label: 'Overview' }, @@ -35,8 +38,28 @@ const tabs: { id: SecurityTab; label: string }[] = [ { id: 'identity', label: 'Sender identity' }, { id: 'blocklists', label: 'Blocklists' }, { id: 'spam', label: 'Spam' }, + // Listed only while a scanner extension is turned on. + { id: 'scanning', label: 'Attachment scanning' }, ]; +/** + * The scanner extensions that are turned on, as main reports them. `null` + * until the first answer, so a tab asked for by name is not dropped before + * main has said whether it exists. + */ +function useEnabledScanners(): { scanners: AttachmentScannerSummary[] | null; reload: () => void } { + const [scanners, setScanners] = useState(null); + const reload = useCallback(() => { + const api = window.electronAPI?.antivirus; + if (!api?.listScanners) { setScanners([]); return; } + api.listScanners() + .then((r) => setScanners(r?.success && Array.isArray(r.data) ? r.data : [])) + .catch(() => setScanners([])); + }, []); + useEffect(() => { reload(); }, [reload]); + return { scanners, reload }; +} + const LEVEL_ICON: Record = { verified: ShieldCheck, authenticated: Shield, unverified: ShieldQuestion, caution: ShieldAlert, danger: ShieldX, }; @@ -56,6 +79,13 @@ const LEVEL_ORDER: SecurityLevel[] = ['verified', 'authenticated', 'unverified', */ export function Security({ initialTab }: { initialTab?: SecurityTab } = {}) { const [activeTab, setActiveTab] = useState(initialTab ?? 'overview'); + const { scanners, reload: reloadScanners } = useEnabledScanners(); + const hasScanner = (scanners?.length ?? 0) > 0; + const visibleTabs = hasScanner ? tabs : tabs.filter((tab) => tab.id !== 'scanning'); + // A scanner turned off elsewhere takes its tab with it. + useEffect(() => { + if (scanners !== null && !hasScanner && activeTab === 'scanning') setActiveTab('overview'); + }, [scanners, hasScanner, activeTab]); return (
@@ -68,7 +98,7 @@ export function Security({ initialTab }: { initialTab?: SecurityTab } = {}) {
); @@ -103,13 +134,13 @@ export function Security({ initialTab }: { initialTab?: SecurityTab } = {}) { const PROTECTIONS: Array<{ title: string; detail: string }> = [ { title: 'Isolated message rendering', detail: 'Every email body renders inside a sandboxed frame. Scripts, stylesheets, fonts and imports are stripped before it loads.' }, - { title: 'Links open in your browser', detail: 'Clicking a link never navigates inside the app — it hands the address to your system browser with referrer and opener stripped.' }, + { title: 'Links open in your browser', detail: 'Clicking a link never navigates inside the app — it hands the address to your system browser with referrer and opener stripped. Before a link opens a site the app did not put there, a warning names the site, unless you chose “Don’t ask again” for it (Trusted & blocked links).' }, { title: 'Sender authentication', detail: 'SPF, DKIM and DMARC verdicts are read from the receiving server’s Authentication-Results header and shown on the shield beside each sender.' }, { title: 'Impersonation checks', detail: 'A display name that names one domain while the message came from another, and links whose text says one domain while pointing to another, are flagged.' }, { title: 'Brand verification (BIMI)', detail: 'A sender domain’s published logo is shown only on mail that passed DMARC, and the blue verified tick only when its Verified Mark Certificate chains to a pinned Mark Verifying Authority for that exact logo and domain. Details per domain under Sender identity.' }, { title: 'Sender reputation', detail: 'As a message arrives, its sending server’s address and its sender domains are checked against spam blocklists through this computer’s DNS, and a listing adds to the spam score before the message is filed. The domains a message links to can be checked too, and how recently its domains were registered. All of it under Security → Blocklists.' }, { title: 'Spam filter', detail: 'Every arriving message is scored from its headers before the AI sees it — failed authentication, a spoofed sender name, a forged reply, missing or mis-dated headers, bulk mail with no unsubscribe, your mail server’s own spam verdict, and senders you have reported. A message over the line is filed as spam with its reasons shown on the shield.' }, - { title: 'Verified TLS to your mail server', detail: 'Certificates are verified and TLS 1.2 is the floor, unless you explicitly allow a self-signed server per account.' }, + { title: 'Verified TLS to your mail server', detail: 'Certificates are always verified and TLS 1.2 is the floor. A server with its own certificate is trusted only for the exact certificate you approve when you add or reconnect the account (Sarv Inbox never asks on its own), and every other certificate is refused.' }, ]; function HeaderBackfillStatus() { @@ -313,6 +344,7 @@ function LinksTab() { onRevoke={revoke} revokeLabel="Unblock" /> +
); } diff --git a/apps/desktop/src/components/settings/AccountRemovalNotes.tsx b/apps/desktop/src/components/settings/AccountRemovalNotes.tsx index 200b27cc..c2a32b5b 100644 --- a/apps/desktop/src/components/settings/AccountRemovalNotes.tsx +++ b/apps/desktop/src/components/settings/AccountRemovalNotes.tsx @@ -8,15 +8,20 @@ * user is pointed at the pages where they can do it themselves. A password * account keeps nothing but the password. */ +import { + GOOGLE_PERMISSIONS_URL, + MICROSOFT_PERSONAL_CONSENT_URL, + MICROSOFT_WORK_APPS_URL, +} from '@sarvinbox/core/app-links'; import { X } from 'lucide-react'; import type { ReactNode } from 'react'; import { openExternalLink } from '../../utils/open-external'; import { Tooltip } from '../Tooltip'; -export const MICROSOFT_PERSONAL_CONSENT_URL = 'https://account.live.com/consent/Manage'; -export const MICROSOFT_WORK_APPS_URL = 'https://myapps.microsoft.com'; -export const GOOGLE_PERMISSIONS_URL = 'https://myaccount.google.com/permissions'; +// The addresses live on the app-links list, which main's external-link gate +// opens without a warning; re-exported under the names this module always had. +export { GOOGLE_PERMISSIONS_URL, MICROSOFT_PERSONAL_CONSENT_URL, MICROSOFT_WORK_APPS_URL }; const linkClass = 'font-medium text-primary underline underline-offset-2 hover:text-primary/80'; diff --git a/apps/desktop/src/components/settings/AccountsTab.tsx b/apps/desktop/src/components/settings/AccountsTab.tsx index cda57ed5..b60c9265 100644 --- a/apps/desktop/src/components/settings/AccountsTab.tsx +++ b/apps/desktop/src/components/settings/AccountsTab.tsx @@ -6,7 +6,8 @@ import { useOAuthSignIn } from '../../hooks/useOAuthSignIn'; import { useReauthSessions } from '../../hooks/useReauthSessions'; import { aiProvidersUsingSignIn } from '../../services/ai-service'; import { useEmailStore } from '../../store/email-store'; -import { accountHost, isAccountEmailDuplicated, effectiveSmtpConfig } from '../../store/helpers'; +import { accountHost, connectAccountId, isAccountEmailDuplicated, effectiveSmtpConfig } from '../../store/helpers'; +import { allowCertificateReview } from '../../utils/certificate-review'; import { findReauthSession } from '../../utils/reauth-sessions'; import { savedAccountSecurity } from '../../utils/saved-account-security'; import { AddAccountModal } from '../AddAccountModal'; @@ -14,6 +15,7 @@ import { ConnectionSecuritySelect } from '../ConnectionSecuritySelect'; import { GmailPrivacyNotice, openInboxPrivacyPolicy } from '../GmailPrivacyNotice'; import { SmtpConfigForm } from '../SmtpConfigForm'; import { Tooltip } from '../Tooltip'; +import { TrustedCertificate } from '../TrustedCertificate'; import { VaultPasswordField } from '../VaultPasswordField'; import { RemovalAccessNote, RevokeFailedNotice, revokeFailureWorthNoticing } from './AccountRemovalNotes'; @@ -96,6 +98,10 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco setImapError(''); setImapLoading(true); try { + // The user asked to reconnect: this connect may ask (in main) about an + // untrusted certificate — armed for the account id the connect runs as. + const host = imapForm.host.trim() || imapConfig.host; + allowCertificateReview(connectAccountId(accounts, imapConfig.username, host), 'imap'); await connect({ ...imapConfig, ...(imapForm.host.trim() ? { host: imapForm.host.trim() } : {}), @@ -235,6 +241,11 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco setImapLoading(true); setImapSuccess(false); try { + // The user asked to reconnect: this connect may ask (in main) about an + // untrusted certificate — armed for the account id the connect runs as. + if (savedAccount.authMethod !== 'oauth2') { + allowCertificateReview(connectAccountId(accounts, savedAccount.username, imapForm.host.trim() || savedAccount.host), 'imap'); + } await connect({ ...savedAccount, ...(imapForm.host.trim() ? { host: imapForm.host.trim() } : {}), @@ -714,6 +725,10 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco + {/* The certificate approved for this server, if any (never for OAuth). */} + {!dIsOAuth && detailAccount && ( + + )} {detailReauth && (
@@ -824,6 +839,9 @@ export function AccountsTab({ settings, updateSetting, openAddAccount, onAddAcco
)} + {dSmtpConfigured && !showSmtpForm && !dIsOAuth && detailAccount && dSmtpConfig && ( + + )} {/* Gate on detailIsActive (stable), NOT detailLive — otherwise a transient connection flicker (connected→reconnecting) would unmount the form mid-entry and wipe what you typed. */} diff --git a/apps/desktop/src/components/settings/EncryptionTab.tsx b/apps/desktop/src/components/settings/EncryptionTab.tsx index 905a2ca8..fcc8509b 100644 --- a/apps/desktop/src/components/settings/EncryptionTab.tsx +++ b/apps/desktop/src/components/settings/EncryptionTab.tsx @@ -1,3 +1,4 @@ +import { PGP_FAILURE_MESSAGE, type PgpFlowCode } from '@sarvinbox/core/pgp-failure'; import { KeyRound, Loader2 } from 'lucide-react'; import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'; @@ -8,6 +9,8 @@ import { credentialStoreProtection } from '../../utils/secure-storage-status'; import { useConfirm } from '../ConfirmDialog'; import { + IMPORT_PASSPHRASE_HINT, + UNLOCK_HINT, keyAddressChoices, keySourceLabel, keyWarnings, @@ -48,6 +51,11 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { const [notice, setNotice] = useState(null); const [busy, setBusy] = useState(false); const [keyAction, setKeyAction] = useState(null); + // Set when main answered `passphrase-required`: the create form then asks + // for one even if the keychain check said none was needed, and the import + // form says a passphrase is needed. + const [createNeedsPassphrase, setCreateNeedsPassphrase] = useState(false); + const [importNeedsPassphrase, setImportNeedsPassphrase] = useState(false); const reload = useCallback(async () => { try { @@ -57,10 +65,11 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { setContactKeys(contacts.success ? contacts.data : []); const failed = [own, contacts].find((result) => !result.success); if (failed && !failed.success) setNotice({ text: failed.error, tone: 'error' }); - } catch (error) { + } catch { + // A rejected bridge: the one OpenPGP sentence, never the rejection's text. setOwnKeys([]); setContactKeys([]); - setNotice({ text: errorText(error), tone: 'error' }); + setNotice({ text: PGP_FAILURE_MESSAGE, tone: 'error' }); } }, [pgp]); @@ -68,22 +77,32 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { void reload(); }, [reload]); - /** Run one bridge call: busy while it runs, its error or success on the notice line, then refresh. */ - const run = async (task: () => Promise>, success: (data: T) => string | null): Promise => { + /** + * Run one bridge call: busy while it runs, its error or success on the + * notice line, then refresh. A failure shows main's sentence as it came + * (PGP_FAILURE_MESSAGE for every OpenPGP cause), and a prompt code goes to + * `onPrompt` so the caller can open what it asks for. + */ + const run = async ( + task: () => Promise>, + success: (data: T) => string | null, + onPrompt?: (code: PgpFlowCode) => void, + ): Promise => { setBusy(true); setNotice(null); try { const result = await task(); if (!result.success) { setNotice({ text: result.error, tone: 'error' }); + if (result.code) onPrompt?.(result.code); return false; } const text = success(result.data); if (text) setNotice({ text, tone: 'success' }); await Promise.all([reload(), retryStorageStatus()]); return true; - } catch (error) { - setNotice({ text: errorText(error), tone: 'error' }); + } catch { + setNotice({ text: PGP_FAILURE_MESSAGE, tone: 'error' }); return false; } finally { setBusy(false); @@ -108,10 +127,14 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { }; const submitKeyAction = async ({ fingerprint, kind }: NonNullable, passphrase: string) => { + // A failed unlock keeps its form open for another try; a backup of a key + // that is locked this session swaps to the unlock form. const done = kind === 'unlock' ? await run(() => pgp.unlock(fingerprint, passphrase), () => 'Key unlocked until you quit') - : await run(() => pgp.exportOwnKey(fingerprint, passphrase), savedText('Backup')); + : await run(() => pgp.exportOwnKey(fingerprint, passphrase), savedText('Backup'), (code) => { + if (code === 'locked') setKeyAction({ fingerprint, kind: 'unlock' }); + }); if (done) setKeyAction(null); }; @@ -181,8 +204,10 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { {keyAction?.fingerprint === key.fingerprint && ( submitKeyAction(keyAction, passphrase)} @@ -198,9 +223,17 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) {
run(() => pgp.generateKey(input), (key) => `Created a key for ${key.email}`)} + onCreate={(input) => + run( + () => pgp.generateKey(input), + (key) => `Created a key for ${key.email}`, + (code) => { + if (code === 'passphrase-required') setCreateNeedsPassphrase(true); + }, + ) + } />
@@ -208,9 +241,19 @@ export function EncryptionTab({ settings, updateSetting }: EncryptionTabProps) { - run(() => pgp.importOwnKey(armored, passphrase), (keys) => `Imported ${keys.length === 1 ? 'your key' : `${keys.length} keys`}`) + run( + () => pgp.importOwnKey(armored, passphrase), + (keys) => { + setImportNeedsPassphrase(false); + return `Imported ${keys.length === 1 ? 'your key' : `${keys.length} keys`}`; + }, + (code) => { + if (code === 'passphrase-required') setImportNeedsPassphrase(true); + }, + ) } /> @@ -380,6 +423,8 @@ function CreateKeyForm(props: { function ArmoredImportForm(props: { what: string; withPassphrase?: boolean; + /** Fixed guidance under the passphrase field, shown once main asked for a passphrase. */ + passphraseHint?: string; busy: boolean; onImport: (armored: string, passphrase?: string) => Promise; }) { @@ -420,6 +465,11 @@ function ArmoredImportForm(props: { {props.withPassphrase && ( setPassphrase(event.target.value)} className={INPUT} /> )} + {props.withPassphrase && props.passphraseHint && ( +

+ {props.passphraseHint} +

+ )} diff --git a/apps/desktop/src/components/settings/FiltersTab.tsx b/apps/desktop/src/components/settings/FiltersTab.tsx index 06e3db93..6f135d24 100644 --- a/apps/desktop/src/components/settings/FiltersTab.tsx +++ b/apps/desktop/src/components/settings/FiltersTab.tsx @@ -5,6 +5,7 @@ import { useState, useEffect } from 'react'; import { useEmailStore } from '../../store/email-store'; import { consumePendingFilterDraft } from '../../utils/filter-draft-bridge'; import { useConfirm } from '../ConfirmDialog'; +import { NewLabelDialog } from '../NewLabelDialog'; import { Tooltip } from '../Tooltip'; import { BlockedSendersPanel } from './BlockedSendersPanel'; @@ -18,7 +19,13 @@ const OPERATOR_LABELS: Record = { const ACTION_LABELS: Record = { markRead: 'Mark as read', star: 'Star', archive: 'Archive', delete: 'Delete (move to Trash)', moveToSpam: 'Move to Spam', moveToFolder: 'Move to folder', applyLabel: 'Apply label', + skipAI: 'Skip AI checks', }; +/** The actions offered in the "Then" rows. "Skip AI checks" is its own tickbox. */ +/** The "Apply label" dropdown's entry that opens the New label dialog; never saved. */ +const NEW_LABEL_OPTION = '__new_label__'; + +const ROW_ACTION_TYPES = (Object.keys(ACTION_LABELS) as FilterActionType[]).filter(t => t !== 'skipAI'); const emptyCondition = (): FilterCondition => ({ field: 'from', operator: 'contains', value: '' }); const emptyAction = (): FilterAction => ({ type: 'markRead' }); @@ -31,12 +38,23 @@ interface DraftRule { actions: FilterAction[]; stopProcessing: boolean; applyToExisting: boolean; + /** Keep the background AI away from matching mail (a `skipAI` action when saved). */ + skipAI: boolean; } const emptyDraft = (): DraftRule => ({ name: '', matchType: 'all', conditions: [emptyCondition()], actions: [emptyAction()], stopProcessing: false, applyToExisting: false, + // On by default for every new filter: mail the user set a filter for is + // mail they have decided about, and the AI leaves it alone. + skipAI: true, }); +/** The actions a draft saves: its rows, plus `skipAI` when ticked. */ +const draftActions = (draft: Pick): FilterAction[] => [ + ...draft.actions.filter(a => a.type !== 'skipAI'), + ...(draft.skipAI ? [{ type: 'skipAI' as const }] : []), +]; + const summarize = (rule: FilterRule): string => { const conds = rule.conditions .map(c => `${FIELD_LABELS[c.field]} ${OPERATOR_LABELS[c.operator]} "${c.value}"`) @@ -53,6 +71,8 @@ export function FiltersTab() { const [rules, setRules] = useState([]); const [loading, setLoading] = useState(false); const [draft, setDraft] = useState(null); + /** The action row whose "Apply label" is creating a label, or null. */ + const [newLabelFor, setNewLabelFor] = useState(null); const [saving, setSaving] = useState(false); const [dragIndex, setDragIndex] = useState(null); const [notice, setNotice] = useState(null); @@ -84,6 +104,7 @@ export function FiltersTab() { name: seed.name, matchType: seed.matchType, conditions: seed.conditions.length ? seed.conditions : [emptyCondition()], + ...(seed.actions ? { actions: seed.actions } : {}), }); }, []); @@ -111,7 +132,8 @@ export function FiltersTab() { const saveDraft = async () => { if (!draft) return; const cleanConditions = draft.conditions.filter(c => c.value.trim()); - if (!draft.name.trim() || cleanConditions.length === 0 || draft.actions.length === 0) return; + const actions = draftActions(draft); + if (!draft.name.trim() || cleanConditions.length === 0 || actions.length === 0) return; setSaving(true); const wantApply = draft.applyToExisting; try { @@ -119,7 +141,7 @@ export function FiltersTab() { name: draft.name.trim(), matchType: draft.matchType, conditions: cleanConditions, - actions: draft.actions, + actions, stopProcessing: draft.stopProcessing, }; const res = draft.id @@ -167,9 +189,11 @@ export function FiltersTab() { name: rule.name, matchType: rule.matchType, conditions: rule.conditions.length ? rule.conditions : [emptyCondition()], - actions: rule.actions.length ? rule.actions : [emptyAction()], + // A filter that only skips the AI opens with no action rows. + actions: rule.actions.filter(a => a.type !== 'skipAI'), stopProcessing: rule.stopProcessing, applyToExisting: false, + skipAI: rule.actions.some(a => a.type === 'skipAI'), }); }; @@ -200,6 +224,12 @@ export function FiltersTab() { return (
{confirmDialog} + {newLabelFor !== null && ( + // The new label is picked for the row that asked for it, so the user + // does not have to leave the filter to make one and come back. + setNewLabelFor(null)} + onCreated={(name) => patchAction(newLabelFor, { value: name })} /> + )} {/* Sub-tabs: Filters | Blocked (nested inside the one Settings tab) */}
{([['filters', 'Filters'], ['blocked', 'Blocked']] as const).map(([id, label]) => ( @@ -322,7 +352,7 @@ export function FiltersTab() {
{a.type === 'moveToFolder' && ( patchAction(i, { value: e.target.value })} + ) : ( - No labels yet — create one in Settings → Labels. + ) )} +
@@ -382,7 +432,7 @@ export function FiltersTab() {