15 KiB
Modularity and security refactoring plan
Goal
Improve the maintainability and auditability of ep-mail without changing its product behavior or weakening the existing Electron/renderer security boundary. Refactor incrementally, keeping each step testable and reversible.
Current assessment
desktop/main.cjscombines Electron lifecycle, IPC registration, account persistence, IMAP/SMTP work, background sync, outbox processing, DAV, and attachment workflows.- Renderer code is loaded as classic scripts with shared global state and implicit load-order dependencies.
- Root web assets are copied into
www/for Capacitor. Treat root assets as source andwww/as generated output; do not hand-edit generated copies. - Electron currently enables context isolation and sandboxing, and disables Node integration. Keep these controls in place.
- Existing tests focus mainly on OpenPGP and attachments; IPC, storage, and mail workflow boundaries need more coverage.
- The web content is sanitized and remote images are approval-gated. Preserve and add regression coverage for these protections.
Target boundaries
desktop/
main.cjs # Electron startup and lifecycle
ipc/ # Request validation and handler registration
mail/ # Account, IMAP, SMTP, sync, outbox, message mapping
dav/ # DAV services and iCalendar/vCard codecs
security/ # Secure storage and shared boundary validation
pgp/ # OpenPGP services (existing focused modules)
renderer/
app/ mail/ accounts/ dav/ pgp/ shared/
This is a gradual destination, not a requirement to move everything at once. IPC modules should validate and translate renderer requests, then call services. Services should not depend on Electron IPC or window objects. Pass dependencies such as storage, network clients, clocks, and notification callbacks explicitly where practical.
Steps and acceptance criteria
1. Baseline and guardrails — in progress
- Record the current test baseline.
- Confirm the current root/
www/web assets match. - Document source-versus-generated asset ownership and add a regression check for drift.
- Preserve unrelated working-tree changes.
Acceptance: npm test passes, the asset check passes, and no runtime behavior changes in this step.
Result: all acceptance checks passed; the suite now contains 38 passing tests.
2. Extract pure helpers — complete
- Extract account/input normalization and public account mapping (
desktop/mail-model.cjs). - Extract folder validation and message filtering (
desktop/mail-model.cjs). - Extract parsed-message display projection (
desktop/mail-content.cjs). - Extract DAV iCalendar/vCard serialization (
desktop/dav-codecs.cjs). - Add isolated unit tests for these helpers.
Acceptance: helper tests do not need Electron or live mail/DAV servers; existing tests remain green.
Result: helper modules are tested independently; npm test passes 47 tests. Runtime-facing call sites in desktop/main.cjs now import the extracted functions.
3. Isolate secure persistence — complete
- Move account, DAV, and OpenPGP encrypted JSON file I/O behind
desktop/secure-json-store.cjs. - Move legacy account-record migration behind
desktop/account-store.cjs. - Keep OS-backed encryption checks, migration behavior, atomic writes, and Linux
basic_textrejection intact. - Add tests using injected storage/encryption adapters.
Acceptance: services no longer manage secure-store paths directly, and persistence behavior is covered by tests.
Result: persistence adapters and legacy migration are covered independently; npm test passes 54 tests.
4. Split mail services — complete
- Extract SMTP submission and Sent-copy handling (
desktop/mail/send-service.cjs). - Extract IMAP special-folder discovery and folder-path resolution (
desktop/mail/folders.cjs). - Extract mailbox page/search reads (
desktop/mail/read-service.cjs). - Extract message actions (
desktop/mail/action-service.cjs). - Extract mailbox reconciliation and rule application (
desktop/mail/sync-service.cjs). - Extract background scheduling, per-account backoff, and request coalescing (
desktop/mail/sync-coordinator.cjs). - Extract IMAP IDLE watcher lifecycle (
desktop/mail/idle-watcher-manager.cjs). - Extract snooze reminder processing (
desktop/mail/snooze-reminder-service.cjs). - Extract offline outbox processing and optimistic cache updates (
desktop/mail/outbox-service.cjs). - Extract attachment saving and preview workflows (
desktop/mail/attachment-service.cjs).
Acceptance: mail services can be tested with fake clients/stores; generation invalidation, connection cleanup, and no-plaintext PGP queueing remain covered.
Result: mail protocol, outbox, attachment, scheduling, IDLE, and snooze workflows are isolated behind injected dependencies; npm test passes 92 tests.
5. Harden and modularize IPC — complete
- Verify the IPC sender is the expected top-level application document (
desktop/security/ipc-sender.cjs). - Restrict navigation to the exact app document URL; reject arbitrary
file:navigation. - Validate channel names, argument counts/types, and nested payload complexity (
desktop/security/ipc-arguments.cjs). - Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (
desktop/dav/remote-reference.cjs). - Validate channel-specific fields and limits; reject renderer-supplied raw SMTP payload fields.
- Group OpenPGP handlers and source fetching in
desktop/ipc/pgp.cjs, retaining the shared IPC boundary. - Group mail/account handlers in
desktop/ipc/mail.cjs. - Group DAV handlers in
desktop/ipc/dav.cjs; keeppreload.cjsas the narrow renderer API. - Retain public account and DAV config projections rather than exposing secret-bearing store records.
Acceptance: IPC tests cover malformed inputs and rejected senders; privileged behavior remains in trusted code.
Result: OpenPGP, mail/account, and DAV handler groups now register through the same sender and payload validation wrapper. Registration/schema tests cover all feature modules.
6. Modularize renderer incrementally — in progress
- Introduce a namespaced shared renderer-state module with transitional classic-script accessors (
renderer-state.js). - Extract mail HTML sanitization and remote-image approval checks into a dedicated renderer API (
mail-content-security.js). - Add an explicit mail feature API and migrate the account manager to it (
renderer-mail-api.js,account-ui.js). - Migrate snooze UI state/sync access to the mail feature API (
snooze-ui.js). - Migrate attachment UI state, selectors, and message hooks to the mail feature API (
attachments.js). - Migrate OpenPGP mail UI reader/compose hooks to the mail feature API (
pgp-mail-ui.js). - Migrate shortcut mail-state access and preferences extension to feature APIs (
shortcuts.js,productivity.js). - Migrate Calendar/Contacts navigation and DAV UI to the productivity feature API (
app.js,dav-ui.js). - Migrate OpenPGP key UI to the mail feature API for active-account access (
pgp-ui.js). - Make the core app shell consume the namespaced renderer state instead of compatibility aliases.
- Expose core shell behavior through an explicit renderer API and migrate mail UI selectors, notifications, rendering, and compose hooks to that API (
app.js,mail-ui.js). - Hide the account-manager script in a local module scope and route selectors, escaping, notifications, and DAV navigation through explicit feature APIs (
account-ui.js,dav-ui.js). - Route the snooze action's message-label hook through the productivity feature API (
snooze-ui.js,productivity.js). - Encapsulate productivity implementation state and helpers in a local module scope, preserving the explicit productivity feature API (
productivity.js). - Encapsulate DAV helpers in a local module scope while preserving
window.epMailFeatures.dav(dav-ui.js). - Encapsulate core renderer implementation behind
window.epMailShell(app.js). - Migrate additional mail-related consumers to unique local aliases to avoid classic-script lexical redeclarations.
- Add a combined-script parse test to prevent duplicate top-level lexical declarations from stopping later UI scripts.
- Migrate remaining mail-related consumers and remove transitional global dependencies.
- Replace hidden globals and script-order dependencies with imports or passed dependencies.
- Keep root web assets canonical and generated copies out of hand-edited workflows.
- Preserve CSP, HTML sanitization, and per-message remote-image approval behavior.
Acceptance: both desktop and Android builds include the intended modules and existing user-visible flows still work.
7. Security regression coverage and review
- Add coverage for HTML sanitization, remote images, DAV URL/object handling, send downgrade decisions, and OpenPGP trust/replacement paths.
- Review pending items from
SECURITY_REVIEW.md, including key-store/IPC/signature UI review, dependency audit, and Android encryption limitations.
Acceptance: security-sensitive behaviors have regression tests, and unresolved risks are documented rather than silently treated as fixed.
Execution notes
- Do not combine architectural refactoring with feature work or broad dependency upgrades.
- Run
npm testafter each extraction; run desktop/Android build checks at relevant integration points. - Keep changes small and inspect generated output before replacing it. The Android preparation script recreates
www/, so edits there are not authoritative.
Build version coordination
package.jsonis the canonical application version; keep bothpackage-lock.jsonversion fields synchronized with it.- Electron Builder and the desktop Actions artifact name derive from
package.json. - Android
versionNamederives from the same package version. Its currentversionCodemapping ismajor * 10000 + minor * 100 + patch; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions. scripts/build-all.ps1uses the package version for APK naming. Before a release, bump once withnpm run bump:build, verify the lockfile and computed Android version code, and build every target without another bump.- Latest version check:
package.jsonand both lockfile version fields are0.4.27; Android derivesversionName 0.4.27andversionCode 427. The user confirms the previous artifact works; this bump is for the next build.
Progress log
- Initial baseline:
npm testpassed 37 tests on 2026-10-16. - Initial inspection found matching root/
www/web assets. package.jsonhas a pre-existing user change allowing theesbuild@0.28.2install script; it is being preserved.- Step 1 added a generated-web-asset parity test; the full suite passed 38 tests.
- Step 2 extracted pure account, folder, mail-content, filtering, and DAV codec helpers; the full suite passed 47 tests.
- Step 3 extracted encrypted JSON persistence and account migration; the full suite passed 54 tests.
- Step 4 extracted injected SMTP, IMAP folder/read/action, outbox, attachment, mailbox-sync, and scheduling services; the full suite passed 86 tests.
- Step 4 completed with extracted IDLE and snooze services; the full suite passed 92 tests.
- Step 5 added a trusted top-level sender check to all 54 registered IPC handlers; sender boundary tests pass.
- Step 5 also aligned
will-navigatewith the same exact-document policy;npm testpasses 96 tests. - Step 5 added request schemas for all 54 registered channels, plus depth/collection/string bounds. Base64 attachment payloads remain uncapped to preserve the existing no-total-size-cap behavior.
- Step 5 also binds DAV updates/deletes to the configured account, same-origin collection, a server-listed resource, and a current ETag; DAV IDs are constrained against line injection and path traversal.
- Step 5 moved OpenPGP handler registration and message-source fetching into a feature module and added registration/schema coverage.
- Step 5 moved DAV handler registration into a feature module and added registration/schema coverage; the full suite passes 110 tests.
- Step 5 grouped mail/account handlers in
desktop/ipc/mail.cjs; all 114 tests pass and the remaining app-version handler stays in the Electron shell. - Added a build-version consistency check; the initial verification was at package version
0.4.21/ Android build number421. - Step 5 grouped mail/account handlers and added a release-version consistency test; current package/lockfile/Android version alignment was checked and documented.
- Step 6 added
renderer-state.js, extracted the mail HTML security API, and introducedrenderer-mail-api.js;account-ui.jsnow uses that explicit API instead of several mail globals. Transitional aliases remain for other classic scripts. - Step 6 migrated snooze, attachment, OpenPGP mail/key, shortcut, productivity state/render, and DAV UI integrations to feature APIs; compatibility globals remain in the core shell and some cross-feature hooks. The core app now reads shared state through
renderer-state.js; the suite passes 123 tests. - Step 6 added an explicit
epMailShellinterface for mail UI selectors, notifications, views, and renderer wrappers.mail-ui.jsnow uses it rather than directly replacing core renderer functions; search resets use namespaced state, and preferences remain owned by the productivity feature. - Step 6 verification at version
0.4.22/ Android build number422: all 123 tests pass, including generatedwww/parity and combined classic-script parsing. - Step 6 at version
0.4.23moves account-manager dependencies onto feature APIs and publishes the DAV manager throughwindow.epMailFeatures.davinstead of a free global function. - Step 6 at version
0.4.24removes the snooze-to-productivity label action's implicit global call; account and snooze feature API checks are covered by the renderer tests. - Step 6 at version
0.4.25wraps productivity internals in a local scope; Calendar, Contacts, labels, and profile behavior remain published through the productivity feature API. - Step 6 at version
0.4.26wraps DAV UI internals in a local scope while preserving the public DAV feature API. - Step 6 at version
0.4.27scopes core renderer functions and state inapp.js; other scripts continue through the explicitepMailShellinterface. - The current IPC/DAV validation changes pass the full suite: 108 tests.
- While work continued,
package.jsonandpackage-lock.jsonreflected a version bump to0.4.6; those changes were preserved.