Compare commits
48
Commits
5059dde07b
...
V0.4.39
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36ccd2eaf0 | ||
|
|
ea825adcc1 | ||
|
|
1ef934045f | ||
|
|
82d2f677aa | ||
|
|
60d692f8b4 | ||
|
|
cdf1b2dd62 | ||
|
|
cfb6ddc2bb | ||
|
|
bc550cc929 | ||
|
|
7cd3e4a392 | ||
|
|
ef764183ec | ||
|
|
4fd962cdfd | ||
|
|
590ecc52aa | ||
|
|
cbb4720353 | ||
|
|
b9b2a6d031 | ||
|
|
4b252c774c | ||
|
|
0f2014213e | ||
|
|
9759c3579a | ||
|
|
928410b10e | ||
|
|
26d79fd836 | ||
|
|
e80f285e8c | ||
|
|
3013e489ed | ||
|
|
718ceb6efe | ||
|
|
1445d42563 | ||
|
|
f4683b6508 | ||
|
|
38340442f0 | ||
|
|
84a63441ef | ||
|
|
f19573a337 | ||
|
|
d14c1cfb07 | ||
|
|
c1961a4059 | ||
|
|
297fe77fc1 | ||
|
|
0737892766 | ||
|
|
52f7001b34 | ||
|
|
928e6dd62a | ||
|
|
88a8729f4f | ||
|
|
0b52949f23 | ||
|
|
da543d5059 | ||
|
|
e398bc4e1a | ||
|
|
e5391dbb62 | ||
|
|
115e29640e | ||
|
|
2a23f4d40e | ||
|
|
959658c400 | ||
|
|
2068e3f32b | ||
|
|
5cd8d545e9 | ||
|
|
acba5d641e | ||
|
|
f3e68b10bd | ||
|
|
04cd4117fe | ||
|
|
a9c52e7868 | ||
|
|
20d58feb9c |
@@ -1,3 +1,4 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
release/
|
release/
|
||||||
dist/
|
dist/
|
||||||
|
android/local.properties
|
||||||
|
|||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
# Architecture
|
||||||
|
|
||||||
|
This project has a layered architecture: a desktop Electron shell, a browser-rendered mail interface, platform-specific storage and sync adapters, and a separate Android Capacitor wrapper. The design keeps user state and credentials in the OS keyring, pushes IMAP/SMTP work into the main process, and exposes only a narrow IPC surface to the renderer.
|
||||||
|
|
||||||
|
## 1. Runtime layout
|
||||||
|
|
||||||
|
### Desktop shell
|
||||||
|
|
||||||
|
- `desktop/main.cjs` is the privileged process.
|
||||||
|
- It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling.
|
||||||
|
- It can show native dialogs, notifications, and system prompts. On Windows, its notification-area tray icon uses the packaged multi-resolution application icon and provides Open and Quit actions. Packaged startup repairs an existing per-user Start Menu shortcut to target the launched app and use its icon, keeping taskbar pins associated with the matching AppUserModelID.
|
||||||
|
- `desktop/preload.cjs` exposes the narrow platform API through `window.daybreakMail`. Renderer-to-renderer contracts are grouped under `window.epMailState`, `window.epMailShell`, and `window.epMailFeatures`.
|
||||||
|
|
||||||
|
### Renderer UI
|
||||||
|
|
||||||
|
The browser UI is rendered from canonical web assets in the repository root; `www/` is generated for Capacitor:
|
||||||
|
|
||||||
|
- `index.html` defines the classic-script bootstrap order. `renderer-state.js` exposes shared state as `window.epMailState` without legacy unnamespaced aliases.
|
||||||
|
- `app.js` publishes `window.epMailShell`; the mail, productivity, DAV, and PGP mail modules publish explicit APIs under `window.epMailFeatures`. PGP key management extends the productivity Preferences UI through that API.
|
||||||
|
- Renderer feature implementations are locally scoped. The ordered classic-script bootstrap remains a compatibility constraint for desktop and Capacitor, and is covered by bootstrap and combined-script tests.
|
||||||
|
- The renderer is intentionally thin: it requests actions and displays data, while mail-protocol and cryptographic network work stays in the main process. The reader makes direct HTTPS image requests only after explicit per-message approval.
|
||||||
|
|
||||||
|
### Android client
|
||||||
|
|
||||||
|
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
|
||||||
|
|
||||||
|
- The same browser UI runs inside the Android app.
|
||||||
|
- Native Android services handle background sync, notification behavior, and secure storage.
|
||||||
|
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
|
||||||
|
|
||||||
|
## 2. Core responsibilities
|
||||||
|
|
||||||
|
### Mail and account state
|
||||||
|
|
||||||
|
The main process owns the canonical account model and persists it in an encrypted store:
|
||||||
|
|
||||||
|
- `mail-account.enc` stores connected IMAP/SMTP accounts, settings, and desktop OAuth tokens; OAuth refresh tokens never enter the renderer API.
|
||||||
|
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
||||||
|
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
||||||
|
|
||||||
|
All three stores are wrapped with Electron `safeStorage` where available. Linux checks explicitly reject the insecure `basic_text` backend before credentials or keys are persisted.
|
||||||
|
|
||||||
|
### Mail sync pipeline
|
||||||
|
|
||||||
|
The desktop app follows a background sync model:
|
||||||
|
|
||||||
|
1. The renderer asks the main process for a folder sync or inbox refresh.
|
||||||
|
2. The main process opens an IMAP connection and fetches only the requested subset or page.
|
||||||
|
3. Sync results are written back into the account state and sent to the renderer via IPC (`mail:sync-update`).
|
||||||
|
4. Periodic background sync and IDLE watchers reduce polling and keep new-mail notifications timely.
|
||||||
|
|
||||||
|
A generation counter invalidates stale sync jobs when accounts are edited or removed, and concurrent syncs are prevented to avoid overlapping IMAP traffic.
|
||||||
|
|
||||||
|
### Message send path
|
||||||
|
|
||||||
|
The send flow is also centralized in the main process:
|
||||||
|
|
||||||
|
- the renderer calls the desktop `mail:send` IPC or the Android `EpMail.send` plugin with message fields and selected attachment bytes
|
||||||
|
- the native send path resolves the account, checks sender settings, builds multipart MIME, and on desktop applies OpenPGP encryption/signing to the body and attachments before sending
|
||||||
|
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable; local draft attachments are persisted with draft content
|
||||||
|
|
||||||
|
The renderer sends file bytes rather than local paths. OpenPGP messages are encrypted before offline queueing so the outbox contains ciphertext instead of plaintext message or attachment content.
|
||||||
|
|
||||||
|
## 3. Security boundary
|
||||||
|
|
||||||
|
The current architecture takes a strict trust split:
|
||||||
|
|
||||||
|
- renderer: UI, user interaction, local conveniences
|
||||||
|
- main process: network access, cryptographic operations, permission prompts, OS secure storage
|
||||||
|
|
||||||
|
This boundary is important for encryption and safety checks:
|
||||||
|
|
||||||
|
- OpenPGP key selection and trust updates are confirmed in the main process.
|
||||||
|
- Replacement-key operations are also confirmed in the main process; tests assert cancellation does not update the contact key.
|
||||||
|
- Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication.
|
||||||
|
- Send-time downgrade checks happen in the main process rather than only in UI logic.
|
||||||
|
- External links open only after a native confirmation dialog.
|
||||||
|
- Incoming HTML is sanitized in the renderer before insertion. HTTPS image URLs are kept in inert data attributes; only a per-message user action assigns image sources, and reopening the message resets that approval. HTTP images are rejected to preserve Android's cleartext-traffic protection. The CSP allows HTTPS images; scripts, frames, forms, and remote connections remain blocked.
|
||||||
|
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
|
||||||
|
|
||||||
|
## 4. OpenPGP subsystem
|
||||||
|
|
||||||
|
The OpenPGP implementation is split into focused modules:
|
||||||
|
|
||||||
|
- `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings.
|
||||||
|
- `desktop/pgp-mail.cjs` handles message detection, decryption, verification, encryption, and signature checks.
|
||||||
|
- `desktop/pgp-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
|
||||||
|
- `desktop/ipc/pgp.cjs` bridges those services into the Electron IPC API; `desktop/main.cjs` wires the services and registrars together.
|
||||||
|
|
||||||
|
This keeps the cryptographic logic separate from the UI and gives the app a single place to enforce trust rules, passphrase checks, and recipient validation.
|
||||||
|
|
||||||
|
Key-server enablement is persisted in encrypted OpenPGP settings; all servers default to disabled, including custom servers already configured by older versions. The main process enforces enabled status for both lookup and publication. A lookup queries all enabled servers, reports partial failures, and merges duplicate fingerprints while retaining source names. The user chooses one enabled server as the publication target. Custom HTTPS endpoints require a native confirmation when added; redirects and oversized responses are rejected. Returned keys are validated and remain untrusted until the user verifies their fingerprints out of band. Publishing sends only public key material and requires a native confirmation naming the destination for each publication.
|
||||||
|
|
||||||
|
## 5. Data flow patterns
|
||||||
|
|
||||||
|
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
|
||||||
|
- Mail content is fetched by the native mail service and passed to the renderer as plain text, bounded HTML alternatives, links, and attachment metadata. HTML is allowlist-sanitized before display; HTTPS image requests remain inert until explicitly enabled for the current message view.
|
||||||
|
- Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed.
|
||||||
|
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
|
||||||
|
|
||||||
|
## 6. Release and packaging model
|
||||||
|
|
||||||
|
The project packages multiple platforms from the same codebase:
|
||||||
|
|
||||||
|
- `npm run dist:win` for Windows installer/portable builds
|
||||||
|
- `npm run dist:linux` for Linux AppImage and Debian builds
|
||||||
|
- Android builds via Capacitor (`npm run android:apk`)
|
||||||
|
|
||||||
|
The app version is managed through package metadata and the Electron build config in `package.json`.
|
||||||
|
|
||||||
|
## 7. Key architectural principles
|
||||||
|
|
||||||
|
- Keep privileged operations in the main process.
|
||||||
|
- Keep security rules in trusted code rather than the UI.
|
||||||
|
- Store secrets in OS-backed secure storage whenever the platform supports it.
|
||||||
|
- Share the same account and sync model between desktop and Android where possible.
|
||||||
|
- Treat mail encryption and secure key handling as first-class product features, not optional extras.
|
||||||
|
|
||||||
|
This architecture is intentionally built for a mail client that must handle privacy-sensitive data, background sync, and cross-platform parity without exposing the network or crypto stack to the renderer.
|
||||||
+20
-4
@@ -1,6 +1,6 @@
|
|||||||
# Encryption plan: OpenPGP mail encryption for ep-mail
|
# Encryption plan: OpenPGP mail encryption for ep-mail
|
||||||
|
|
||||||
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support and an independent security review are still open; see [TODO.md](./TODO.md).
|
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
||||||
|
|
||||||
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
|
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
|
||||||
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
|
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
|
||||||
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
|
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
|
||||||
- Out of scope for v1: Autocrypt headers, key servers, Web Key Directory.
|
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
|
||||||
|
|
||||||
## 2. Key handling
|
## 2. Key handling
|
||||||
|
|
||||||
@@ -25,11 +25,11 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
|
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
|
||||||
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
|
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
|
||||||
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
||||||
- Deleting or exporting a private key requires the passphrase.
|
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
|
||||||
|
|
||||||
**Public keys**
|
**Public keys**
|
||||||
- Per-account contact keyring: address, fingerprint, trust level, source.
|
- Per-account contact keyring: address, fingerprint, trust level, source.
|
||||||
- Sources: file import, attached to received mail, own key attached to outgoing mail.
|
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
|
||||||
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
|
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
|
||||||
|
|
||||||
## 3. User experience
|
## 3. User experience
|
||||||
@@ -72,6 +72,8 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
|
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
|
||||||
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
|
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
|
||||||
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
|
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
|
||||||
|
- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP.
|
||||||
|
- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply.
|
||||||
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
|
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
|
||||||
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
|
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
|
||||||
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
|
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
|
||||||
@@ -83,3 +85,17 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- User confusion about trust; keep states simple: unknown, trusted, verified.
|
- User confusion about trust; keep states simple: unknown, trusted, verified.
|
||||||
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
|
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
|
||||||
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
|
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
|
||||||
|
|
||||||
|
## 9. Public key servers (desktop)
|
||||||
|
|
||||||
|
The desktop Settings → Encryption keys view can search and publish through:
|
||||||
|
|
||||||
|
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
|
||||||
|
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
|
||||||
|
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
|
||||||
|
|
||||||
|
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
|
||||||
|
|
||||||
|
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented.
|
||||||
|
|
||||||
|
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
|
||||||
|
|||||||
@@ -4,10 +4,18 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E
|
|||||||
|
|
||||||
## Desktop app
|
## Desktop app
|
||||||
|
|
||||||
The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser; the app never renders remote message HTML. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
|
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
|
||||||
|
|
||||||
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
||||||
|
|
||||||
|
### Google and Microsoft OAuth2
|
||||||
|
|
||||||
|
Desktop account setup supports Google and Microsoft OAuth2 when provider client configuration is supplied to the Electron process. Set `EP_MAIL_GOOGLE_OAUTH_CLIENT_ID` (and `EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET` if issued for the desktop client) and/or `EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID`; `EP_MAIL_MICROSOFT_OAUTH_TENANT_ID` is optional and defaults to `common`. Register the corresponding native/desktop public client with a loopback redirect URI. Microsoft app registrations must allow public-client authorization and delegated IMAP/SMTP permissions. Google's full Gmail mail scope is restricted; production use may require app verification, and unverified projects may need the account added as a test user. OAuth sign-in opens the system browser, uses PKCE, and stores refresh/access tokens only in the encrypted account store. Android continues to use its existing password-based account setup.
|
||||||
|
|
||||||
|
On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build.
|
||||||
|
|
||||||
|
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||||
|
|
||||||
## Android app
|
## Android app
|
||||||
|
|
||||||
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
||||||
@@ -31,4 +39,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
|
|||||||
|
|
||||||
## Current scope
|
## Current scope
|
||||||
|
|
||||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; you can import contacts' public keys, read encrypted or signed OpenPGP mail, and encrypt or sign outgoing messages from the compose window (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md); Android is not supported yet). Run the tests with `npm test`.
|
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`.
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
# 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.cjs` combines 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 and `www/` 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.
|
||||||
|
|
||||||
|
## Current boundaries and target direction
|
||||||
|
|
||||||
|
```text
|
||||||
|
desktop/
|
||||||
|
main.cjs, preload.cjs # Electron startup, lifecycle, narrow bridge
|
||||||
|
ipc/ # Mail, DAV, and OpenPGP handler registrars
|
||||||
|
mail/ # IMAP/SMTP, sync, outbox, snooze, attachments
|
||||||
|
dav/ # DAV remote-reference validation
|
||||||
|
security/ # IPC sender and request validation
|
||||||
|
pgp-*.cjs # OpenPGP key, mail, and key-server services
|
||||||
|
account-store.cjs # Account-record migration
|
||||||
|
secure-json-store.cjs # Encrypted JSON persistence
|
||||||
|
mail-*.cjs, dav-codecs.cjs # Mail models, content projection, DAV codecs
|
||||||
|
index.html # Shared desktop/browser/Capacitor entry point
|
||||||
|
app.js, *-ui.js, *.css # Shared renderer sources (canonical)
|
||||||
|
renderer-state.js # Shared namespaced renderer state
|
||||||
|
renderer-mail-api.js # Shared renderer feature API factory
|
||||||
|
mail-content-security.js # HTML sanitizer and remote-image policy
|
||||||
|
platform-bridge.js # Generated platform bridge
|
||||||
|
www/ # Generated Capacitor web assets; do not edit
|
||||||
|
scripts/prepare-android-web.cjs # Copies root web assets into www/
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep the shared renderer outside `desktop/`: Electron, the browser build, and Android all use these web sources. The root files are canonical and `www/` is generated. Desktop service boundaries are reflected by the existing `desktop/ipc/`, `desktop/mail/`, `desktop/dav/`, and `desktop/security/` directories.
|
||||||
|
|
||||||
|
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. A future move of shared UI sources into a dedicated `renderer/` directory is optional, not required for this plan; it would need coordinated updates to `index.html` script/style URLs, Electron Builder file inclusion, Android copying, service-worker precache paths, and asset-parity tests.
|
||||||
|
|
||||||
|
## Steps and acceptance criteria
|
||||||
|
|
||||||
|
### 1. Baseline and guardrails — complete
|
||||||
|
|
||||||
|
- [x] Record the current test baseline.
|
||||||
|
- [x] Confirm the current root/`www/` web assets match.
|
||||||
|
- [x] Document source-versus-generated asset ownership and add a regression check for drift.
|
||||||
|
- [x] 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
|
||||||
|
|
||||||
|
- [x] Extract account/input normalization and public account mapping (`desktop/mail-model.cjs`).
|
||||||
|
- [x] Extract folder validation and message filtering (`desktop/mail-model.cjs`).
|
||||||
|
- [x] Extract parsed-message display projection (`desktop/mail-content.cjs`).
|
||||||
|
- [x] Extract DAV iCalendar/vCard serialization (`desktop/dav-codecs.cjs`).
|
||||||
|
- [x] 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
|
||||||
|
|
||||||
|
- [x] Move account, DAV, and OpenPGP encrypted JSON file I/O behind `desktop/secure-json-store.cjs`.
|
||||||
|
- [x] Move legacy account-record migration behind `desktop/account-store.cjs`.
|
||||||
|
- [x] Keep OS-backed encryption checks, migration behavior, atomic writes, and Linux `basic_text` rejection intact.
|
||||||
|
- [x] 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
|
||||||
|
|
||||||
|
- [x] Extract SMTP submission and Sent-copy handling (`desktop/mail/send-service.cjs`).
|
||||||
|
- [x] Extract IMAP special-folder discovery and folder-path resolution (`desktop/mail/folders.cjs`).
|
||||||
|
- [x] Extract mailbox page/search reads (`desktop/mail/read-service.cjs`).
|
||||||
|
- [x] Extract message actions (`desktop/mail/action-service.cjs`).
|
||||||
|
- [x] Extract mailbox reconciliation and rule application (`desktop/mail/sync-service.cjs`).
|
||||||
|
- [x] Extract background scheduling, per-account backoff, and request coalescing (`desktop/mail/sync-coordinator.cjs`).
|
||||||
|
- [x] Extract IMAP IDLE watcher lifecycle (`desktop/mail/idle-watcher-manager.cjs`).
|
||||||
|
- [x] Extract snooze reminder processing (`desktop/mail/snooze-reminder-service.cjs`).
|
||||||
|
- [x] Extract offline outbox processing and optimistic cache updates (`desktop/mail/outbox-service.cjs`).
|
||||||
|
- [x] 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
|
||||||
|
|
||||||
|
- [x] Verify the IPC sender is the expected top-level application document (`desktop/security/ipc-sender.cjs`).
|
||||||
|
- [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation.
|
||||||
|
- [x] Validate channel names, argument counts/types, and nested payload complexity (`desktop/security/ipc-arguments.cjs`).
|
||||||
|
- [x] Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (`desktop/dav/remote-reference.cjs`).
|
||||||
|
- [x] Validate channel-specific fields and limits; reject renderer-supplied raw SMTP payload fields.
|
||||||
|
- [x] Group OpenPGP handlers and source fetching in `desktop/ipc/pgp.cjs`, retaining the shared IPC boundary.
|
||||||
|
- [x] Group mail/account handlers in `desktop/ipc/mail.cjs`.
|
||||||
|
- [x] Group DAV handlers in `desktop/ipc/dav.cjs`; keep `preload.cjs` as the narrow renderer API.
|
||||||
|
- [x] 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 — complete
|
||||||
|
|
||||||
|
- [x] Introduce a namespaced shared renderer-state module with transitional classic-script accessors (`renderer-state.js`).
|
||||||
|
- [x] Extract mail HTML sanitization and remote-image approval checks into a dedicated renderer API (`mail-content-security.js`).
|
||||||
|
- [x] Add an explicit mail feature API and migrate the account manager to it (`renderer-mail-api.js`, `account-ui.js`).
|
||||||
|
- [x] Migrate snooze UI state/sync access to the mail feature API (`snooze-ui.js`).
|
||||||
|
- [x] Migrate attachment UI state, selectors, and message hooks to the mail feature API (`attachments.js`).
|
||||||
|
- [x] Migrate OpenPGP mail UI reader/compose hooks to the mail feature API (`pgp-mail-ui.js`).
|
||||||
|
- [x] Migrate shortcut mail-state access and preferences extension to feature APIs (`shortcuts.js`, `productivity.js`).
|
||||||
|
- [x] Migrate Calendar/Contacts navigation and DAV UI to the productivity feature API (`app.js`, `dav-ui.js`).
|
||||||
|
- [x] Migrate OpenPGP key UI to the mail feature API for active-account access (`pgp-ui.js`).
|
||||||
|
- [x] Make the core app shell consume the namespaced renderer state instead of compatibility aliases.
|
||||||
|
- [x] 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`).
|
||||||
|
- [x] 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`).
|
||||||
|
- [x] Route the snooze action's message-label hook through the productivity feature API (`snooze-ui.js`, `productivity.js`).
|
||||||
|
- [x] Encapsulate productivity implementation state and helpers in a local module scope, preserving the explicit productivity feature API (`productivity.js`).
|
||||||
|
- [x] Encapsulate DAV helpers in a local module scope while preserving `window.epMailFeatures.dav` (`dav-ui.js`).
|
||||||
|
- [x] Encapsulate core renderer implementation behind `window.epMailShell` (`app.js`).
|
||||||
|
- [x] Encapsulate mail UI implementation behind `window.epMailFeatures.mail` (`mail-ui.js`).
|
||||||
|
- [x] Encapsulate OpenPGP key-management UI helpers locally; it contributes to Preferences through the productivity API (`pgp-ui.js`).
|
||||||
|
- [x] Encapsulate OpenPGP mail helpers behind `window.epMailFeatures.pgp` and use the mail API's HTML escaping helper (`pgp-mail-ui.js`).
|
||||||
|
- [x] Encapsulate attachment UI helpers locally; its navigation and renderer hooks continue through the mail API (`attachments.js`).
|
||||||
|
- [x] Encapsulate snooze UI helpers locally while preserving explicit mail/productivity API usage (`snooze-ui.js`).
|
||||||
|
- [x] Encapsulate keyboard shortcut settings and handlers locally; integrations remain through the mail/productivity feature APIs (`shortcuts.js`).
|
||||||
|
- [x] Remove transitional renderer-state globals after all consumers migrated to the namespaced state API (`renderer-state.js`).
|
||||||
|
- [x] Register the mail API factory under the shared feature namespace instead of a standalone renderer global (`renderer-mail-api.js`, `mail-ui.js`).
|
||||||
|
- [x] Register content security helpers under the shared feature namespace instead of a standalone global (`mail-content-security.js`, `app.js`).
|
||||||
|
- [x] Migrate additional mail-related consumers to unique local aliases to avoid classic-script lexical redeclarations.
|
||||||
|
- [x] Add a combined-script parse test to prevent duplicate top-level lexical declarations from stopping later UI scripts.
|
||||||
|
- [x] Migrate remaining mail-related consumers and remove legacy/transitional global dependencies.
|
||||||
|
- [x] Make cross-feature dependencies explicit through namespaced APIs and test the required classic-script load order.
|
||||||
|
- [x] Keep root web assets canonical and verify generated `www/` parity.
|
||||||
|
- [x] Preserve CSP, HTML sanitization, and per-message remote-image approval behavior with regression coverage.
|
||||||
|
|
||||||
|
**Acceptance:** both desktop and Android builds include the intended modules and existing user-visible flows still work.
|
||||||
|
|
||||||
|
**Result:** renderer features are locally scoped behind `epMailState`, `epMailShell`, and `epMailFeatures` APIs. The classic-script bootstrap remains intentionally ordered for desktop/Capacitor compatibility, with that order covered by tests. The user has confirmed successive built artifacts work.
|
||||||
|
|
||||||
|
**Deferred follow-up:** migrate the renderer from classic scripts to native ES modules; this is not required to complete the incremental modularization step above.
|
||||||
|
|
||||||
|
### 7. Security regression coverage and review — in progress
|
||||||
|
|
||||||
|
- [x] Cover HTML sanitization and remote-image validation/approval gating.
|
||||||
|
- [x] Cover DAV URL/object validation and current ETag binding.
|
||||||
|
- [ ] Add direct IPC-handler coverage for main-process plaintext-send downgrade confirmation (the confirmation behavior exists; its critical accept/cancel branch is not directly tested yet).
|
||||||
|
- [x] Cover native OpenPGP trust elevation and replacement-key confirmation, including cancellation behavior.
|
||||||
|
- [ ] Complete the human review and remaining items in `SECURITY_REVIEW.md` (dependency audit/version pinning and Android encryption limitations included).
|
||||||
|
|
||||||
|
**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 test` after 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.json` is the canonical application version; keep both `package-lock.json` version fields synchronized with it.
|
||||||
|
- Electron Builder and the desktop Actions artifact name derive from `package.json`.
|
||||||
|
- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions.
|
||||||
|
- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump.
|
||||||
|
- Latest version check: `package.json` and both lockfile version fields are `0.4.39`; Android derives `versionName 0.4.39` and `versionCode 439`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified.
|
||||||
|
|
||||||
|
## Progress log
|
||||||
|
|
||||||
|
- Initial baseline: `npm test` passed 37 tests on 2026-10-16.
|
||||||
|
- Initial inspection found matching root/`www/` web assets.
|
||||||
|
- `package.json` has a pre-existing user change allowing the `esbuild@0.28.2` install 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-navigate` with the same exact-document policy; `npm test` passes 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 number `421`.
|
||||||
|
- 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 introduced `renderer-mail-api.js`; `account-ui.js` now 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 `epMailShell` interface for mail UI selectors, notifications, views, and renderer wrappers. `mail-ui.js` now 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 number `422`: all 123 tests pass, including generated `www/` parity and combined classic-script parsing.
|
||||||
|
- Step 6 at version `0.4.23` moves account-manager dependencies onto feature APIs and publishes the DAV manager through `window.epMailFeatures.dav` instead of a free global function.
|
||||||
|
- Step 6 at version `0.4.24` removes 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.25` wraps 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.26` wraps DAV UI internals in a local scope while preserving the public DAV feature API.
|
||||||
|
- Step 6 at version `0.4.27` scopes core renderer functions and state in `app.js`; other scripts continue through the explicit `epMailShell` interface.
|
||||||
|
- Step 6 at version `0.4.28` scopes mail UI implementation details while retaining its explicit mail feature API.
|
||||||
|
- Step 6 at version `0.4.29` scopes OpenPGP key UI implementation helpers without changing its Preferences integration.
|
||||||
|
- Step 6 at version `0.4.30` scopes PGP mail helpers, preserving the `prepareSend` API and removing its dependency on the core shell's former global HTML escape helper.
|
||||||
|
- Step 6 at version `0.4.31` scopes attachment preview and search helpers while retaining their event-driven integrations.
|
||||||
|
- Step 6 at version `0.4.32` scopes snooze UI helpers; message labeling and mail-state access remain routed through feature APIs.
|
||||||
|
- Step 6 at version `0.4.33` scopes keyboard shortcut helpers and event handlers without changing their Preferences integration.
|
||||||
|
- Step 6 at version `0.4.34` removes legacy global renderer-state accessors; the state module now exposes only `window.epMailState` to the renderer.
|
||||||
|
- Step 6 at version `0.4.35` consolidates the mail API factory under `window.epMailFeatures.modules`, removing the separate `window.epMailUiModules` global.
|
||||||
|
- Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`.
|
||||||
|
- Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading.
|
||||||
|
- Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state.
|
||||||
|
- Desktop OAuth2 support for Google and Microsoft was added after the `0.4.38` artifact; `0.4.39` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints.
|
||||||
|
- Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open.
|
||||||
|
- Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up.
|
||||||
|
- The current IPC/DAV validation changes pass the full suite: 108 tests.
|
||||||
|
- While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved.
|
||||||
+30
-6
@@ -4,12 +4,14 @@ Date: 2026-10-08
|
|||||||
Version reviewed: 0.3.2 (working tree, uncommitted changes included)
|
Version reviewed: 0.3.2 (working tree, uncommitted changes included)
|
||||||
Type: automated review by an AI security-review agent. It is not a substitute for a human review.
|
Type: automated review by an AI security-review agent. It is not a substitute for a human review.
|
||||||
|
|
||||||
|
> **Current status (2026-10-16, ep-mail 0.4.38):** The entries below are a historical review record. The replacement-key and trust-elevation confirmations are implemented in the main process and now have IPC regression tests for cancel/confirm behavior. The send-time plaintext downgrade check is enforced in the main process. The user confirms the current built artifact works. A direct IPC test for the plaintext-send confirmation branch and an independent human review remain open; Android OpenPGP support is not implemented.
|
||||||
|
|
||||||
## Scope
|
## Scope
|
||||||
|
|
||||||
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
|
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
|
||||||
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
|
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
|
||||||
- `pgp:*` IPC handlers in `desktop/main.cjs` and `desktop/preload.cjs`
|
- `pgp:*` IPC handlers, now registered in `desktop/ipc/pgp.cjs`, plus the plaintext-send check in `desktop/ipc/mail.cjs`; the original review predates this IPC extraction.
|
||||||
- Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, the `pgpPrepareSend` hook in `mail-ui.js`
|
- Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, and the `window.epMailFeatures.pgp.prepareSend` feature hook used by `mail-ui.js`.
|
||||||
- Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)
|
- Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)
|
||||||
|
|
||||||
Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime.
|
Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime.
|
||||||
@@ -25,19 +27,41 @@ No critical or high severity issues were reported.
|
|||||||
|
|
||||||
## Fixes applied
|
## Fixes applied
|
||||||
|
|
||||||
1. **Send-time check:** `pgpPrepareSend` now checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt.
|
1. **Send-time check:** the renderer checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt. This renderer hook is now exposed as `window.epMailFeatures.pgp.prepareSend`.
|
||||||
2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations.
|
2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations.
|
||||||
|
|
||||||
## Verification
|
## Verification at the original review time
|
||||||
|
|
||||||
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
|
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
|
||||||
- `node --check` on the edited files.
|
- `node --check` on the edited files.
|
||||||
- The fixes were not exercised in the running app.
|
- The fixes were not exercised in the running app.
|
||||||
|
|
||||||
## Remaining work
|
## Remaining work recorded after the first review (2026-10-08)
|
||||||
|
|
||||||
- Human review of the key store, the IPC boundary and the signature UI.
|
- Human review of the key store, the IPC boundary and the signature UI.
|
||||||
- Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. The review suggested it, and only the trust confirmation was added.
|
- Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. This was still open at the time; see the later review pass below.
|
||||||
- Run `npm audit` and pin the OpenPGP.js version.
|
- Run `npm audit` and pin the OpenPGP.js version.
|
||||||
- Re-run the GnuPG interoperability tests after dependency updates.
|
- Re-run the GnuPG interoperability tests after dependency updates.
|
||||||
- Android has no encryption support yet, so it was not reviewed.
|
- Android has no encryption support yet, so it was not reviewed.
|
||||||
|
|
||||||
|
## Second review pass (2026-10-09)
|
||||||
|
|
||||||
|
Fresh review of the same scope after the first round of fixes. Tests: 20 passed, 0 failed. No code was changed in this pass.
|
||||||
|
|
||||||
|
| # | Severity | File | Issue | Confidence | Status |
|
||||||
|
|---|----------|------|-------|------------|--------|
|
||||||
|
| 3 | 🟡 MEDIUM | `desktop/pgp-keystore.cjs`, `desktop/main.cjs` | `pgp:add-contact` adds a key for an address that already has one without a main-process confirmation. At equal trust the newest key wins recipient selection, so an added key can take over outgoing encryption. The trust dialog does not cover replacement. | 9/10 | Fixed |
|
||||||
|
| 4 | 🟡 MEDIUM | `desktop/main.cjs`, `desktop/preload.cjs` | The send-time downgrade check exists only in the renderer. `mail:send` sends plaintext when `pgp` is omitted, so a compromised renderer can bypass the warning. | 9/10 | Fixed |
|
||||||
|
| 5 | 🟡 MEDIUM | `desktop/main.cjs` | `safeStorage` is used without checking the backend. On Linux the `basic_text` backend uses a hardcoded password, so a copied store would expose account credentials and mail data. PGP private keys stay protected by their own passphrases. | 8/10 | Fixed |
|
||||||
|
|
||||||
|
Applied fixes:
|
||||||
|
- #3: native confirmation showing both fingerprints when a key overlaps existing contacts, and the add-contact flow aborts if the replacement is not confirmed.
|
||||||
|
- #4: the main process checks recipient keys before allowing a plaintext send and shows a trusted confirmation dialog.
|
||||||
|
- #5: Linux now rejects the insecure `basic_text` safeStorage backend and asks the user to switch to a secure system keyring before storing mail or PGP secrets.
|
||||||
|
|
||||||
|
## Current follow-up
|
||||||
|
|
||||||
|
- Replacement-key and trust-elevation confirmation are enforced in `desktop/ipc/pgp.cjs`. `tests/pgp-ipc-registration.test.cjs` verifies both cancellation and confirmation paths for those changes.
|
||||||
|
- Main-process plaintext-send confirmation is implemented in `desktop/ipc/mail.cjs`; direct regression coverage for that dialog's accept/cancel branches remains open.
|
||||||
|
- Human cryptography/security review, dependency audit and OpenPGP.js version pinning remain outstanding. GnuPG interoperability tests are in the current test suite and should be rerun after dependency changes.
|
||||||
|
- Android has no OpenPGP implementation and is outside the reviewed desktop scope.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
|
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
|
||||||
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
|
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
|
||||||
|
- [x] Fix the ep-mail logo not appearing in the Windows taskbar.
|
||||||
- [x] Add Android support for the mail app.
|
- [x] Add Android support for the mail app.
|
||||||
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
|
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
|
||||||
- [x] Show the app version after **ep-mail** in the window title.
|
- [x] Show the app version after **ep-mail** in the window title.
|
||||||
@@ -11,7 +12,7 @@
|
|||||||
## Mail workflow
|
## Mail workflow
|
||||||
|
|
||||||
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
|
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
|
||||||
- [ ] Add Undo Send and scheduled sending.
|
- [ ] Add a configurable Undo Send delay and scheduled sending.
|
||||||
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
|
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
|
||||||
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
|
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
|
||||||
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
|
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
|
||||||
@@ -21,21 +22,23 @@
|
|||||||
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
||||||
- [x] Add per-account signatures, notification preferences, and sync settings.
|
- [x] Add per-account signatures, notification preferences, and sync settings.
|
||||||
- [x] Add the ability to create IMAP folders from the app.
|
- [x] Add the ability to create IMAP folders from the app.
|
||||||
- [ ] Block remote images by default and let users load them per message.
|
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
|
||||||
|
|
||||||
## Mail security
|
## Mail security
|
||||||
|
|
||||||
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
|
- [x] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME). Android support remains open; see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
|
||||||
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
||||||
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
||||||
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
||||||
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
||||||
- [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
|
- [ ] Phase 4 (Android): add Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
|
||||||
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
||||||
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
||||||
- [x] Phase 6: documentation and release.
|
- [x] Phase 6: documentation and release.
|
||||||
- [x] Manual interoperability check with Thunderbird.
|
- [x] Manual interoperability check with Thunderbird.
|
||||||
- [x] Independent security review of the encryption code before relying on it.
|
- [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
|
||||||
|
- [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android.
|
||||||
|
- [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation.
|
||||||
|
|
||||||
## Appearance and settings
|
## Appearance and settings
|
||||||
|
|
||||||
@@ -46,6 +49,7 @@
|
|||||||
|
|
||||||
## Account settings
|
## Account settings
|
||||||
|
|
||||||
|
- [x] Add desktop OAuth2 account setup for Google and Microsoft. Configure provider client IDs with the environment variables documented in `README.md`; Android remains password-based.
|
||||||
- [ ] Fix the mailbox space indicator; it is not working.
|
- [ ] Fix the mailbox space indicator; it is not working.
|
||||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
||||||
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
||||||
@@ -62,9 +66,12 @@
|
|||||||
- [x] Remove the display name initials from the bottom-left corner.
|
- [x] Remove the display name initials from the bottom-left corner.
|
||||||
- [x] Add the ability to delete draft mails.
|
- [x] Add the ability to delete draft mails.
|
||||||
- [x] Fix IMAP folder creation, which does not work.
|
- [x] Fix IMAP folder creation, which does not work.
|
||||||
- [ ] Give the sidebar (Inbox, Folders, etc.) more room so every item fits on screen: make the box scrollable with a slider, or remove or collapse less-used items.
|
- [ ] Improve sidebar usability so all folders fit or can be reached by scrolling; consider collapsing less-used sections.
|
||||||
- [ ] Make labels work and add the ability to create more labels.
|
- [ ] Make labels work reliably and support creating and managing additional labels.
|
||||||
- [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown.
|
- [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown.
|
||||||
- [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once.
|
- [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once.
|
||||||
- [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area.
|
- [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area.
|
||||||
- [ ] Add public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKPS), and user-defined custom key servers.
|
- [x] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification.
|
||||||
|
- [x] Add the ability to attach multiple files to outgoing mails on desktop and Android/Web, persist them in local drafts, and include them within desktop OpenPGP protection.
|
||||||
|
- [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
|
||||||
|
- [x] Add the ability to change the passphrase of an encryption key on desktop.
|
||||||
|
|||||||
+13
-8
@@ -1,26 +1,31 @@
|
|||||||
|
(() => {
|
||||||
|
const accountMailUi = window.epMailFeatures.mail;
|
||||||
|
const accountDavUi = window.epMailFeatures.dav;
|
||||||
|
|
||||||
async function openAccountManager(){
|
async function openAccountManager(){
|
||||||
const root=$('#modal-root');
|
const root=accountMailUi.select('#modal-root');
|
||||||
try{
|
try{
|
||||||
const data=await window.daybreakMail.listAccounts();
|
const data=await window.daybreakMail.listAccounts();
|
||||||
const accounts=data.accounts||[];
|
const accounts=data.accounts||[];
|
||||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
|
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${accountMailUi.escapeHtml(account.displayName||account.email)}</strong><small>${accountMailUi.escapeHtml(account.email)} · ${accountMailUi.escapeHtml(account.imapHost)} · ${accountMailUi.escapeHtml(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${accountMailUi.escapeHtml(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${accountMailUi.escapeHtml(account.id)}">Edit</button><button class="discard" data-remove-account="${accountMailUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
|
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
|
||||||
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()};
|
root.querySelector('#add-mail-account').onclick=()=>{close();accountMailUi.openMailAccount()};
|
||||||
root.onclick=async event=>{
|
root.onclick=async event=>{
|
||||||
const switchButton=event.target.closest('[data-switch-account]');
|
const switchButton=event.target.closest('[data-switch-account]');
|
||||||
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
|
if(switchButton){switchButton.disabled=true;try{accountMailUi.connectedAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));accountMailUi.select('#sidebar-title').textContent='Inbox';accountMailUi.select('#crumb-current').textContent='Inbox';accountMailUi.updateAccountCard(accountMailUi.connectedAccount);close();await accountMailUi.syncMailbox(true,{offset:0})}catch(error){accountMailUi.toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
|
||||||
const davButton=event.target.closest('[data-open-dav]');
|
const davButton=event.target.closest('[data-open-dav]');
|
||||||
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
|
if(davButton){close();accountDavUi.openManager(davButton.dataset.openDav);return}
|
||||||
const editButton=event.target.closest('[data-edit-account]');
|
const editButton=event.target.closest('[data-edit-account]');
|
||||||
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
||||||
};
|
};
|
||||||
}catch(error){toast(error.message||'Could not load mail accounts')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
||||||
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
||||||
|
})();
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import java.util.Date
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.Properties
|
import java.util.Properties
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
import android.util.Base64
|
||||||
|
import javax.activation.DataHandler
|
||||||
import javax.mail.Address
|
import javax.mail.Address
|
||||||
import javax.mail.Authenticator
|
import javax.mail.Authenticator
|
||||||
import javax.mail.Flags
|
import javax.mail.Flags
|
||||||
@@ -28,6 +30,7 @@ import javax.mail.PasswordAuthentication
|
|||||||
import javax.mail.Session
|
import javax.mail.Session
|
||||||
import javax.mail.Store
|
import javax.mail.Store
|
||||||
import javax.mail.Transport
|
import javax.mail.Transport
|
||||||
|
import javax.mail.util.ByteArrayDataSource
|
||||||
import javax.mail.UIDFolder
|
import javax.mail.UIDFolder
|
||||||
import javax.mail.internet.InternetAddress
|
import javax.mail.internet.InternetAddress
|
||||||
import javax.mail.internet.MimeBodyPart
|
import javax.mail.internet.MimeBodyPart
|
||||||
@@ -272,10 +275,37 @@ internal object AndroidMailService {
|
|||||||
message.subject = input.optString("subject", "(no subject)")
|
message.subject = input.optString("subject", "(no subject)")
|
||||||
val body = input.optString("text")
|
val body = input.optString("text")
|
||||||
val signature = account.optString("signature").take(5000)
|
val signature = account.optString("signature").take(5000)
|
||||||
message.setText(
|
val fullBody = if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature"
|
||||||
if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature",
|
val attachments = input.optJSONArray("attachments") ?: JSONArray()
|
||||||
"UTF-8"
|
if (attachments.length() == 0) {
|
||||||
)
|
message.setText(fullBody, "UTF-8")
|
||||||
|
} else {
|
||||||
|
val multipart = MimeMultipart("mixed")
|
||||||
|
multipart.addBodyPart(MimeBodyPart().apply { setText(fullBody, "UTF-8") })
|
||||||
|
for (index in 0 until attachments.length()) {
|
||||||
|
val file = attachments.optJSONObject(index)
|
||||||
|
?: throw IllegalArgumentException("An attachment could not be read.")
|
||||||
|
val encoded = file.optString("contentBase64")
|
||||||
|
require(encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
||||||
|
"The contents of an attachment are invalid."
|
||||||
|
}
|
||||||
|
val filename = file.optString("filename", "attachment")
|
||||||
|
.replace(Regex("[\\\\/\\r\\n\\u0000]"), "")
|
||||||
|
.take(255)
|
||||||
|
.ifBlank { "attachment" }
|
||||||
|
val contentType = file.optString("contentType", "application/octet-stream")
|
||||||
|
.lowercase(Locale.ROOT)
|
||||||
|
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) {
|
||||||
|
"The content type for $filename is invalid."
|
||||||
|
}
|
||||||
|
val part = MimeBodyPart()
|
||||||
|
part.dataHandler = DataHandler(ByteArrayDataSource(Base64.decode(encoded, Base64.DEFAULT), contentType))
|
||||||
|
part.fileName = MimeUtility.encodeText(filename, "UTF-8", null)
|
||||||
|
part.disposition = javax.mail.Part.ATTACHMENT
|
||||||
|
multipart.addBodyPart(part)
|
||||||
|
}
|
||||||
|
message.setContent(multipart)
|
||||||
|
}
|
||||||
message.sentDate = Date()
|
message.sentDate = Date()
|
||||||
message.saveChanges()
|
message.saveChanges()
|
||||||
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
||||||
@@ -561,9 +591,10 @@ internal object AndroidMailService {
|
|||||||
val senderEmail = sender?.address ?: ""
|
val senderEmail = sender?.address ?: ""
|
||||||
val subject = decode(message.subject).ifBlank { "(no subject)" }
|
val subject = decode(message.subject).ifBlank { "(no subject)" }
|
||||||
val body = ArrayList<String>()
|
val body = ArrayList<String>()
|
||||||
|
val htmlBodies = ArrayList<String>()
|
||||||
val attachments = JSONArray()
|
val attachments = JSONArray()
|
||||||
val links = linkedSetOf<String>()
|
val links = linkedSetOf<String>()
|
||||||
collectParts(message, body, attachments, links)
|
collectParts(message, body, htmlBodies, attachments, links)
|
||||||
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
||||||
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
||||||
val date = message.receivedDate ?: message.sentDate ?: Date()
|
val date = message.receivedDate ?: message.sentDate ?: Date()
|
||||||
@@ -598,6 +629,7 @@ internal object AndroidMailService {
|
|||||||
.put("archived", requestedFolder == "Archive")
|
.put("archived", requestedFolder == "Archive")
|
||||||
.put("deleted", requestedFolder == "Trash")
|
.put("deleted", requestedFolder == "Trash")
|
||||||
.put("sourceFolder", labelFolder)
|
.put("sourceFolder", labelFolder)
|
||||||
|
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
|
||||||
.put("body", JSONArray().apply {
|
.put("body", JSONArray().apply {
|
||||||
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
||||||
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
||||||
@@ -611,7 +643,13 @@ internal object AndroidMailService {
|
|||||||
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
||||||
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
||||||
|
|
||||||
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray, links: MutableSet<String>) {
|
private fun collectParts(
|
||||||
|
part: javax.mail.Part,
|
||||||
|
body: MutableList<String>,
|
||||||
|
htmlBodies: MutableList<String>,
|
||||||
|
attachments: JSONArray,
|
||||||
|
links: MutableSet<String>
|
||||||
|
) {
|
||||||
val filename = decode(part.fileName)
|
val filename = decode(part.fileName)
|
||||||
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
||||||
val name = filename.ifBlank { "attachment" }
|
val name = filename.ifBlank { "attachment" }
|
||||||
@@ -624,6 +662,7 @@ internal object AndroidMailService {
|
|||||||
is String -> if (part.isMimeType("text/plain")) {
|
is String -> if (part.isMimeType("text/plain")) {
|
||||||
body.add(content.replace("\r", "").trim())
|
body.add(content.replace("\r", "").trim())
|
||||||
} else if (part.isMimeType("text/html")) {
|
} else if (part.isMimeType("text/html")) {
|
||||||
|
if (htmlBodies.isEmpty()) htmlBodies.add(content.take(100000))
|
||||||
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
|
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
|
||||||
.findAll(content)
|
.findAll(content)
|
||||||
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&", "&") }
|
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&", "&") }
|
||||||
@@ -632,9 +671,9 @@ internal object AndroidMailService {
|
|||||||
if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
|
if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
|
||||||
}
|
}
|
||||||
is Multipart -> for (index in 0 until content.count) {
|
is Multipart -> for (index in 0 until content.count) {
|
||||||
collectParts(content.getBodyPart(index), body, attachments, links)
|
collectParts(content.getBodyPart(index), body, htmlBodies, attachments, links)
|
||||||
}
|
}
|
||||||
is javax.mail.BodyPart -> collectParts(content, body, attachments, links)
|
is javax.mail.BodyPart -> collectParts(content, body, htmlBodies, attachments, links)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -331,6 +331,7 @@ class EpMailPlugin : Plugin() {
|
|||||||
.put("cc", input.optString("cc").take(4000))
|
.put("cc", input.optString("cc").take(4000))
|
||||||
.put("subject", input.optString("subject").take(998))
|
.put("subject", input.optString("subject").take(998))
|
||||||
.put("text", input.optString("text").take(500000))
|
.put("text", input.optString("text").take(500000))
|
||||||
|
.put("attachments", input.optJSONArray("attachments") ?: JSONArray())
|
||||||
.put("updatedAt", System.currentTimeMillis())
|
.put("updatedAt", System.currentTimeMillis())
|
||||||
AndroidAccountVault.saveDraft(account.optString("id"), draft)
|
AndroidAccountVault.saveDraft(account.optString("id"), draft)
|
||||||
call.resolve(draft.toJSObject())
|
call.resolve(draft.toJSObject())
|
||||||
|
|||||||
@@ -1,17 +1,57 @@
|
|||||||
|
(() => {
|
||||||
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
|
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
|
||||||
const messages = [];
|
const state = window.epMailState;
|
||||||
const contacts=[];
|
|
||||||
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
|
|
||||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||||
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||||||
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
|
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
||||||
function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)}
|
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
|
||||||
|
function openMessage(id){
|
||||||
|
state.activeMessage=id;
|
||||||
|
const m=state.messages.find(x=>x.id===id);
|
||||||
|
if(!m)return;
|
||||||
|
m.unread=false;
|
||||||
|
renderList();
|
||||||
|
let safeHtml={html:'',remoteImageCount:0};
|
||||||
|
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
|
||||||
|
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
||||||
|
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
||||||
|
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
||||||
|
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
||||||
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
|
image.removeAttribute('data-remote-src');
|
||||||
|
if(url)image.src=url;
|
||||||
|
});
|
||||||
|
$('.remote-image-notice')?.remove();
|
||||||
|
});
|
||||||
|
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
|
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
|
$('#forward').onclick=()=>showCompose(m,true);
|
||||||
|
}
|
||||||
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
|
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
|
||||||
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
|
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(state.toastTimer);state.toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
|
||||||
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
|
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;state.messages.unshift({id:Date.now(),initials:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me'),email:(window.epMailFeatures.mail.connectedAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
|
||||||
function switchView(view){activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';}
|
function switchView(view){state.activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';if(view==='calendar')window.epMailFeatures.productivity.renderCalendar();if(view==='contacts')window.epMailFeatures.productivity.renderContacts();}
|
||||||
function renderCalendar(){}
|
$$('.folder').forEach(b=>b.onclick=()=>{state.activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=state.activeFolder;$('#crumb-current').textContent=state.activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{state.query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';state.query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=state.messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>state.selectedIds.has(m.id));visible.forEach(m=>all?state.selectedIds.delete(m.id):state.selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.archived=true);state.selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.deleted=true);state.selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(state.activeMessage);
|
||||||
function showEvent(){}
|
|
||||||
function renderContacts(){}
|
window.epMailShell = Object.freeze({
|
||||||
function showContact(){}
|
state,
|
||||||
$$('.folder').forEach(b=>b.onclick=()=>{activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);if(b.dataset.view==='calendar')renderCalendar();if(b.dataset.view==='contacts')renderContacts()});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>selectedIds.has(m.id));visible.forEach(m=>all?selectedIds.delete(m.id):selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.archived=true);selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.deleted=true);selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(activeMessage);
|
select: $,
|
||||||
|
selectAll: $$,
|
||||||
|
escapeHtml: esc,
|
||||||
|
toast,
|
||||||
|
switchView,
|
||||||
|
applyTheme,
|
||||||
|
baseRenderList: renderList,
|
||||||
|
get renderList() { return renderList; },
|
||||||
|
get openMessage() { return openMessage; },
|
||||||
|
get showCompose() { return showCompose; },
|
||||||
|
emptyReader,
|
||||||
|
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
||||||
|
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
||||||
|
wrapShowCompose(decorator) { showCompose = decorator(showCompose); }
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
+24
-21
@@ -1,4 +1,9 @@
|
|||||||
|
(() => {
|
||||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||||
|
const attachmentMailUi = window.epMailFeatures.mail;
|
||||||
|
const selectAttachmentUi = attachmentMailUi.select;
|
||||||
|
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
||||||
|
const toastAttachmentUi = attachmentMailUi.toast;
|
||||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
let attachmentItems = [];
|
let attachmentItems = [];
|
||||||
|
|
||||||
@@ -45,20 +50,18 @@ async function previewAttachment(target, details) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function downloadAttachment(details) {
|
function downloadAttachment(details) {
|
||||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
|
||||||
window.daybreakMail.saveAttachment(details)
|
window.daybreakMail.saveAttachment(details)
|
||||||
.then(result => { if (result.saved) toast('Attachment saved'); })
|
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
|
||||||
.catch(error => toast(error.message || 'Could not save attachment'));
|
.catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add a Preview button to each attachment in the reader.
|
// Add a Preview button to each attachment in the reader.
|
||||||
if (typeof openMessage === 'function') {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
const baseOpenMessage = openMessage;
|
|
||||||
openMessage = function (id) {
|
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid) return;
|
||||||
$$('#reader-pane .attachment').forEach(row => {
|
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
||||||
const download = row.querySelector('.download');
|
const download = row.querySelector('.download');
|
||||||
if (!download || row.querySelector('.preview-attachment')) return;
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
@@ -73,12 +76,11 @@ if (typeof openMessage === 'function') {
|
|||||||
panel = document.createElement('div');
|
panel = document.createElement('div');
|
||||||
panel.className = 'attachment-preview';
|
panel.className = 'attachment-preview';
|
||||||
row.after(panel);
|
row.after(panel);
|
||||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || attachmentMailUi.state.activeFolder, filename: download.dataset.filename });
|
||||||
});
|
});
|
||||||
download.before(button);
|
download.before(button);
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
}
|
|
||||||
|
|
||||||
async function collectAttachments() {
|
async function collectAttachments() {
|
||||||
const items = [];
|
const items = [];
|
||||||
@@ -103,16 +105,16 @@ async function collectAttachments() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openAttachmentsView() {
|
async function openAttachmentsView() {
|
||||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
||||||
const root = $('#modal-root');
|
const root = selectAttachmentUi('#modal-root');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('.modal-close').onclick = close;
|
root.querySelector('.modal-close').onclick = close;
|
||||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
const list = $('#attachment-list');
|
const list = selectAttachmentUi('#attachment-list');
|
||||||
const render = () => {
|
const render = () => {
|
||||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
||||||
const type = $('#attachment-type').value;
|
const type = selectAttachmentUi('#attachment-type').value;
|
||||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
@@ -146,16 +148,17 @@ async function openAttachmentsView() {
|
|||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
$('#attachment-search').oninput = render;
|
selectAttachmentUi('#attachment-search').oninput = render;
|
||||||
$('#attachment-type').onchange = render;
|
selectAttachmentUi('#attachment-type').onchange = render;
|
||||||
try {
|
try {
|
||||||
attachmentItems = await collectAttachments();
|
attachmentItems = await collectAttachments();
|
||||||
if ($('#attachment-list')) render();
|
if (selectAttachmentUi('#attachment-list')) render();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
});
|
});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -1,38 +1,48 @@
|
|||||||
|
(() => {
|
||||||
|
const davProductivityUi = window.epMailFeatures.productivity;
|
||||||
|
const selectDavUi = davProductivityUi.select;
|
||||||
|
|
||||||
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
|
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
|
||||||
async function syncDav(type, uploadLocal=false){
|
async function syncDav(type, uploadLocal=false){
|
||||||
try{
|
try{
|
||||||
const localOnly=type==='caldav'?savedEvents.filter(item=>!item._dav):savedContacts.filter(item=>!item._dav);
|
const localOnly=type==='caldav'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.filter(item=>!item._dav);
|
||||||
const result=await window.daybreakMail.davSync(type);
|
const result=await window.daybreakMail.davSync(type);
|
||||||
if(type==='caldav'){
|
if(type==='caldav'){
|
||||||
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){toast(`Could not upload “${event.title}”: ${error.message}`)}}
|
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){davProductivityUi.toast(`Could not upload “${event.title}”: ${error.message}`)}}
|
||||||
savedEvents=[...localOnly,...result.items];
|
davProductivityUi.events=[...localOnly,...result.items];
|
||||||
productWrite(productKeys.events,savedEvents);renderCalendar();toast(`Synced ${result.items.length} calendar events`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.toast(`Synced ${result.items.length} calendar events`);
|
||||||
}else{
|
}else{
|
||||||
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){toast(`Could not upload “${contact.name}”: ${error.message}`)}}
|
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){davProductivityUi.toast(`Could not upload “${contact.name}”: ${error.message}`)}}
|
||||||
savedContacts=[...localOnly,...result.items];
|
davProductivityUi.contacts=[...localOnly,...result.items];
|
||||||
productWrite(productKeys.contacts,savedContacts);renderContacts();toast(`Synced ${result.items.length} contacts`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
||||||
}
|
}
|
||||||
}catch(error){toast(error.message||`Could not sync ${davTypeName(type)}`)}
|
}catch(error){davProductivityUi.toast(error.message||`Could not sync ${davTypeName(type)}`)}
|
||||||
}
|
}
|
||||||
async function openDavManager(type){
|
async function openDavManager(type){
|
||||||
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
||||||
try{
|
try{
|
||||||
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
|
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
|
||||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.username)}</strong><small>${esc(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>esc(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${esc(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${esc(account.id)}">Remove</button></div></div>`).join('');
|
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${davProductivityUi.escapeHtml(account.username)}</strong><small>${davProductivityUi.escapeHtml(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>davProductivityUi.escapeHtml(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${davProductivityUi.escapeHtml(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${davProductivityUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
|
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
|
||||||
root.onclick=async event=>{
|
root.onclick=async event=>{
|
||||||
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){toast(error.message)}return}
|
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){davProductivityUi.toast(error.message)}return}
|
||||||
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){savedEvents=savedEvents.filter(item=>!item._dav);productWrite(productKeys.events,savedEvents);renderCalendar()}else{savedContacts=savedContacts.filter(item=>!item._dav);productWrite(productKeys.contacts,savedContacts);renderContacts()}await openDavManager(type)}catch(error){toast(error.message)} }
|
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){davProductivityUi.events=davProductivityUi.events.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar()}else{davProductivityUi.contacts=davProductivityUi.contacts.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts()}await openDavManager(type)}catch(error){davProductivityUi.toast(error.message)} }
|
||||||
};
|
};
|
||||||
}catch(error){toast(error.message||`Could not load ${label} servers`)}
|
}catch(error){davProductivityUi.toast(error.message||`Could not load ${label} servers`)}
|
||||||
}
|
}
|
||||||
function showDavConnect(type){
|
function showDavConnect(type){
|
||||||
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test & connect</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test & connect</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
|
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
|
||||||
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
|
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();davProductivityUi.toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
|
||||||
root.querySelector('#dav-server-url').focus();
|
root.querySelector('#dav-server-url').focus();
|
||||||
}
|
}
|
||||||
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
|
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
|
||||||
|
|
||||||
|
window.epMailFeatures.dav = Object.freeze({
|
||||||
|
openManager: openDavManager,
|
||||||
|
sync: syncDav
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
const { randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
|
function createAccountStore(secureStore, { createId = randomUUID } = {}) {
|
||||||
|
return {
|
||||||
|
async load() {
|
||||||
|
try {
|
||||||
|
const stored = await secureStore.load();
|
||||||
|
if (Array.isArray(stored.accounts)) return stored;
|
||||||
|
if (stored.email) {
|
||||||
|
const account = { ...stored, id: stored.id || createId() };
|
||||||
|
const migrated = { accounts: [account], activeId: account.id };
|
||||||
|
await secureStore.save(migrated);
|
||||||
|
return migrated;
|
||||||
|
}
|
||||||
|
return { accounts: [], activeId: null };
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
save(store) {
|
||||||
|
return secureStore.save(store);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createAccountStore };
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
const { randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
|
function escapeIcal(value = '') {
|
||||||
|
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeVcard(value = '') {
|
||||||
|
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeDavUid(value, createId) {
|
||||||
|
const uid = String(value || createId());
|
||||||
|
if (!uid || uid.length > 255 || /[\\/\\?#\u0000-\u001f\u007f]/.test(uid)) {
|
||||||
|
throw new Error('The DAV item identifier is invalid.');
|
||||||
|
}
|
||||||
|
return uid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCalendarData(event, { createId = randomUUID, now = () => new Date() } = {}) {
|
||||||
|
const uid = safeDavUid(event._dav?.uid, createId);
|
||||||
|
const stamp = now().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
||||||
|
const start = event.time
|
||||||
|
? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
|
||||||
|
: event.date.replace(/-/g, '');
|
||||||
|
const endDate = event.time
|
||||||
|
? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000)
|
||||||
|
.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
|
||||||
|
: null;
|
||||||
|
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n`}SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeVcard(contact, { createId = randomUUID } = {}) {
|
||||||
|
const name = String(contact.name || '').trim().split(/\s+/);
|
||||||
|
const first = name.shift() || '';
|
||||||
|
const last = name.join(' ');
|
||||||
|
const uid = safeDavUid(contact._dav?.uid, createId);
|
||||||
|
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${uid}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { escapeIcal, escapeVcard, makeCalendarData, makeVcard };
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
function asSafeDavUrl(value, baseUrl, serverOrigin) {
|
||||||
|
if (typeof value !== 'string' || !value.trim()) return null;
|
||||||
|
try {
|
||||||
|
const url = new URL(value, baseUrl);
|
||||||
|
if (url.origin !== serverOrigin || url.username || url.password || url.search || url.hash) return null;
|
||||||
|
return url;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertDavObjectReference({ config, remote, collections, objects }) {
|
||||||
|
if (!config || typeof config.id !== 'string' || typeof config.serverUrl !== 'string') {
|
||||||
|
throw new Error('The DAV account reference is invalid.');
|
||||||
|
}
|
||||||
|
if (!remote || typeof remote !== 'object' || Array.isArray(remote) || remote.accountId !== config.id) {
|
||||||
|
throw new Error('This DAV item does not belong to the selected account.');
|
||||||
|
}
|
||||||
|
if (!Array.isArray(collections) || !Array.isArray(objects)) {
|
||||||
|
throw new Error('The DAV collection could not be verified.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let serverUrl;
|
||||||
|
try {
|
||||||
|
serverUrl = new URL(config.serverUrl);
|
||||||
|
} catch {
|
||||||
|
throw new Error('The DAV server address is invalid.');
|
||||||
|
}
|
||||||
|
if (!['https:', 'http:'].includes(serverUrl.protocol) || serverUrl.username || serverUrl.password) {
|
||||||
|
throw new Error('The DAV server address is invalid.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestedCollection = asSafeDavUrl(remote.collectionUrl, serverUrl.href, serverUrl.origin);
|
||||||
|
const collection = collections.find(candidate => {
|
||||||
|
const url = asSafeDavUrl(candidate?.url, serverUrl.href, serverUrl.origin);
|
||||||
|
return url && requestedCollection && url.href === requestedCollection.href;
|
||||||
|
});
|
||||||
|
if (!collection || !requestedCollection) throw new Error('This DAV collection is not available on the selected server.');
|
||||||
|
|
||||||
|
const collectionUrl = asSafeDavUrl(collection.url, serverUrl.href, serverUrl.origin);
|
||||||
|
const objectUrl = asSafeDavUrl(remote.objectUrl, collectionUrl.href, serverUrl.origin);
|
||||||
|
if (!objectUrl) throw new Error('This DAV object address is not valid for the selected server.');
|
||||||
|
const collectionPath = collectionUrl.pathname.endsWith('/') ? collectionUrl.pathname : `${collectionUrl.pathname}/`;
|
||||||
|
if (objectUrl.pathname === collectionPath || !objectUrl.pathname.startsWith(collectionPath)) {
|
||||||
|
throw new Error('This DAV object is outside the selected collection.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const object = objects.find(candidate => {
|
||||||
|
const url = asSafeDavUrl(candidate?.url, collectionUrl.href, serverUrl.origin);
|
||||||
|
return url && url.href === objectUrl.href;
|
||||||
|
});
|
||||||
|
if (!object) throw new Error('This DAV object is no longer available in the selected collection.');
|
||||||
|
if (object.etag != null && remote.etag !== object.etag) {
|
||||||
|
throw new Error('This DAV item has changed on the server. Sync again before editing it.');
|
||||||
|
}
|
||||||
|
if (remote.etag != null && typeof remote.etag !== 'string') {
|
||||||
|
throw new Error('The DAV object version is invalid.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { collection, object, collectionUrl: collectionUrl.href, objectUrl: objectUrl.href };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { assertDavObjectReference };
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
function registerDavIpcHandlers({
|
||||||
|
registerIpcHandler,
|
||||||
|
readDavStore,
|
||||||
|
saveDavStore,
|
||||||
|
davPublicConfig,
|
||||||
|
openDavClient,
|
||||||
|
activeDavConfig,
|
||||||
|
ICAL,
|
||||||
|
makeCalendarData,
|
||||||
|
makeVcard,
|
||||||
|
randomUUID,
|
||||||
|
assertDavObjectReference
|
||||||
|
}) {
|
||||||
|
registerIpcHandler('dav:list', async () => {
|
||||||
|
const store = await readDavStore();
|
||||||
|
return {
|
||||||
|
caldav: store.caldav.map(davPublicConfig),
|
||||||
|
carddav: store.carddav.map(davPublicConfig),
|
||||||
|
activeCaldavId: store.activeCaldavId,
|
||||||
|
activeCarddavId: store.activeCarddavId
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:connect', async (_event, input) => {
|
||||||
|
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||||
|
const serverUrl = String(input?.serverUrl || '').trim();
|
||||||
|
const username = String(input?.username || '').trim();
|
||||||
|
const password = String(input?.password || '');
|
||||||
|
let parsedUrl;
|
||||||
|
try { parsedUrl = new URL(serverUrl); } catch { throw new Error('Enter a valid CalDAV or CardDAV server URL.'); }
|
||||||
|
if (!['https:', 'http:'].includes(parsedUrl.protocol) || parsedUrl.username || parsedUrl.password ||
|
||||||
|
(parsedUrl.protocol === 'http:' && !['localhost', '127.0.0.1', '::1'].includes(parsedUrl.hostname))) {
|
||||||
|
throw new Error('DAV server URLs must use HTTPS and must not contain embedded credentials.');
|
||||||
|
}
|
||||||
|
if (!username || !password) throw new Error('Enter the DAV username and password.');
|
||||||
|
const config = { id: randomUUID(), type, serverUrl: parsedUrl.href, username, password };
|
||||||
|
const client = await openDavClient(config, type);
|
||||||
|
const collections = type === 'caldav' ? await client.fetchCalendars() : await client.fetchAddressBooks();
|
||||||
|
if (!collections.length) throw new Error(`No ${type === 'caldav' ? 'calendars' : 'address books'} were found on this server.`);
|
||||||
|
config.collections = collections.map(collection => ({
|
||||||
|
url: collection.url,
|
||||||
|
name: typeof collection.displayName === 'string' ? collection.displayName : collection.url
|
||||||
|
}));
|
||||||
|
const store = await readDavStore();
|
||||||
|
const key = type;
|
||||||
|
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
||||||
|
const duplicate = store[key].find(account => account.serverUrl === config.serverUrl && account.username.toLowerCase() === username.toLowerCase());
|
||||||
|
if (duplicate) config.id = duplicate.id;
|
||||||
|
store[key] = [...store[key].filter(account => account.id !== config.id), config];
|
||||||
|
store[activeKey] = config.id;
|
||||||
|
await saveDavStore(store);
|
||||||
|
return {
|
||||||
|
config: davPublicConfig(config),
|
||||||
|
collections: config.collections,
|
||||||
|
accounts: {
|
||||||
|
caldav: store.caldav.map(davPublicConfig),
|
||||||
|
carddav: store.carddav.map(davPublicConfig),
|
||||||
|
activeCaldavId: store.activeCaldavId,
|
||||||
|
activeCarddavId: store.activeCarddavId
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:activate', async (_event, input) => {
|
||||||
|
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||||
|
const store = await readDavStore();
|
||||||
|
const config = store[type].find(item => item.id === input?.id);
|
||||||
|
if (!config) throw new Error('That DAV account could not be found.');
|
||||||
|
store[type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'] = config.id;
|
||||||
|
await saveDavStore(store);
|
||||||
|
return { id: config.id };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:remove', async (_event, input) => {
|
||||||
|
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
|
||||||
|
const store = await readDavStore();
|
||||||
|
store[type] = store[type].filter(item => item.id !== input?.id);
|
||||||
|
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
|
||||||
|
if (store[activeKey] === input?.id) store[activeKey] = store[type][0]?.id || null;
|
||||||
|
await saveDavStore(store);
|
||||||
|
return { accounts: store[type].map(davPublicConfig), activeId: store[activeKey] };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:sync', async (_event, requestedType) => {
|
||||||
|
const type = requestedType === 'carddav' ? 'carddav' : 'caldav';
|
||||||
|
const store = await readDavStore();
|
||||||
|
const config = activeDavConfig(store, type);
|
||||||
|
if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`);
|
||||||
|
const client = await openDavClient(config, type);
|
||||||
|
if (type === 'caldav') {
|
||||||
|
const calendars = await client.fetchCalendars();
|
||||||
|
const result = [];
|
||||||
|
for (const calendar of calendars) {
|
||||||
|
const objects = await client.fetchCalendarObjects({ calendar });
|
||||||
|
for (const object of objects) {
|
||||||
|
if (!object.data) continue;
|
||||||
|
try {
|
||||||
|
const component = new ICAL.Component(ICAL.parse(object.data));
|
||||||
|
for (const part of component.getAllSubcomponents('vevent')) {
|
||||||
|
const parsed = new ICAL.Event(part);
|
||||||
|
if (!parsed.startDate) continue;
|
||||||
|
const start = parsed.startDate.toJSDate();
|
||||||
|
result.push({
|
||||||
|
id: `dav:${config.id}:${encodeURIComponent(object.url)}:${encodeURIComponent(parsed.uid)}`,
|
||||||
|
title: parsed.summary || '(no title)',
|
||||||
|
date: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`,
|
||||||
|
time: parsed.startDate.isDate ? '' : `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`,
|
||||||
|
with: part.getAllProperties('attendee').map(property => String(property.getFirstValue() || '').replace(/^mailto:/i, '')).join(', '),
|
||||||
|
place: parsed.location || '',
|
||||||
|
notes: parsed.description || '',
|
||||||
|
_dav: { accountId: config.id, collectionUrl: calendar.url, objectUrl: object.url, etag: object.etag, uid: parsed.uid }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { items: result, account: davPublicConfig(config) };
|
||||||
|
}
|
||||||
|
const books = await client.fetchAddressBooks();
|
||||||
|
const result = [];
|
||||||
|
for (const book of books) {
|
||||||
|
const cards = await client.fetchVCards({ addressBook: book });
|
||||||
|
for (const card of cards) {
|
||||||
|
if (!card.data) continue;
|
||||||
|
try {
|
||||||
|
const parsed = new ICAL.Component(ICAL.parse(card.data));
|
||||||
|
const name = String(parsed.getFirstPropertyValue('fn') || '').trim();
|
||||||
|
if (!name) continue;
|
||||||
|
const emails = parsed.getAllProperties('email').map(property => String(property.getFirstValue() || ''));
|
||||||
|
const uid = String(parsed.getFirstPropertyValue('uid') || '');
|
||||||
|
result.push({
|
||||||
|
id: `dav:${config.id}:${encodeURIComponent(card.url)}:${encodeURIComponent(uid)}`,
|
||||||
|
name,
|
||||||
|
email: emails[0] || '',
|
||||||
|
note: String(parsed.getFirstPropertyValue('note') || ''),
|
||||||
|
initials: name.split(/\s+/).map(part => part[0]).join('').slice(0, 2).toUpperCase(),
|
||||||
|
color: '#dce9dd',
|
||||||
|
_dav: { accountId: config.id, collectionUrl: book.url, objectUrl: card.url, etag: card.etag, uid }
|
||||||
|
});
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { items: result, account: davPublicConfig(config) };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:save-event', async (_event, input) => {
|
||||||
|
const store = await readDavStore();
|
||||||
|
const remote = input?._dav;
|
||||||
|
const config = activeDavConfig(store, 'caldav', remote?.accountId);
|
||||||
|
if (!config) return null;
|
||||||
|
const client = await openDavClient(config, 'caldav');
|
||||||
|
const calendars = await client.fetchCalendars();
|
||||||
|
const calendar = remote?.collectionUrl
|
||||||
|
? calendars.find(item => item.url === remote.collectionUrl)
|
||||||
|
: calendars[0];
|
||||||
|
if (!calendar) throw new Error('No writable calendar was found.');
|
||||||
|
let trustedObject = null;
|
||||||
|
if (remote?.objectUrl) {
|
||||||
|
const objects = await client.fetchCalendarObjects({ calendar });
|
||||||
|
trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
|
||||||
|
}
|
||||||
|
const uid = remote?.uid || randomUUID();
|
||||||
|
const data = makeCalendarData({ ...input, _dav: { ...remote, uid } });
|
||||||
|
if (remote?.objectUrl) {
|
||||||
|
const response = await client.updateCalendarObject({
|
||||||
|
calendarObject: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
accountId: config.id,
|
||||||
|
collectionUrl: calendar.url,
|
||||||
|
objectUrl: trustedObject.objectUrl,
|
||||||
|
etag: response.headers.get('etag') || remote.etag,
|
||||||
|
uid
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const filename = `${encodeURIComponent(uid)}.ics`;
|
||||||
|
const response = await client.createCalendarObject({ calendar, iCalString: data.replace(`UID:${uid}`, `UID:${uid}`), filename });
|
||||||
|
return {
|
||||||
|
accountId: config.id,
|
||||||
|
collectionUrl: calendar.url,
|
||||||
|
objectUrl: new URL(filename, calendar.url.endsWith('/') ? calendar.url : `${calendar.url}/`).href,
|
||||||
|
etag: response.headers.get('etag'),
|
||||||
|
uid
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:delete-event', async (_event, remote) => {
|
||||||
|
const store = await readDavStore();
|
||||||
|
const config = activeDavConfig(store, 'caldav', remote?.accountId);
|
||||||
|
if (!config || !remote?.objectUrl) return;
|
||||||
|
const client = await openDavClient(config, 'caldav');
|
||||||
|
const calendars = await client.fetchCalendars();
|
||||||
|
const calendar = calendars.find(item => item.url === remote.collectionUrl);
|
||||||
|
if (!calendar) throw new Error('This DAV collection is not available on the selected server.');
|
||||||
|
const objects = await client.fetchCalendarObjects({ calendar });
|
||||||
|
const trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
|
||||||
|
await client.deleteCalendarObject({
|
||||||
|
calendarObject: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:save-contact', async (_event, input) => {
|
||||||
|
const store = await readDavStore();
|
||||||
|
const remote = input?._dav;
|
||||||
|
const config = activeDavConfig(store, 'carddav', remote?.accountId);
|
||||||
|
if (!config) return null;
|
||||||
|
const client = await openDavClient(config, 'carddav');
|
||||||
|
const books = await client.fetchAddressBooks();
|
||||||
|
const book = remote?.collectionUrl
|
||||||
|
? books.find(item => item.url === remote.collectionUrl)
|
||||||
|
: books[0];
|
||||||
|
if (!book) throw new Error('No writable address book was found.');
|
||||||
|
let trustedObject = null;
|
||||||
|
if (remote?.objectUrl) {
|
||||||
|
const cards = await client.fetchVCards({ addressBook: book });
|
||||||
|
trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
|
||||||
|
}
|
||||||
|
const uid = remote?.uid || randomUUID();
|
||||||
|
const data = makeVcard({ ...input, _dav: { ...remote, uid } });
|
||||||
|
if (remote?.objectUrl) {
|
||||||
|
const response = await client.updateVCard({
|
||||||
|
vCard: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
accountId: config.id,
|
||||||
|
collectionUrl: book.url,
|
||||||
|
objectUrl: trustedObject.objectUrl,
|
||||||
|
etag: response.headers.get('etag') || remote.etag,
|
||||||
|
uid
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const filename = `${encodeURIComponent(uid)}.vcf`;
|
||||||
|
const response = await client.createVCard({ addressBook: book, vCardString: data, filename });
|
||||||
|
return {
|
||||||
|
accountId: config.id,
|
||||||
|
collectionUrl: book.url,
|
||||||
|
objectUrl: new URL(filename, book.url.endsWith('/') ? book.url : `${book.url}/`).href,
|
||||||
|
etag: response.headers.get('etag'),
|
||||||
|
uid
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('dav:delete-contact', async (_event, remote) => {
|
||||||
|
const store = await readDavStore();
|
||||||
|
const config = activeDavConfig(store, 'carddav', remote?.accountId);
|
||||||
|
if (!config || !remote?.objectUrl) return;
|
||||||
|
const client = await openDavClient(config, 'carddav');
|
||||||
|
const books = await client.fetchAddressBooks();
|
||||||
|
const book = books.find(item => item.url === remote.collectionUrl);
|
||||||
|
if (!book) throw new Error('This DAV collection is not available on the selected server.');
|
||||||
|
const cards = await client.fetchVCards({ addressBook: book });
|
||||||
|
const trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
|
||||||
|
await client.deleteVCard({ vCard: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag } });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { registerDavIpcHandlers };
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
const { createAttachmentService } = require('../mail/attachment-service.cjs');
|
||||||
|
|
||||||
|
function registerMailIpcHandlers(dependencies) {
|
||||||
|
const {
|
||||||
|
registerIpcHandler,
|
||||||
|
BrowserWindow,
|
||||||
|
dialog,
|
||||||
|
shell,
|
||||||
|
fs,
|
||||||
|
credentialsPath,
|
||||||
|
readAccount,
|
||||||
|
readAccountStore,
|
||||||
|
saveAccountStore,
|
||||||
|
updateAccountStore,
|
||||||
|
saveAccount,
|
||||||
|
publicAccount,
|
||||||
|
normalizeAccount,
|
||||||
|
connectMail,
|
||||||
|
authorizeOAuthAccount,
|
||||||
|
listOAuthProviders,
|
||||||
|
requestBackgroundSync,
|
||||||
|
CUSTOM_FOLDER_PREFIX,
|
||||||
|
flushMailOutbox,
|
||||||
|
fetchMailbox,
|
||||||
|
cachedMailbox,
|
||||||
|
listCustomFolders,
|
||||||
|
imapClient,
|
||||||
|
validFolderName,
|
||||||
|
isConnectivityFailure,
|
||||||
|
randomUUID,
|
||||||
|
serializeOutgoingAttachments,
|
||||||
|
normalizeOutgoingAttachments,
|
||||||
|
sendMailSyncUpdate,
|
||||||
|
applyMessageAction,
|
||||||
|
mailOutbox,
|
||||||
|
pgpMail,
|
||||||
|
PgpError,
|
||||||
|
simpleParser,
|
||||||
|
folderPath,
|
||||||
|
sendMailNow,
|
||||||
|
pgpFailure
|
||||||
|
} = dependencies;
|
||||||
|
|
||||||
|
registerIpcHandler('mail:get-account', async () => {
|
||||||
|
const account = await readAccount();
|
||||||
|
return account ? publicAccount(account) : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:list-accounts', async () => {
|
||||||
|
const store = (await readAccountStore()) || { accounts: [], activeId: null };
|
||||||
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
|
||||||
|
|
||||||
|
registerIpcHandler('mail:select-account', async (_event, accountId) => {
|
||||||
|
const account = await updateAccountStore(store => {
|
||||||
|
const selected = store.accounts.find(item => item.id === accountId);
|
||||||
|
if (!selected) throw new Error('That mail account is no longer available.');
|
||||||
|
store.activeId = selected.id;
|
||||||
|
return selected;
|
||||||
|
});
|
||||||
|
requestBackgroundSync();
|
||||||
|
return publicAccount(account);
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:remove-account', async (_event, accountId) => {
|
||||||
|
const result = await updateAccountStore(store => {
|
||||||
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
||||||
|
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
|
||||||
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
|
});
|
||||||
|
requestBackgroundSync(accountId);
|
||||||
|
requestBackgroundSync();
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
|
||||||
|
const existing = await readAccount(accountId);
|
||||||
|
if (!existing) throw new Error('That mail account is no longer available.');
|
||||||
|
let account = normalizeAccount({
|
||||||
|
...existing,
|
||||||
|
...input,
|
||||||
|
authMethod: input?.authMethod || existing.authMethod || 'password',
|
||||||
|
password: String(input?.password || '') || existing.password || ''
|
||||||
|
});
|
||||||
|
account.id = existing.id;
|
||||||
|
if (account.authMethod === 'oauth2') {
|
||||||
|
if (!input?.reauthorizeOAuth && existing.authMethod === 'oauth2' && existing.oauthProvider === account.oauthProvider && existing.oauthRefreshToken) {
|
||||||
|
account.oauthAccessToken = existing.oauthAccessToken;
|
||||||
|
account.oauthRefreshToken = existing.oauthRefreshToken;
|
||||||
|
account.oauthAccessTokenExpiresAt = existing.oauthAccessTokenExpiresAt;
|
||||||
|
} else {
|
||||||
|
account = await authorizeOAuthAccount(account);
|
||||||
|
account.id = existing.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const status = await connectMail(account);
|
||||||
|
const savedAccount = await updateAccountStore(store => {
|
||||||
|
const current = store.accounts.find(item => item.id === existing.id);
|
||||||
|
if (!current) throw new Error('That mail account is no longer available.');
|
||||||
|
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
|
||||||
|
store.accounts = store.accounts.map(item => item.id === existing.id
|
||||||
|
? {
|
||||||
|
...account,
|
||||||
|
syncState: endpointChanged ? undefined : current.syncState,
|
||||||
|
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
|
||||||
|
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
|
||||||
|
}
|
||||||
|
: item);
|
||||||
|
return store.accounts.find(item => item.id === existing.id);
|
||||||
|
});
|
||||||
|
requestBackgroundSync(existing.id);
|
||||||
|
return { ...publicAccount(savedAccount), ...status };
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Could not update the mailbox: ${error.message}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:connect', async (_event, input) => {
|
||||||
|
let account = normalizeAccount(input);
|
||||||
|
try {
|
||||||
|
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
||||||
|
const status = await connectMail(account);
|
||||||
|
const saved = await saveAccount(account);
|
||||||
|
requestBackgroundSync(saved.id);
|
||||||
|
return { ok: true, ...publicAccount(saved), ...status };
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Could not connect to the mailbox: ${error.message}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
|
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
||||||
|
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
|
||||||
|
const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX)
|
||||||
|
? selectedFolder : 'Inbox';
|
||||||
|
const { folder: _filterFolder, ...criteria } = filters;
|
||||||
|
try {
|
||||||
|
await flushMailOutbox(account);
|
||||||
|
return await fetchMailbox(account, folder, offset, 20, criteria);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
const cached = cachedMailbox(account, folder, offset, 20, criteria);
|
||||||
|
if (!cached.total) throw error;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:list-folders', async () => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before listing folders.');
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
return { folders: await listCustomFolders(client) };
|
||||||
|
} catch (error) {
|
||||||
|
if (isConnectivityFailure(error)) return { folders: [], offline: true };
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:create-folder', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before creating folders.');
|
||||||
|
const name = validFolderName(input?.name);
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const existing = await client.list();
|
||||||
|
if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) {
|
||||||
|
throw new Error('A folder with that name already exists.');
|
||||||
|
}
|
||||||
|
const created = await client.mailboxCreate(name);
|
||||||
|
await client.mailboxSubscribe(created.path).catch(() => {});
|
||||||
|
return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) };
|
||||||
|
} catch (error) {
|
||||||
|
if (error.message === 'A folder with that name already exists.') throw error;
|
||||||
|
throw new Error(`Could not create the folder: ${error.message}`);
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:list-drafts', async () => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before opening drafts.');
|
||||||
|
return { drafts: account.drafts || [], offline: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:save-draft', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before saving drafts.');
|
||||||
|
const draft = {
|
||||||
|
id: String(input?.id || randomUUID()),
|
||||||
|
to: String(input?.to || '').slice(0, 4000),
|
||||||
|
cc: String(input?.cc || '').slice(0, 4000),
|
||||||
|
subject: String(input?.subject || '').slice(0, 998),
|
||||||
|
text: String(input?.text || '').slice(0, 500000),
|
||||||
|
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
|
||||||
|
updatedAt: Date.now()
|
||||||
|
};
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
const drafts = saved.drafts || [];
|
||||||
|
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
|
||||||
|
});
|
||||||
|
return draft;
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:delete-draft', async (_event, id) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before deleting drafts.');
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
|
||||||
|
});
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:set-snooze', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before setting a reminder.');
|
||||||
|
const uid = Number(input?.uid);
|
||||||
|
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
|
||||||
|
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
|
||||||
|
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
|
||||||
|
throw new Error('Choose a reminder time in the future.');
|
||||||
|
}
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
const snoozes = saved.snoozedMessages || [];
|
||||||
|
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
|
||||||
|
if (dueAt != null) {
|
||||||
|
remaining.push({
|
||||||
|
uid,
|
||||||
|
folder,
|
||||||
|
dueAt,
|
||||||
|
subject: String(input.subject || '').slice(0, 200)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
saved.snoozedMessages = remaining;
|
||||||
|
});
|
||||||
|
sendMailSyncUpdate({
|
||||||
|
accountId: account.id,
|
||||||
|
foldersChanged: ['Snoozed', folder]
|
||||||
|
});
|
||||||
|
return { ok: true, snoozed: dueAt != null };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:update-message', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before changing messages.');
|
||||||
|
try {
|
||||||
|
return await applyMessageAction(account, input);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
return mailOutbox.queueMessageAction(account, input);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Encrypted messages keep their attachments inside the encrypted payload.
|
||||||
|
async function parseForAttachments(source) {
|
||||||
|
const parsed = await simpleParser(source);
|
||||||
|
const kind = pgpMail.detect(parsed);
|
||||||
|
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
|
||||||
|
try {
|
||||||
|
return (await pgpMail.decrypt(parsed)).parsed;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments });
|
||||||
|
|
||||||
|
registerIpcHandler('mail:save-attachment', async (event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before downloading attachments.');
|
||||||
|
const parent = BrowserWindow.fromWebContents(event.sender);
|
||||||
|
return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options));
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:preview-attachment', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
||||||
|
return attachmentService.previewAttachment(account, input);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
registerIpcHandler('mail:open-external', async (event, rawUrl) => {
|
||||||
|
let target;
|
||||||
|
try {
|
||||||
|
target = new URL(String(rawUrl || ''));
|
||||||
|
} catch {
|
||||||
|
throw new Error('This link is not a valid web address.');
|
||||||
|
}
|
||||||
|
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
||||||
|
throw new Error('Only standard web links can be opened from mail.');
|
||||||
|
}
|
||||||
|
const parent = BrowserWindow.fromWebContents(event.sender);
|
||||||
|
const confirmation = await dialog.showMessageBox(parent, {
|
||||||
|
type: 'warning',
|
||||||
|
title: 'Open external link?',
|
||||||
|
message: 'Email links can lead to fake sign-in pages or harmful content.',
|
||||||
|
detail: `Check the full address before continuing:\n${target.href}`,
|
||||||
|
buttons: ['Cancel', 'Open link'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (confirmation.response !== 1) return { opened: false };
|
||||||
|
await shell.openExternal(target.href);
|
||||||
|
return { opened: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:sync-inbox', async () => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
|
return fetchMailbox(account, 'Inbox');
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
registerIpcHandler('mail:send', async (event, message) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before sending.');
|
||||||
|
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
|
||||||
|
const queuedMessage = {
|
||||||
|
to: message.to,
|
||||||
|
cc: message.cc,
|
||||||
|
subject: message.subject,
|
||||||
|
text: message.text,
|
||||||
|
displayName: message.displayName,
|
||||||
|
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
|
||||||
|
attachments: message.attachments
|
||||||
|
};
|
||||||
|
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
||||||
|
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
|
||||||
|
delete queuedMessage.pgp;
|
||||||
|
if (!pgpOptions?.encrypt) {
|
||||||
|
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
|
||||||
|
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
|
||||||
|
if (status.recipients.length && !status.missing.length) {
|
||||||
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
type: 'warning',
|
||||||
|
buttons: ['Cancel', 'Send anyway'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
title: 'Send without encryption?',
|
||||||
|
message: 'Public keys are available for all recipients.',
|
||||||
|
detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.',
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (response !== 1) throw new Error('Plaintext send cancelled.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pgpOptions) {
|
||||||
|
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
|
||||||
|
const signature = String(account.signature || '').slice(0, 5000);
|
||||||
|
const body = String(queuedMessage.text || '').slice(0, 500000);
|
||||||
|
const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||||
|
try {
|
||||||
|
const built = await pgpMail.build({
|
||||||
|
from: { name: fromName, address: account.email },
|
||||||
|
to: queuedMessage.to,
|
||||||
|
cc: queuedMessage.cc,
|
||||||
|
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
|
||||||
|
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||||
|
messageId: queuedMessage.messageId,
|
||||||
|
encrypt: Boolean(pgpOptions.encrypt),
|
||||||
|
sign: Boolean(pgpOptions.sign),
|
||||||
|
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
|
||||||
|
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
|
||||||
|
});
|
||||||
|
queuedMessage.rawBase64 = built.raw.toString('base64');
|
||||||
|
queuedMessage.envelope = built.envelope;
|
||||||
|
queuedMessage.text = '';
|
||||||
|
queuedMessage.attachments = [];
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof PgpError) return pgpFailure(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await sendMailNow(account, queuedMessage);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
saved.mailOutbox = saved.mailOutbox || [];
|
||||||
|
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
|
||||||
|
});
|
||||||
|
return { ok: true, queued: true };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
registerIpcHandler('mail:disconnect', async (_event, accountId) => {
|
||||||
|
const store = await readAccountStore();
|
||||||
|
if (!store) return { accounts: [], activeId: null };
|
||||||
|
if (accountId) {
|
||||||
|
store.accounts = store.accounts.filter(account => account.id !== accountId);
|
||||||
|
} else {
|
||||||
|
store.accounts = [];
|
||||||
|
}
|
||||||
|
if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true });
|
||||||
|
else {
|
||||||
|
if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id;
|
||||||
|
await saveAccountStore(store);
|
||||||
|
}
|
||||||
|
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { registerMailIpcHandlers };
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
function pgpFailure(error) {
|
||||||
|
return {
|
||||||
|
failed: true,
|
||||||
|
code: error.code,
|
||||||
|
message: error.message,
|
||||||
|
fingerprint: error.details?.fingerprint || null,
|
||||||
|
email: error.details?.email || null,
|
||||||
|
missing: error.details?.missing || []
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerPgpIpcHandlers({
|
||||||
|
registerIpcHandler,
|
||||||
|
BrowserWindow,
|
||||||
|
dialog,
|
||||||
|
fs,
|
||||||
|
openpgp,
|
||||||
|
pgpKeys,
|
||||||
|
pgpCache,
|
||||||
|
pgpMail,
|
||||||
|
PgpError,
|
||||||
|
pgpKeyServers,
|
||||||
|
listServers,
|
||||||
|
MAX_CUSTOM_SERVERS,
|
||||||
|
normalizeCustomServer,
|
||||||
|
randomUUID,
|
||||||
|
readAccount,
|
||||||
|
imapClient,
|
||||||
|
folderPath,
|
||||||
|
simpleParser,
|
||||||
|
extractMailContent
|
||||||
|
}) {
|
||||||
|
async function fetchMessageSource(account, folder, uid) {
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const mailboxPath = await folderPath(client, folder);
|
||||||
|
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||||
|
const lock = await client.getMailboxLock(mailboxPath);
|
||||||
|
try {
|
||||||
|
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||||
|
if (!item?.source) throw new Error('The message is no longer available.');
|
||||||
|
return item.source;
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveKeyFile(event, defaultName, content) {
|
||||||
|
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: defaultName });
|
||||||
|
if (result.canceled || !result.filePath) return { canceled: true };
|
||||||
|
await fs.writeFile(result.filePath, content, { mode: 0o600 });
|
||||||
|
return { saved: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pgpFingerprint = value => {
|
||||||
|
const fingerprint = String(value || '').toUpperCase();
|
||||||
|
if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.');
|
||||||
|
return fingerprint;
|
||||||
|
};
|
||||||
|
|
||||||
|
registerIpcHandler('pgp:list', () => pgpKeys.list());
|
||||||
|
registerIpcHandler('pgp:generate', (_event, input) => pgpKeys.generate({
|
||||||
|
name: input?.name, email: input?.email, passphrase: input?.passphrase, accountId: input?.accountId || null
|
||||||
|
}));
|
||||||
|
registerIpcHandler('pgp:import', async (event, input) => {
|
||||||
|
let armoredKey = input?.armoredKey;
|
||||||
|
if (!armoredKey) {
|
||||||
|
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
properties: ['openFile'], filters: [{ name: 'OpenPGP keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
|
||||||
|
});
|
||||||
|
if (result.canceled || !result.filePaths[0]) return { canceled: true };
|
||||||
|
const stat = await fs.stat(result.filePaths[0]);
|
||||||
|
if (stat.size > 200000) throw new Error('That key file is too large.');
|
||||||
|
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||||
|
}
|
||||||
|
return { key: await pgpKeys.import({ armoredKey, passphrase: input?.passphrase, accountId: input?.accountId || null }) };
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:export-public', async (event, fingerprint) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
return saveKeyFile(event, `ep-mail-public-${id.slice(-16)}.asc`, await pgpKeys.exportPublic(id));
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:export-private', async (event, fingerprint, passphrase) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:change-passphrase', async (_event, input) => {
|
||||||
|
const id = pgpFingerprint(input?.fingerprint);
|
||||||
|
const result = await pgpKeys.changePassphrase(id, input?.currentPassphrase, input?.newPassphrase);
|
||||||
|
pgpCache.clear(id);
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:export-revocation', async (event, fingerprint, passphrase) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:delete', async (_event, fingerprint, passphrase) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
const result = await pgpKeys.remove(id, passphrase);
|
||||||
|
pgpCache.clear(id);
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:decrypt-message', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before opening messages.');
|
||||||
|
const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid));
|
||||||
|
const outer = await simpleParser(source);
|
||||||
|
try {
|
||||||
|
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
|
||||||
|
const content = extractMailContent(result.parsed);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
body: content.body,
|
||||||
|
html: content.html,
|
||||||
|
links: content.links,
|
||||||
|
attachments: content.attachments,
|
||||||
|
attachment: content.attachment,
|
||||||
|
size: content.size,
|
||||||
|
signatures: result.signatures,
|
||||||
|
attachedKeys: result.attachedKeys.map(key => ({ fingerprint: key.fingerprint, emails: key.emails, armoredKey: key.armoredKey }))
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof PgpError) return pgpFailure(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:check-send', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
return pgpMail.recipientStatus([input?.to, input?.cc], { sign: Boolean(input?.sign), from: account?.email || '' });
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:contacts', () => pgpKeys.listContacts());
|
||||||
|
registerIpcHandler('pgp:add-contact', async (event, input) => {
|
||||||
|
let armoredKey = typeof input?.armoredKey === 'string' ? input.armoredKey : '';
|
||||||
|
if (!armoredKey) {
|
||||||
|
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
properties: ['openFile'], filters: [{ name: 'OpenPGP public keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
|
||||||
|
});
|
||||||
|
if (result.canceled || !result.filePaths[0]) return { canceled: true };
|
||||||
|
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
|
||||||
|
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||||
|
}
|
||||||
|
const key = await openpgp.readKey({ armoredKey }).catch(() => {
|
||||||
|
throw new Error('That is not a valid OpenPGP public key.');
|
||||||
|
});
|
||||||
|
const fingerprint = key.getFingerprint().toUpperCase();
|
||||||
|
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||||
|
const existing = await pgpKeys.listContacts();
|
||||||
|
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
|
||||||
|
if (overlaps.length) {
|
||||||
|
const detail = overlaps.map(item => {
|
||||||
|
const name = item.name || 'Unknown contact';
|
||||||
|
const addresses = (item.emails || []).join(', ') || 'no address';
|
||||||
|
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
|
||||||
|
return `${name} (${addresses})\nFingerprint: ${fp}`;
|
||||||
|
}).join('\n\n');
|
||||||
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
type: 'warning',
|
||||||
|
buttons: ['Cancel', 'Replace key'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
title: 'Confirm key replacement',
|
||||||
|
message: 'A different public key already exists for this email address.',
|
||||||
|
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (response !== 1) throw new Error('Key replacement cancelled.');
|
||||||
|
}
|
||||||
|
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
|
||||||
|
return pgpKeys.addContact({ armoredKey, source });
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:set-trust', async (event, fingerprint, trust) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
const level = String(trust);
|
||||||
|
// Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer.
|
||||||
|
if (level !== 'unknown') {
|
||||||
|
const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id);
|
||||||
|
if (!contact) throw new Error('That contact key was not found.');
|
||||||
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
type: 'question',
|
||||||
|
buttons: ['Cancel', `Mark as ${level}`],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
title: 'Confirm key trust',
|
||||||
|
message: `Mark this key as ${level}?`,
|
||||||
|
detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.`
|
||||||
|
});
|
||||||
|
if (response !== 1) throw new Error('Trust change cancelled.');
|
||||||
|
}
|
||||||
|
return pgpKeys.setTrust(id, level);
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
|
||||||
|
registerIpcHandler('pgp:export-contact', async (event, fingerprint) => {
|
||||||
|
const id = pgpFingerprint(fingerprint);
|
||||||
|
return saveKeyFile(event, `ep-mail-contact-${id.slice(-16)}.asc`, await pgpKeys.exportContact(id));
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:get-settings', () => pgpKeys.getSettings());
|
||||||
|
registerIpcHandler('pgp:set-settings', async (_event, input) => {
|
||||||
|
const settings = await pgpKeys.setSettings({ cacheMinutes: input?.cacheMinutes });
|
||||||
|
pgpCache.clear();
|
||||||
|
return settings;
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:key-servers', async () => {
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
return listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => {
|
||||||
|
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||||
|
const serverId = String(input?.serverId || '');
|
||||||
|
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
|
||||||
|
const enabled = new Set(settings.enabledKeyServers);
|
||||||
|
if (input.enabled) enabled.add(serverId);
|
||||||
|
else enabled.delete(serverId);
|
||||||
|
await pgpKeys.setSettings({
|
||||||
|
cacheMinutes: settings.cacheMinutes,
|
||||||
|
customKeyServers: settings.customKeyServers,
|
||||||
|
enabledKeyServers: [...enabled]
|
||||||
|
});
|
||||||
|
return { serverId, enabled: input.enabled };
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:add-key-server', async (event, input) => {
|
||||||
|
const candidate = normalizeCustomServer(input);
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
const customServers = settings.customKeyServers.map(normalizeCustomServer);
|
||||||
|
if (customServers.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`);
|
||||||
|
if (customServers.some(server => server.url === candidate.url && server.protocol === candidate.protocol)) {
|
||||||
|
throw new Error('That key server is already configured.');
|
||||||
|
}
|
||||||
|
const url = new URL(candidate.url);
|
||||||
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
type: 'warning',
|
||||||
|
buttons: ['Cancel', 'Add server'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
title: 'Add custom key server?',
|
||||||
|
message: `Allow ep-mail to contact ${url.host} for OpenPGP keys?`,
|
||||||
|
detail: `Protocol: ${candidate.protocol.toUpperCase()}\nEndpoint: ${candidate.url}\nThe server may learn which email addresses you search for. Only add a server you trust.`,
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (response !== 1) return { canceled: true };
|
||||||
|
candidate.id = randomUUID();
|
||||||
|
const updated = await pgpKeys.setSettings({
|
||||||
|
cacheMinutes: settings.cacheMinutes,
|
||||||
|
customKeyServers: [...customServers, candidate]
|
||||||
|
});
|
||||||
|
return { server: updated.customKeyServers[updated.customKeyServers.length - 1] };
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:remove-key-server', async (_event, serverId) => {
|
||||||
|
const id = String(serverId || '');
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
const customServers = settings.customKeyServers.filter(server => server.id !== id);
|
||||||
|
if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.');
|
||||||
|
await pgpKeys.setSettings({
|
||||||
|
cacheMinutes: settings.cacheMinutes,
|
||||||
|
customKeyServers,
|
||||||
|
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
|
||||||
|
});
|
||||||
|
return { removed: true };
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:find-key', async (_event, input) => {
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||||
|
return pgpKeyServers.lookupEnabled(servers, input?.email);
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:publish-key', async (event, input) => {
|
||||||
|
const fingerprint = pgpFingerprint(input?.fingerprint);
|
||||||
|
const settings = await pgpKeys.getSettings();
|
||||||
|
const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || ''));
|
||||||
|
if (!server) throw new Error('Choose a configured key server.');
|
||||||
|
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
|
||||||
|
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
if (!entry.email) throw new Error('This key has no email address to publish.');
|
||||||
|
const armoredKey = await pgpKeys.exportPublic(fingerprint);
|
||||||
|
const publicKey = await openpgp.readKey({ armoredKey });
|
||||||
|
const emails = [...new Set(publicKey.getUserIDs()
|
||||||
|
.map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase())
|
||||||
|
.filter(Boolean))];
|
||||||
|
if (!emails.includes(entry.email.toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
|
||||||
|
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||||
|
type: 'warning',
|
||||||
|
buttons: ['Cancel', 'Publish public key'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
title: 'Publish public key?',
|
||||||
|
message: `Publish the public key for ${emails.join(', ')} to ${server.name}?`,
|
||||||
|
detail: `Fingerprint:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly the public key will be sent. This exposes the email address(es) in the key to the server, which may retain them. The server may send a verification email before the key becomes searchable.`,
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (response !== 1) return { canceled: true };
|
||||||
|
return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint);
|
||||||
|
});
|
||||||
|
registerIpcHandler('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { pgpFailure, registerPgpIpcHandlers };
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
function normalizeOutgoingAttachments(value) {
|
||||||
|
if (value === undefined) return [];
|
||||||
|
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
|
||||||
|
return value.map(file => {
|
||||||
|
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
|
||||||
|
throw new Error('An attachment could not be read.');
|
||||||
|
}
|
||||||
|
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
|
||||||
|
.replace(/[\r\n\0]/g, '')
|
||||||
|
.slice(0, 255) || 'attachment';
|
||||||
|
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
|
||||||
|
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
|
||||||
|
throw new Error(`The content type for ${filename} is invalid.`);
|
||||||
|
}
|
||||||
|
const encoded = file.contentBase64;
|
||||||
|
if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
|
||||||
|
throw new Error(`The contents of ${filename} are invalid.`);
|
||||||
|
}
|
||||||
|
const content = Buffer.from(encoded, 'base64');
|
||||||
|
return { filename, contentType, contentBase64: encoded, size: content.length, content };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeOutgoingAttachments(attachments) {
|
||||||
|
return attachments.map(({ content, ...file }) => file);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
function extractMailContent(parsed) {
|
||||||
|
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
|
||||||
|
const body = bodyText
|
||||||
|
? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40)
|
||||||
|
: ['This message has no plain-text body.'];
|
||||||
|
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
|
||||||
|
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
|
||||||
|
.map(match => (match[1] || match[2] || match[3] || '').replace(/&/gi, '&').replace(///gi, '/'))
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 30);
|
||||||
|
const files = (parsed.attachments || [])
|
||||||
|
.filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
|
||||||
|
return {
|
||||||
|
bodyText,
|
||||||
|
body,
|
||||||
|
html: html.slice(0, 100000),
|
||||||
|
links,
|
||||||
|
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||||
|
attachment: files[0]?.filename || null,
|
||||||
|
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { extractMailContent };
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
const { randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
|
const CUSTOM_FOLDER_PREFIX = 'Folder:';
|
||||||
|
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
|
||||||
|
|
||||||
|
function normalizeAccount(input, { createId = randomUUID } = {}) {
|
||||||
|
const email = String(input?.email || '').trim();
|
||||||
|
const authMethod = input?.authMethod === undefined ? 'password' : String(input.authMethod);
|
||||||
|
if (!['password', 'oauth2'].includes(authMethod)) throw new Error('Choose a supported sign-in method.');
|
||||||
|
const oauthProvider = authMethod === 'oauth2' ? String(input?.oauthProvider || '') : '';
|
||||||
|
if (authMethod === 'oauth2' && !['google', 'microsoft'].includes(oauthProvider)) {
|
||||||
|
throw new Error('Choose Google or Microsoft OAuth2 sign-in.');
|
||||||
|
}
|
||||||
|
const providerDefaults = oauthProvider === 'google'
|
||||||
|
? { imapHost: 'imap.gmail.com', smtpHost: 'smtp.gmail.com', imapPort: 993, smtpPort: 587, imapSecure: true }
|
||||||
|
: oauthProvider === 'microsoft'
|
||||||
|
? { imapHost: 'outlook.office365.com', smtpHost: 'smtp.office365.com', imapPort: 993, smtpPort: 587, imapSecure: true }
|
||||||
|
: { imapHost: '', smtpHost: '', imapPort: 143, smtpPort: 587, imapSecure: false };
|
||||||
|
const password = authMethod === 'password' ? String(input?.password || '') : '';
|
||||||
|
const imapHost = String(oauthProvider ? providerDefaults.imapHost : input?.imapHost || providerDefaults.imapHost).trim();
|
||||||
|
const smtpHost = String(oauthProvider ? providerDefaults.smtpHost : input?.smtpHost || providerDefaults.smtpHost).trim();
|
||||||
|
const displayName = String(input?.displayName || '').trim().slice(0, 80);
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !imapHost || !smtpHost || (authMethod === 'password' && !password)) {
|
||||||
|
throw new Error(authMethod === 'password'
|
||||||
|
? 'Enter a valid email, password, and both mail server names.'
|
||||||
|
: 'Enter a valid email and supported OAuth mail servers.');
|
||||||
|
}
|
||||||
|
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
||||||
|
const imapPort = Number(oauthProvider ? providerDefaults.imapPort : input?.imapPort ?? providerDefaults.imapPort);
|
||||||
|
const smtpPort = Number(oauthProvider ? providerDefaults.smtpPort : input?.smtpPort ?? providerDefaults.smtpPort);
|
||||||
|
if (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535)) {
|
||||||
|
throw new Error('Enter valid IMAP and SMTP ports.');
|
||||||
|
}
|
||||||
|
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
|
||||||
|
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
||||||
|
throw new Error('Choose a supported mailbox sync interval.');
|
||||||
|
}
|
||||||
|
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
|
||||||
|
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
|
||||||
|
const rules = inputRules.map((rule, index) => {
|
||||||
|
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
|
||||||
|
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
|
||||||
|
const action = String(rule?.action || '');
|
||||||
|
const value = String(rule?.value || '').trim().slice(0, 200);
|
||||||
|
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
|
||||||
|
}
|
||||||
|
if ((action === 'move' || action === 'label') && !value) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
|
||||||
|
}
|
||||||
|
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
|
||||||
|
}
|
||||||
|
return { id: String(rule.id || createId()), senderContains, subjectContains, action, value };
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
email, password, authMethod, oauthProvider: oauthProvider || null,
|
||||||
|
displayName, imapHost, smtpHost, imapPort, smtpPort,
|
||||||
|
imapSecure: oauthProvider ? providerDefaults.imapSecure : input?.imapSecure === undefined ? providerDefaults.imapSecure : Boolean(input.imapSecure),
|
||||||
|
smtpSecure: oauthProvider ? false : input?.smtpSecure === undefined ? false : Boolean(input.smtpSecure),
|
||||||
|
signature: String(input?.signature || '').slice(0, 5000),
|
||||||
|
notificationsEnabled: input?.notificationsEnabled !== false,
|
||||||
|
syncIntervalMinutes,
|
||||||
|
rules
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function publicAccount(account) {
|
||||||
|
return {
|
||||||
|
id: account.id,
|
||||||
|
email: account.email,
|
||||||
|
displayName: account.displayName || '',
|
||||||
|
authMethod: account.authMethod === 'oauth2' ? 'oauth2' : 'password',
|
||||||
|
oauthProvider: account.authMethod === 'oauth2' ? account.oauthProvider || null : null,
|
||||||
|
imapHost: account.imapHost,
|
||||||
|
smtpHost: account.smtpHost,
|
||||||
|
imapPort: Number(account.imapPort) || (account.authMethod === 'oauth2' ? 993 : 143),
|
||||||
|
smtpPort: Number(account.smtpPort) || 587,
|
||||||
|
imapSecure: Boolean(account.imapSecure),
|
||||||
|
smtpSecure: Boolean(account.smtpSecure),
|
||||||
|
signature: account.signature || '',
|
||||||
|
notificationsEnabled: account.notificationsEnabled !== false,
|
||||||
|
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
||||||
|
rules: Array.isArray(account.rules) ? account.rules : []
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isReservedFolderName(name) {
|
||||||
|
return RESERVED_FOLDER_NAMES.has(String(name).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function validFolderName(input) {
|
||||||
|
const name = String(input || '').trim();
|
||||||
|
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
|
||||||
|
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
|
||||||
|
if (isReservedFolderName(name)) throw new Error('That folder name is reserved.');
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterMailboxMessages(messages, filters = {}) {
|
||||||
|
const text = String(filters.query || '').trim().toLowerCase();
|
||||||
|
const sender = String(filters.sender || '').trim().toLowerCase();
|
||||||
|
const subject = String(filters.subject || '').trim().toLowerCase();
|
||||||
|
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
|
||||||
|
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
|
||||||
|
return messages.filter(message => {
|
||||||
|
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
|
||||||
|
const date = Number(message.timestamp || 0);
|
||||||
|
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
|
||||||
|
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
|
||||||
|
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
|
||||||
|
(!after || date >= after) && (!before || date <= before) &&
|
||||||
|
(!filters.hasAttachments || (message.attachments || []).length > 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
CUSTOM_FOLDER_PREFIX,
|
||||||
|
filterMailboxMessages,
|
||||||
|
isReservedFolderName,
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
validFolderName
|
||||||
|
};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
function createMessageActionService({ imapClient, folderPath, findSpecialMailbox, updateAccountStore }) {
|
||||||
|
async function applyMessageAction(account, input) {
|
||||||
|
const uid = Number(input?.uid);
|
||||||
|
const folder = String(input?.folder || 'Inbox');
|
||||||
|
const action = String(input?.action || '');
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const sourcePath = await folderPath(client, folder);
|
||||||
|
if (!sourcePath) throw new Error('That mail folder could not be found.');
|
||||||
|
const lock = await client.getMailboxLock(sourcePath);
|
||||||
|
try {
|
||||||
|
if (action === 'star') {
|
||||||
|
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
|
||||||
|
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
|
||||||
|
} else if (action === 'unread') {
|
||||||
|
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
|
||||||
|
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
|
||||||
|
} else {
|
||||||
|
const target = action === 'archive'
|
||||||
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
||||||
|
: action === 'delete'
|
||||||
|
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
|
||||||
|
: 'INBOX';
|
||||||
|
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
|
||||||
|
if (action === 'delete') await client.messageDelete(uid, { uid: true });
|
||||||
|
}
|
||||||
|
else await client.messageMove(uid, target, { uid: true });
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
if (action === 'archive' || action === 'delete' || action === 'inbox') {
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) {
|
||||||
|
saved.snoozedMessages = (saved.snoozedMessages || [])
|
||||||
|
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { applyMessageAction };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createMessageActionService };
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
const fs = require('node:fs/promises');
|
||||||
|
|
||||||
|
function createAttachmentService({ imapClient, folderPath, parseForAttachments, writeFile = fs.writeFile }) {
|
||||||
|
async function loadAttachment(account, input, selectAttachment) {
|
||||||
|
const uid = Number(input?.uid);
|
||||||
|
const folder = String(input?.folder || 'Inbox');
|
||||||
|
const filename = String(input?.filename || 'attachment');
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const mailboxPath = await folderPath(client, folder);
|
||||||
|
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||||
|
const lock = await client.getMailboxLock(mailboxPath);
|
||||||
|
try {
|
||||||
|
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||||
|
if (!item?.source) throw new Error('The message is no longer available.');
|
||||||
|
const parsed = await parseForAttachments(item.source);
|
||||||
|
const attachment = selectAttachment(parsed.attachments || [], filename);
|
||||||
|
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||||
|
return { attachment, filename };
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveAttachment(account, input, showSaveDialog) {
|
||||||
|
const { attachment, filename } = await loadAttachment(account, input, (attachments, selectedName) =>
|
||||||
|
attachments.find(file => (file.filename || 'attachment') === selectedName) || attachments[0]);
|
||||||
|
const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_');
|
||||||
|
const result = await showSaveDialog({
|
||||||
|
defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_')
|
||||||
|
});
|
||||||
|
if (result.canceled || !result.filePath) return { canceled: true };
|
||||||
|
await writeFile(result.filePath, attachment.content);
|
||||||
|
return { saved: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function previewAttachment(account, input) {
|
||||||
|
const { attachment } = await loadAttachment(account, input, (attachments, filename) =>
|
||||||
|
attachments.find(file => (file.filename || 'attachment') === filename));
|
||||||
|
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
|
||||||
|
const size = attachment.content.length;
|
||||||
|
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
|
||||||
|
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
|
||||||
|
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
|
||||||
|
}
|
||||||
|
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
|
||||||
|
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
|
||||||
|
}
|
||||||
|
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { previewAttachment, saveAttachment };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createAttachmentService };
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
function createMailConnections({ ImapFlow, createTransport, oauthTokenManager }) {
|
||||||
|
async function imapClient(account, options = {}) {
|
||||||
|
const isOAuth = account.authMethod === 'oauth2';
|
||||||
|
const auth = isOAuth
|
||||||
|
? { user: account.email, accessToken: await oauthTokenManager.getAccessToken(account) }
|
||||||
|
: { user: account.email, pass: account.password };
|
||||||
|
return new ImapFlow({
|
||||||
|
host: account.imapHost,
|
||||||
|
port: account.imapPort,
|
||||||
|
secure: Boolean(account.imapSecure),
|
||||||
|
doSTARTTLS: !account.imapSecure,
|
||||||
|
auth,
|
||||||
|
tls: { rejectUnauthorized: true },
|
||||||
|
logger: false,
|
||||||
|
connectionTimeout: 15000,
|
||||||
|
greetingTimeout: 10000,
|
||||||
|
socketTimeout: 20000,
|
||||||
|
...options
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function smtpTransport(account) {
|
||||||
|
const isOAuth = account.authMethod === 'oauth2';
|
||||||
|
const auth = isOAuth
|
||||||
|
? {
|
||||||
|
type: 'OAuth2',
|
||||||
|
user: account.email,
|
||||||
|
accessToken: await oauthTokenManager.getAccessToken(account),
|
||||||
|
expires: account.oauthAccessTokenExpiresAt
|
||||||
|
}
|
||||||
|
: { user: account.email, pass: account.password };
|
||||||
|
const secure = Boolean(account.smtpSecure);
|
||||||
|
return createTransport({
|
||||||
|
host: account.smtpHost,
|
||||||
|
port: account.smtpPort,
|
||||||
|
secure,
|
||||||
|
requireTLS: !secure,
|
||||||
|
auth,
|
||||||
|
tls: { rejectUnauthorized: true, servername: account.smtpHost },
|
||||||
|
connectionTimeout: 15000,
|
||||||
|
greetingTimeout: 10000,
|
||||||
|
socketTimeout: 20000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({ imapClient, smtpTransport });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createMailConnections };
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
function isConnectivityFailure(error) {
|
||||||
|
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
|
||||||
|
for (let current = error; current; current = current.cause) {
|
||||||
|
if (networkCodes.has(current.code)) return true;
|
||||||
|
if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { isConnectivityFailure };
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
function createFolderService({ customFolderPrefix = 'Folder:', isReservedFolderName = () => false } = {}) {
|
||||||
|
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
|
||||||
|
const mailboxes = await client.list();
|
||||||
|
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
|
||||||
|
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
|
||||||
|
if (match) return match.path;
|
||||||
|
if (!createName) return null;
|
||||||
|
return (await client.mailboxCreate(createName)).path;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findSentMailbox(client, createIfMissing = false) {
|
||||||
|
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listCustomFolders(client) {
|
||||||
|
return (await client.list())
|
||||||
|
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
|
||||||
|
mailbox.path.toUpperCase() !== 'INBOX' &&
|
||||||
|
!isReservedFolderName(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
|
||||||
|
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
|
||||||
|
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
|
||||||
|
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: customFolderPrefix + mailbox.path }))
|
||||||
|
.sort((a, b) => a.path.localeCompare(b.path));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function folderPath(client, folder, createIfMissing = false) {
|
||||||
|
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
|
||||||
|
const definitions = {
|
||||||
|
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
|
||||||
|
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
|
||||||
|
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
|
||||||
|
};
|
||||||
|
const definition = definitions[folder];
|
||||||
|
if (!definition && typeof folder === 'string' && folder.startsWith(customFolderPrefix)) {
|
||||||
|
const path = folder.slice(customFolderPrefix.length);
|
||||||
|
const match = (await client.list()).find(mailbox => mailbox.path === path);
|
||||||
|
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
|
||||||
|
return match.path;
|
||||||
|
}
|
||||||
|
if (!definition) throw new Error('This folder is not available on the mail server.');
|
||||||
|
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { findSpecialMailbox, findSentMailbox, folderPath, listCustomFolders };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createFolderService };
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
function createIdleWatcherManager({
|
||||||
|
readAccountStore,
|
||||||
|
readAccount,
|
||||||
|
imapClient,
|
||||||
|
backgroundSyncGenerations,
|
||||||
|
concurrency = 2,
|
||||||
|
logError = (...args) => console.error(...args),
|
||||||
|
wait = delay => new Promise(resolve => {
|
||||||
|
const timer = setTimeout(resolve, delay);
|
||||||
|
timer.unref();
|
||||||
|
})
|
||||||
|
}) {
|
||||||
|
const idleWatchers = new Map();
|
||||||
|
let requestSync = () => {};
|
||||||
|
|
||||||
|
function setRequestBackgroundSync(callback) {
|
||||||
|
requestSync = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopIdleWatcher(accountId) {
|
||||||
|
const watcher = idleWatchers.get(accountId);
|
||||||
|
if (!watcher) return;
|
||||||
|
watcher.stopped = true;
|
||||||
|
watcher.client?.close();
|
||||||
|
idleWatchers.delete(accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startIdleWatcher(account) {
|
||||||
|
if (idleWatchers.has(account.id)) return;
|
||||||
|
const watcher = {
|
||||||
|
generation: backgroundSyncGenerations.get(account.id) || 0,
|
||||||
|
stopped: false,
|
||||||
|
client: null
|
||||||
|
};
|
||||||
|
idleWatchers.set(account.id, watcher);
|
||||||
|
void runIdleWatcher(account.id, watcher).catch(error => {
|
||||||
|
logError(`IMAP IDLE watcher failed for ${account.email}:`, error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runIdleWatcher(accountId, watcher) {
|
||||||
|
let failures = 0;
|
||||||
|
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
|
||||||
|
let client;
|
||||||
|
try {
|
||||||
|
const account = await readAccount(accountId);
|
||||||
|
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
client = await imapClient(account, {
|
||||||
|
autoIdleDelay: 10_000,
|
||||||
|
maxIdleTime: 25 * 60 * 1000,
|
||||||
|
socketTimeout: 30 * 60 * 1000
|
||||||
|
});
|
||||||
|
watcher.client = client;
|
||||||
|
let signalDisconnected;
|
||||||
|
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
|
||||||
|
client.on('exists', event => {
|
||||||
|
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestSync();
|
||||||
|
});
|
||||||
|
client.on('flags', event => {
|
||||||
|
if (event.path.toLowerCase() === 'inbox') requestSync();
|
||||||
|
});
|
||||||
|
client.on('error', error => {
|
||||||
|
if (!watcher.stopped) logError(`IMAP IDLE connection failed for ${account.email}:`, error);
|
||||||
|
signalDisconnected();
|
||||||
|
});
|
||||||
|
client.once('close', signalDisconnected);
|
||||||
|
await client.connect();
|
||||||
|
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
await client.mailboxOpen('INBOX', { readOnly: true });
|
||||||
|
const connectedAt = Date.now();
|
||||||
|
await disconnected;
|
||||||
|
if (Date.now() - connectedAt > 60_000) failures = 0;
|
||||||
|
} catch (error) {
|
||||||
|
if (!watcher.stopped) logError(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
|
||||||
|
} finally {
|
||||||
|
if (watcher.client === client) watcher.client = null;
|
||||||
|
if (client?.usable) await client.logout().catch(() => client.close());
|
||||||
|
else client?.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
|
||||||
|
failures += 1;
|
||||||
|
await wait(retryDelay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reconcileIdleWatchers() {
|
||||||
|
const store = (await readAccountStore()) || { accounts: [] };
|
||||||
|
const desiredAccounts = store.accounts.slice(0, concurrency);
|
||||||
|
const desiredIds = new Set(desiredAccounts.map(account => account.id));
|
||||||
|
for (const [accountId, watcher] of idleWatchers) {
|
||||||
|
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
|
||||||
|
stopIdleWatcher(accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const account of desiredAccounts) startIdleWatcher(account);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopAll() {
|
||||||
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { reconcileIdleWatchers, setRequestBackgroundSync, stopAll, stopIdleWatcher };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createIdleWatcherManager };
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
function createOAuthTokenManager({ oauth2Service, persistTokens, now = Date.now }) {
|
||||||
|
const refreshOperations = new Map();
|
||||||
|
|
||||||
|
async function getAccessToken(account) {
|
||||||
|
if (account?.authMethod !== 'oauth2') throw new Error('This account does not use OAuth2.');
|
||||||
|
if (account.oauthAccessToken && Number(account.oauthAccessTokenExpiresAt) > now() + 60_000) {
|
||||||
|
return account.oauthAccessToken;
|
||||||
|
}
|
||||||
|
if (!account.oauthRefreshToken) {
|
||||||
|
throw new Error('Reconnect this OAuth2 account to continue.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = String(account.id || `${account.oauthProvider}:${account.email}`);
|
||||||
|
let pending = refreshOperations.get(key);
|
||||||
|
if (!pending) {
|
||||||
|
pending = (async () => {
|
||||||
|
const tokens = await oauth2Service.refresh(account.oauthProvider, account.oauthRefreshToken);
|
||||||
|
await persistTokens(account.id, tokens);
|
||||||
|
return tokens;
|
||||||
|
})();
|
||||||
|
refreshOperations.set(key, pending);
|
||||||
|
pending.finally(() => {
|
||||||
|
if (refreshOperations.get(key) === pending) refreshOperations.delete(key);
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
const tokens = await pending;
|
||||||
|
Object.assign(account, tokens);
|
||||||
|
return tokens.oauthAccessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({ getAccessToken });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createOAuthTokenManager };
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
const { createHash, randomBytes, timingSafeEqual } = require('node:crypto');
|
||||||
|
const http = require('node:http');
|
||||||
|
|
||||||
|
const GOOGLE_SCOPE = 'https://mail.google.com/';
|
||||||
|
const MICROSOFT_SCOPES = [
|
||||||
|
'offline_access',
|
||||||
|
'https://outlook.office.com/IMAP.AccessAsUser.All',
|
||||||
|
'https://outlook.office.com/SMTP.Send'
|
||||||
|
].join(' ');
|
||||||
|
|
||||||
|
function loadOAuthProviderConfig(environment = process.env) {
|
||||||
|
const googleClientId = String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_ID || '').trim();
|
||||||
|
const microsoftClientId = String(environment.EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID || '').trim();
|
||||||
|
const microsoftTenant = String(environment.EP_MAIL_MICROSOFT_OAUTH_TENANT_ID || 'common').trim();
|
||||||
|
if (microsoftTenant && !/^(?:common|organizations|consumers|[a-f0-9-]{36})$/i.test(microsoftTenant)) {
|
||||||
|
throw new Error('The Microsoft OAuth tenant ID is invalid.');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(googleClientId ? {
|
||||||
|
google: {
|
||||||
|
clientId: googleClientId,
|
||||||
|
clientSecret: String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET || '').trim(),
|
||||||
|
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
|
||||||
|
tokenEndpoint: 'https://oauth2.googleapis.com/token',
|
||||||
|
scope: GOOGLE_SCOPE,
|
||||||
|
redirectHost: 'localhost'
|
||||||
|
}
|
||||||
|
} : {}),
|
||||||
|
...(microsoftClientId ? {
|
||||||
|
microsoft: {
|
||||||
|
clientId: microsoftClientId,
|
||||||
|
tenant: microsoftTenant || 'common',
|
||||||
|
authorizationEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/authorize`,
|
||||||
|
tokenEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/token`,
|
||||||
|
scope: MICROSOFT_SCOPES,
|
||||||
|
redirectHost: 'localhost'
|
||||||
|
}
|
||||||
|
} : {})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createOAuth2Service({
|
||||||
|
providers,
|
||||||
|
openExternal,
|
||||||
|
fetchImpl = globalThis.fetch,
|
||||||
|
createServer = http.createServer,
|
||||||
|
timeoutMs = 3 * 60 * 1000
|
||||||
|
}) {
|
||||||
|
function listProviders() {
|
||||||
|
return [
|
||||||
|
{ id: 'google', label: 'Google', configured: Boolean(providers.google?.clientId) },
|
||||||
|
{ id: 'microsoft', label: 'Microsoft', configured: Boolean(providers.microsoft?.clientId) }
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function providerConfig(provider) {
|
||||||
|
const config = providers[provider];
|
||||||
|
if (!['google', 'microsoft'].includes(provider) || !config?.clientId) {
|
||||||
|
throw new Error(`OAuth2 sign-in for ${provider} is not configured on this desktop build.`);
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestTokens(config, parameters) {
|
||||||
|
const body = new URLSearchParams({ client_id: config.clientId, ...parameters });
|
||||||
|
if (config.clientSecret) body.set('client_secret', config.clientSecret);
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetchImpl(config.tokenEndpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||||
|
body,
|
||||||
|
signal: AbortSignal.timeout(20_000),
|
||||||
|
redirect: 'error'
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new Error('Could not contact the OAuth2 provider. Check your network and try again.');
|
||||||
|
}
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
const detail = String(data.error_description || data.error || '').slice(0, 240).replace(/\s+/g, ' ');
|
||||||
|
throw new Error(detail ? `OAuth2 sign-in failed: ${detail}` : 'OAuth2 sign-in failed. Try again.');
|
||||||
|
}
|
||||||
|
if (typeof data.access_token !== 'string' || !data.access_token || !Number.isFinite(Number(data.expires_in))) {
|
||||||
|
throw new Error('The OAuth2 provider returned an invalid token response.');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
oauthAccessToken: data.access_token,
|
||||||
|
oauthRefreshToken: typeof data.refresh_token === 'string' && data.refresh_token
|
||||||
|
? data.refresh_token : parameters.refresh_token || '',
|
||||||
|
oauthAccessTokenExpiresAt: Date.now() + Math.max(0, Number(data.expires_in)) * 1000
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authorize(provider, email) {
|
||||||
|
const config = providerConfig(provider);
|
||||||
|
if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
||||||
|
throw new Error('Enter a valid email address before authorizing OAuth2.');
|
||||||
|
}
|
||||||
|
if (typeof openExternal !== 'function' || typeof fetchImpl !== 'function') {
|
||||||
|
throw new Error('Desktop OAuth2 sign-in is unavailable.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = randomBytes(32).toString('base64url');
|
||||||
|
const verifier = randomBytes(48).toString('base64url');
|
||||||
|
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
||||||
|
let settleCallback;
|
||||||
|
let callbackComplete = false;
|
||||||
|
const callback = new Promise((resolve, reject) => {
|
||||||
|
settleCallback = { resolve, reject };
|
||||||
|
});
|
||||||
|
callback.catch(() => {});
|
||||||
|
const server = createServer((request, response) => {
|
||||||
|
if (request.method !== 'GET') {
|
||||||
|
response.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' }).end('Method not allowed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const callbackUrl = new URL(request.url || '/', 'http://localhost');
|
||||||
|
if (callbackUrl.pathname !== '/') {
|
||||||
|
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const returnedState = callbackUrl.searchParams.get('state') || '';
|
||||||
|
const expected = Buffer.from(state);
|
||||||
|
const received = Buffer.from(returnedState);
|
||||||
|
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
|
||||||
|
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('OAuth2 state validation failed. You can close this window.');
|
||||||
|
if (!callbackComplete) {
|
||||||
|
callbackComplete = true;
|
||||||
|
settleCallback.reject(new Error('OAuth2 state validation failed. Please try again.'));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const error = callbackUrl.searchParams.get('error');
|
||||||
|
if (error) {
|
||||||
|
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('Sign-in was not completed. You can close this window.');
|
||||||
|
if (!callbackComplete) {
|
||||||
|
callbackComplete = true;
|
||||||
|
settleCallback.reject(new Error('OAuth2 authorization was cancelled or denied.'));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const code = callbackUrl.searchParams.get('code');
|
||||||
|
if (!code) {
|
||||||
|
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('The authorization response was incomplete. You can close this window.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
||||||
|
.end('<!doctype html><title>ep-mail</title><p>Sign-in complete. You may close this browser window and return to ep-mail.</p>');
|
||||||
|
if (!callbackComplete) {
|
||||||
|
callbackComplete = true;
|
||||||
|
settleCallback.resolve(code);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let timeout;
|
||||||
|
try {
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
server.once('error', reject);
|
||||||
|
server.listen(0, 'localhost', resolve);
|
||||||
|
});
|
||||||
|
const port = server.address().port;
|
||||||
|
const redirectUri = `http://${config.redirectHost}:${port}`;
|
||||||
|
const authorizationUrl = new URL(config.authorizationEndpoint);
|
||||||
|
authorizationUrl.search = new URLSearchParams({
|
||||||
|
client_id: config.clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
response_type: 'code',
|
||||||
|
response_mode: 'query',
|
||||||
|
scope: config.scope,
|
||||||
|
state,
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: 'S256',
|
||||||
|
login_hint: email,
|
||||||
|
...(provider === 'google' ? { access_type: 'offline', prompt: 'consent' } : {})
|
||||||
|
}).toString();
|
||||||
|
timeout = setTimeout(() => {
|
||||||
|
if (!callbackComplete) {
|
||||||
|
callbackComplete = true;
|
||||||
|
settleCallback.reject(new Error('OAuth2 sign-in timed out. Try again.'));
|
||||||
|
}
|
||||||
|
}, timeoutMs);
|
||||||
|
await openExternal(authorizationUrl.href);
|
||||||
|
const code = await callback;
|
||||||
|
return await requestTokens(config, {
|
||||||
|
grant_type: 'authorization_code',
|
||||||
|
code,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: verifier,
|
||||||
|
scope: config.scope
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
await new Promise(resolve => server.close(() => resolve()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh(provider, refreshToken) {
|
||||||
|
const config = providerConfig(provider);
|
||||||
|
if (typeof refreshToken !== 'string' || !refreshToken) {
|
||||||
|
throw new Error(`Reconnect this ${provider === 'google' ? 'Google' : 'Microsoft'} account to continue.`);
|
||||||
|
}
|
||||||
|
return requestTokens(config, {
|
||||||
|
grant_type: 'refresh_token',
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
scope: config.scope
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({ listProviders, authorize, refresh });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createOAuth2Service, loadOAuthProviderConfig };
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
const { randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
|
function applyQueuedActionToCache(account, input) {
|
||||||
|
const folder = String(input.folder || 'Inbox');
|
||||||
|
const cache = account.mailCache?.[folder];
|
||||||
|
if (!cache) return;
|
||||||
|
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
|
||||||
|
if (index < 0) return;
|
||||||
|
const [message] = cache.splice(index, 1);
|
||||||
|
if (input.action === 'star' || input.action === 'unread') {
|
||||||
|
message[input.action] = Boolean(input.enabled);
|
||||||
|
cache.splice(index, 0, message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
|
||||||
|
if (!target) {
|
||||||
|
cache.splice(index, 0, message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
message.sourceFolder = target;
|
||||||
|
message.archived = target === 'Archive';
|
||||||
|
message.deleted = target === 'Trash';
|
||||||
|
account.mailCache[target] = account.mailCache[target] || [];
|
||||||
|
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMailOutboxService({
|
||||||
|
sendMailNow,
|
||||||
|
applyMessageAction,
|
||||||
|
updateAccountStore,
|
||||||
|
isConnectivityFailure,
|
||||||
|
createId = randomUUID,
|
||||||
|
now = Date.now,
|
||||||
|
logError = (...args) => console.error(...args)
|
||||||
|
}) {
|
||||||
|
async function flushMailOutbox(account) {
|
||||||
|
const operations = [...(account.mailOutbox || [])];
|
||||||
|
for (const operation of operations) {
|
||||||
|
try {
|
||||||
|
if (operation.type === 'send') await sendMailNow(account, operation.data);
|
||||||
|
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
|
||||||
|
else throw new Error('Unsupported queued mail operation.');
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (isConnectivityFailure(error)) break;
|
||||||
|
logError(`Could not complete queued mail operation ${operation.id}:`, error);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function queueMessageAction(account, input) {
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
saved.mailOutbox = saved.mailOutbox || [];
|
||||||
|
saved.mailOutbox = saved.mailOutbox.filter(item => !(item.type === 'action' &&
|
||||||
|
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
|
||||||
|
saved.mailOutbox.push({ id: createId(), type: 'action', data: input, createdAt: now() });
|
||||||
|
applyQueuedActionToCache(saved, input);
|
||||||
|
});
|
||||||
|
return { ok: true, queued: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { flushMailOutbox, queueMessageAction };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { applyQueuedActionToCache, createMailOutboxService };
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
function createMailReader({
|
||||||
|
imapClient,
|
||||||
|
folderPath,
|
||||||
|
toUiMessage,
|
||||||
|
cacheMailboxMessages,
|
||||||
|
fetchSnoozedMailbox,
|
||||||
|
filterMailboxMessages
|
||||||
|
}) {
|
||||||
|
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
||||||
|
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const mailboxPath = await folderPath(client, folder);
|
||||||
|
if (!mailboxPath) return { messages: [], total: 0 };
|
||||||
|
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
|
||||||
|
const snoozed = new Set((account.snoozedMessages || [])
|
||||||
|
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
|
||||||
|
.map(item => Number(item.uid)));
|
||||||
|
if (Object.values(filters).some(value => value && value !== false)) {
|
||||||
|
const searchStart = Math.max(1, mailbox.exists - 4999);
|
||||||
|
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
|
||||||
|
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||||
|
}) : [];
|
||||||
|
const all = [];
|
||||||
|
for (const item of fetched) {
|
||||||
|
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||||
|
const message = await toUiMessage(item, folder);
|
||||||
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||||
|
all.push(message);
|
||||||
|
}
|
||||||
|
await cacheMailboxMessages(account.id, folder, all);
|
||||||
|
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
|
||||||
|
const start = Math.max(0, Number(offset) || 0);
|
||||||
|
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||||
|
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
|
||||||
|
}
|
||||||
|
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
|
||||||
|
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
|
||||||
|
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
|
||||||
|
const fetched = await client.fetchAll(`${first}:${end}`, {
|
||||||
|
uid: true,
|
||||||
|
envelope: true,
|
||||||
|
flags: true,
|
||||||
|
internalDate: true,
|
||||||
|
source: true
|
||||||
|
});
|
||||||
|
const messages = [];
|
||||||
|
for (const item of fetched.reverse()) {
|
||||||
|
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||||
|
const message = await toUiMessage(item, folder);
|
||||||
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||||
|
messages.push(message);
|
||||||
|
}
|
||||||
|
await cacheMailboxMessages(account.id, folder, messages);
|
||||||
|
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { fetchMailbox };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createMailReader };
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
const { randomUUID } = require('node:crypto');
|
||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs');
|
||||||
|
|
||||||
|
function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) {
|
||||||
|
async function sendMailNow(account, message) {
|
||||||
|
const to = String(message?.to || '').trim();
|
||||||
|
if (!to) throw new Error('Add at least one recipient.');
|
||||||
|
const attachments = normalizeOutgoingAttachments(message?.attachments);
|
||||||
|
const transport = await smtpTransport(account);
|
||||||
|
const sentMessageId = String(message.messageId || `<${randomUUID()}@ep-mail.local>`);
|
||||||
|
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||||
|
const body = String(message?.text || '').slice(0, 500000);
|
||||||
|
const signature = String(account.signature || '').slice(0, 5000);
|
||||||
|
const messageOptions = {
|
||||||
|
from: { name: fromName, address: account.email },
|
||||||
|
to,
|
||||||
|
cc: String(message.cc || '').trim() || undefined,
|
||||||
|
subject: String(message.subject || '(no subject)').slice(0, 998),
|
||||||
|
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||||
|
messageId: sentMessageId,
|
||||||
|
attachments: attachments.map(file => ({
|
||||||
|
filename: file.filename,
|
||||||
|
contentType: file.contentType,
|
||||||
|
content: file.content
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
|
||||||
|
try {
|
||||||
|
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
|
||||||
|
else await transport.sendMail(messageOptions);
|
||||||
|
} finally {
|
||||||
|
transport.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
let savedToSent = false;
|
||||||
|
const copy = createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
|
||||||
|
try {
|
||||||
|
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const sentPath = await findSentMailbox(client, true);
|
||||||
|
const lock = await client.getMailboxLock(sentPath);
|
||||||
|
try {
|
||||||
|
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
|
||||||
|
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
|
||||||
|
savedToSent = true;
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
|
||||||
|
}
|
||||||
|
return { ok: true, savedToSent };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sendMailNow };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createMailSender };
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
function createSnoozeReminderService({
|
||||||
|
readAccountStore,
|
||||||
|
updateAccountStore,
|
||||||
|
showNotification,
|
||||||
|
sendMailSyncUpdate,
|
||||||
|
now = Date.now,
|
||||||
|
logError = (...args) => console.error(...args)
|
||||||
|
}) {
|
||||||
|
let checkInProgress = false;
|
||||||
|
|
||||||
|
async function checkSnoozeReminders() {
|
||||||
|
if (checkInProgress) return;
|
||||||
|
checkInProgress = true;
|
||||||
|
try {
|
||||||
|
const current = await readAccountStore();
|
||||||
|
if (!current?.accounts.some(account =>
|
||||||
|
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= now())
|
||||||
|
)) return;
|
||||||
|
const due = await updateAccountStore(store => {
|
||||||
|
const reminders = [];
|
||||||
|
for (const account of store.accounts) {
|
||||||
|
const snoozes = account.snoozedMessages || [];
|
||||||
|
const remaining = [];
|
||||||
|
for (const item of snoozes) {
|
||||||
|
if (Number(item.dueAt) <= now()) reminders.push({
|
||||||
|
accountId: account.id,
|
||||||
|
email: account.email,
|
||||||
|
notificationsEnabled: account.notificationsEnabled !== false,
|
||||||
|
...item
|
||||||
|
});
|
||||||
|
else remaining.push(item);
|
||||||
|
}
|
||||||
|
account.snoozedMessages = remaining;
|
||||||
|
}
|
||||||
|
return reminders;
|
||||||
|
});
|
||||||
|
for (const reminder of due) {
|
||||||
|
if (reminder.notificationsEnabled !== false) showNotification(reminder);
|
||||||
|
sendMailSyncUpdate({
|
||||||
|
accountId: reminder.accountId,
|
||||||
|
snoozeReminder: true,
|
||||||
|
snoozedFolder: reminder.folder,
|
||||||
|
foldersChanged: ['Snoozed', reminder.folder]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logError('Could not process snooze reminders:', error);
|
||||||
|
} finally {
|
||||||
|
checkInProgress = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { checkSnoozeReminders };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createSnoozeReminderService };
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
function createBackgroundSyncCoordinator({
|
||||||
|
readAccountStore,
|
||||||
|
syncAccountMailboxes,
|
||||||
|
backgroundSyncGenerations,
|
||||||
|
backgroundSyncFailures,
|
||||||
|
lastBackgroundSyncAt,
|
||||||
|
flagSnapshots,
|
||||||
|
reconcileIdleWatchers,
|
||||||
|
sendMailSyncUpdate,
|
||||||
|
showNewMailNotification,
|
||||||
|
concurrency = 2,
|
||||||
|
retryIntervalMs = 2 * 60 * 1000,
|
||||||
|
now = Date.now,
|
||||||
|
logError = (...args) => console.error(...args)
|
||||||
|
}) {
|
||||||
|
let backgroundSyncInProgress = false;
|
||||||
|
let backgroundSyncRequested = false;
|
||||||
|
|
||||||
|
async function syncAccountWithBackoff(account, periodicOnly = false) {
|
||||||
|
if (periodicOnly) {
|
||||||
|
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
|
||||||
|
if (now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
|
||||||
|
}
|
||||||
|
const failure = backgroundSyncFailures.get(account.id);
|
||||||
|
if (failure && now() < failure.retryAt) return;
|
||||||
|
lastBackgroundSyncAt.set(account.id, now());
|
||||||
|
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||||
|
try {
|
||||||
|
const result = await syncAccountMailboxes(account);
|
||||||
|
if (backgroundSyncGenerations.get(account.id) !== generation) return;
|
||||||
|
backgroundSyncFailures.delete(account.id);
|
||||||
|
if (result.newCount || result.changedFolders.length) {
|
||||||
|
const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders };
|
||||||
|
sendMailSyncUpdate(update);
|
||||||
|
showNewMailNotification(account, result.newCount);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const attempts = (failure?.attempts || 0) + 1;
|
||||||
|
const retryDelay = Math.min(30 * 60 * 1000, retryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
||||||
|
backgroundSyncFailures.set(account.id, { attempts, retryAt: now() + retryDelay });
|
||||||
|
logError(`Background mail sync failed for ${account.email}:`, error);
|
||||||
|
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runBackgroundSync(periodicOnly = false) {
|
||||||
|
if (backgroundSyncInProgress) {
|
||||||
|
if (!periodicOnly) backgroundSyncRequested = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
backgroundSyncInProgress = true;
|
||||||
|
let onlyDueAccounts = periodicOnly;
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
backgroundSyncRequested = false;
|
||||||
|
const store = (await readAccountStore()) || { accounts: [] };
|
||||||
|
for (let index = 0; index < store.accounts.length; index += concurrency) {
|
||||||
|
await Promise.all(store.accounts.slice(index, index + concurrency)
|
||||||
|
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
|
||||||
|
}
|
||||||
|
if (backgroundSyncRequested) onlyDueAccounts = false;
|
||||||
|
} while (backgroundSyncRequested);
|
||||||
|
} finally {
|
||||||
|
backgroundSyncInProgress = false;
|
||||||
|
if (backgroundSyncRequested) void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestBackgroundSync(accountId = null, force = false) {
|
||||||
|
if (accountId) {
|
||||||
|
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
|
||||||
|
backgroundSyncFailures.delete(accountId);
|
||||||
|
flagSnapshots.delete(accountId);
|
||||||
|
}
|
||||||
|
if (force) {
|
||||||
|
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
|
||||||
|
}
|
||||||
|
void reconcileIdleWatchers().catch(error => logError('Could not reconcile IMAP IDLE watchers:', error));
|
||||||
|
if (backgroundSyncInProgress) {
|
||||||
|
if (accountId || force) backgroundSyncRequested = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
backgroundSyncRequested = true;
|
||||||
|
void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
|
||||||
|
}
|
||||||
|
|
||||||
|
return { requestBackgroundSync, runBackgroundSync, syncAccountWithBackoff };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createBackgroundSyncCoordinator };
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
function backgroundFolderLabel(mailbox) {
|
||||||
|
const specialUse = String(mailbox.specialUse || '').toLowerCase();
|
||||||
|
if (specialUse === '\\sent') return 'Sent';
|
||||||
|
if (specialUse === '\\archive') return 'Archive';
|
||||||
|
if (specialUse === '\\trash') return 'Trash';
|
||||||
|
if (mailbox.path.toLowerCase() === 'inbox') return 'Inbox';
|
||||||
|
const finalPart = mailbox.path.toLowerCase().split(/[./]/).pop();
|
||||||
|
if (['sent', 'sent items', 'sent mail', 'sent messages'].includes(finalPart)) return 'Sent';
|
||||||
|
if (['archive', 'archives', 'all mail'].includes(finalPart)) return 'Archive';
|
||||||
|
if (['trash', 'deleted items', 'deleted messages'].includes(finalPart)) return 'Trash';
|
||||||
|
return mailbox.path;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMailboxSyncService({
|
||||||
|
imapClient,
|
||||||
|
flushMailOutbox,
|
||||||
|
updateAccountStore,
|
||||||
|
saveAccountSyncState,
|
||||||
|
backgroundSyncGenerations,
|
||||||
|
flagSnapshots,
|
||||||
|
findSpecialMailbox,
|
||||||
|
folderPath,
|
||||||
|
logError = (...args) => console.error(...args)
|
||||||
|
}) {
|
||||||
|
async function syncAccountMailboxes(account) {
|
||||||
|
await flushMailOutbox(account);
|
||||||
|
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||||
|
const client = await imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const mailboxes = await client.list();
|
||||||
|
const states = { ...(account.syncState?.folders || {}) };
|
||||||
|
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
|
||||||
|
let inboxNewCount = 0;
|
||||||
|
const changedFolders = [];
|
||||||
|
const ruleActions = [];
|
||||||
|
|
||||||
|
for (const listedMailbox of mailboxes) {
|
||||||
|
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
|
||||||
|
const folder = listedMailbox.path;
|
||||||
|
const label = backgroundFolderLabel(listedMailbox);
|
||||||
|
const uidValidity = String(mailbox.uidValidity);
|
||||||
|
const uidCeiling = Math.max(0, Number(mailbox.uidNext) - 1);
|
||||||
|
const oldState = states[folder];
|
||||||
|
const cursorIsValid = oldState?.uidValidity === uidValidity && Number.isInteger(oldState.lastUid);
|
||||||
|
|
||||||
|
if (!cursorIsValid) {
|
||||||
|
states[folder] = {
|
||||||
|
uidValidity,
|
||||||
|
lastUid: uidCeiling,
|
||||||
|
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : null
|
||||||
|
};
|
||||||
|
if (!mailbox.highestModseq) {
|
||||||
|
const initialFlags = await client.fetchAll('1:*', { uid: true, flags: true });
|
||||||
|
accountSnapshots.set(folder, {
|
||||||
|
uidValidity,
|
||||||
|
flags: new Map(initialFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousUid = Number(oldState.lastUid);
|
||||||
|
const added = uidCeiling > previousUid
|
||||||
|
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
|
||||||
|
: [];
|
||||||
|
if (label === 'Inbox' && account.rules?.length) {
|
||||||
|
for (const item of added) {
|
||||||
|
const rule = account.rules.find(candidate => {
|
||||||
|
const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase();
|
||||||
|
const subject = String(item.envelope?.subject || '').toLowerCase();
|
||||||
|
return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) &&
|
||||||
|
(!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase()));
|
||||||
|
});
|
||||||
|
if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let flagsChanged = false;
|
||||||
|
|
||||||
|
if (mailbox.highestModseq && oldState.highestModseq) {
|
||||||
|
const changed = await client.fetchAll('1:*', { uid: true, flags: true, modseq: true }, {
|
||||||
|
uid: true,
|
||||||
|
changedSince: BigInt(oldState.highestModseq)
|
||||||
|
});
|
||||||
|
flagsChanged = changed.some(item => Number(item.uid) <= previousUid);
|
||||||
|
} else if (!mailbox.highestModseq) {
|
||||||
|
const currentFlags = await client.fetchAll('1:*', { uid: true, flags: true });
|
||||||
|
const nextSnapshot = new Map(currentFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]));
|
||||||
|
const previousSnapshot = accountSnapshots.get(folder);
|
||||||
|
if (previousSnapshot?.uidValidity === uidValidity) {
|
||||||
|
flagsChanged = [...previousSnapshot.flags].some(([uid, flags]) => uid <= previousUid && nextSnapshot.get(uid) !== flags);
|
||||||
|
}
|
||||||
|
accountSnapshots.set(folder, { uidValidity, flags: nextSnapshot });
|
||||||
|
}
|
||||||
|
|
||||||
|
states[folder] = {
|
||||||
|
uidValidity,
|
||||||
|
lastUid: Math.max(previousUid, uidCeiling),
|
||||||
|
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : oldState.highestModseq || null
|
||||||
|
};
|
||||||
|
if (added.length && label === 'Inbox') inboxNewCount += added.length;
|
||||||
|
if (added.length || flagsChanged) changedFolders.push(label);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ruleLabels = [];
|
||||||
|
for (const { uid, folder, rule } of ruleActions) {
|
||||||
|
const lock = await client.getMailboxLock(folder);
|
||||||
|
try {
|
||||||
|
if (rule.action === 'flag') {
|
||||||
|
await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
|
||||||
|
} else if (rule.action === 'archive' || rule.action === 'move') {
|
||||||
|
const target = rule.action === 'archive'
|
||||||
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
||||||
|
: await folderPath(client, rule.value);
|
||||||
|
if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`);
|
||||||
|
if (target !== folder) await client.messageMove(uid, target, { uid: true });
|
||||||
|
changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target }));
|
||||||
|
} else if (rule.action === 'label') {
|
||||||
|
ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logError(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error);
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ruleLabels.length) {
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) return;
|
||||||
|
saved.ruleLabels = saved.ruleLabels || {};
|
||||||
|
for (const { key, label } of ruleLabels) {
|
||||||
|
saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const saved = await saveAccountSyncState(account.id, generation, states);
|
||||||
|
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
|
||||||
|
return { newCount: 0, changedFolders: [] };
|
||||||
|
}
|
||||||
|
flagSnapshots.set(account.id, accountSnapshots);
|
||||||
|
return { newCount: inboxNewCount, changedFolders: [...new Set(changedFolders)] };
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { syncAccountMailboxes };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { backgroundFolderLabel, createMailboxSyncService };
|
||||||
+325
-1462
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,277 @@
|
|||||||
|
const openpgp = require('openpgp');
|
||||||
|
|
||||||
|
const MAX_KEY_LENGTH = 200000;
|
||||||
|
const MAX_RESPONSE_BYTES = 600000;
|
||||||
|
const REQUEST_TIMEOUT_MS = 15000;
|
||||||
|
const MAX_CUSTOM_SERVERS = 10;
|
||||||
|
|
||||||
|
const BUILTIN_SERVERS = [
|
||||||
|
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
||||||
|
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
|
||||||
|
];
|
||||||
|
|
||||||
|
function normalizeBaseUrl(value) {
|
||||||
|
const raw = String(value || '').trim();
|
||||||
|
if (raw.length > 300) throw new Error('The key server URL is too long.');
|
||||||
|
let url;
|
||||||
|
try {
|
||||||
|
url = new URL(raw);
|
||||||
|
} catch {
|
||||||
|
throw new Error('Enter a valid HTTPS key server URL.');
|
||||||
|
}
|
||||||
|
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
|
||||||
|
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
|
||||||
|
}
|
||||||
|
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCustomServer(input) {
|
||||||
|
const name = String(input?.name || '').trim().slice(0, 60);
|
||||||
|
const protocol = input?.protocol;
|
||||||
|
if (!name) throw new Error('Enter a name for the key server.');
|
||||||
|
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
|
||||||
|
return {
|
||||||
|
id: String(input?.id || ''),
|
||||||
|
name,
|
||||||
|
url: normalizeBaseUrl(input?.url),
|
||||||
|
protocol,
|
||||||
|
builtin: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function listServers(customServers = [], enabledServerIds = []) {
|
||||||
|
const enabled = new Set(enabledServerIds);
|
||||||
|
return [
|
||||||
|
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
||||||
|
...customServers.map(server => {
|
||||||
|
const normalized = normalizeCustomServer(server);
|
||||||
|
return { ...normalized, enabled: enabled.has(normalized.id) };
|
||||||
|
})
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateEmail(value) {
|
||||||
|
const email = String(value || '').trim();
|
||||||
|
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseUrl(server) {
|
||||||
|
return new URL(normalizeBaseUrl(server.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
function endpoint(server, path) {
|
||||||
|
return new URL(path, baseUrl(server));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readResponseText(response) {
|
||||||
|
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
|
||||||
|
if (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
|
||||||
|
if (!response.body) return '';
|
||||||
|
const chunks = [];
|
||||||
|
let length = 0;
|
||||||
|
for await (const chunk of response.body) {
|
||||||
|
const bytes = Buffer.from(chunk);
|
||||||
|
length += bytes.length;
|
||||||
|
if (length > MAX_RESPONSE_BYTES) {
|
||||||
|
throw new Error('The key server response is too large.');
|
||||||
|
}
|
||||||
|
chunks.push(bytes);
|
||||||
|
}
|
||||||
|
return Buffer.concat(chunks, length).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
||||||
|
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
|
||||||
|
|
||||||
|
async function request(server, url, options = {}) {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetchImpl(url, {
|
||||||
|
...options,
|
||||||
|
redirect: 'error',
|
||||||
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Could not reach ${server.name}: ${error.message}`);
|
||||||
|
}
|
||||||
|
const text = await readResponseText(response);
|
||||||
|
return { response, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parsePublicKeys(armored, email) {
|
||||||
|
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
|
||||||
|
throw new Error('The key server returned an invalid or oversized key response.');
|
||||||
|
}
|
||||||
|
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
|
||||||
|
if (!blocks.length) {
|
||||||
|
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
|
||||||
|
throw new Error('The key server response did not contain an OpenPGP public key.');
|
||||||
|
}
|
||||||
|
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
|
||||||
|
const keys = [];
|
||||||
|
const seen = new Set();
|
||||||
|
let validKeyCount = 0;
|
||||||
|
for (const block of blocks) {
|
||||||
|
if (block.length > MAX_KEY_LENGTH) continue;
|
||||||
|
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
|
||||||
|
if (!key) continue;
|
||||||
|
const fingerprint = key.getFingerprint().toUpperCase();
|
||||||
|
if (seen.has(fingerprint)) continue;
|
||||||
|
seen.add(fingerprint);
|
||||||
|
const emails = [...new Set(key.getUserIDs()
|
||||||
|
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
|
||||||
|
.filter(Boolean))];
|
||||||
|
const primary = await key.getPrimaryUser().catch(() => null);
|
||||||
|
if (!primary) continue;
|
||||||
|
validKeyCount += 1;
|
||||||
|
if (email && !emails.includes(email.toLowerCase())) continue;
|
||||||
|
keys.push({
|
||||||
|
fingerprint,
|
||||||
|
name: primary.user.userID?.name || '',
|
||||||
|
emails,
|
||||||
|
armoredKey: key.armor()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lookup(serverInput, emailInput) {
|
||||||
|
const server = normalizeCustomServer(serverInput);
|
||||||
|
const email = validateEmail(emailInput);
|
||||||
|
let url;
|
||||||
|
if (server.protocol === 'vks') {
|
||||||
|
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
|
||||||
|
} else {
|
||||||
|
url = endpoint(server, 'pks/lookup');
|
||||||
|
url.searchParams.set('op', 'get');
|
||||||
|
url.searchParams.set('search', email);
|
||||||
|
}
|
||||||
|
const { response, text } = await request(server, url);
|
||||||
|
if (response.status === 404) return [];
|
||||||
|
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
|
||||||
|
let armored = text;
|
||||||
|
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(text);
|
||||||
|
armored = data.publicKeyArmored || '';
|
||||||
|
} catch {
|
||||||
|
throw new Error(`${server.name} returned an invalid key response.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parsePublicKeys(armored, email);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lookupEnabled(serverInputs, emailInput) {
|
||||||
|
const servers = serverInputs.filter(server => server.enabled === true);
|
||||||
|
if (!servers.length) throw new Error('Enable at least one key server before searching.');
|
||||||
|
const email = validateEmail(emailInput);
|
||||||
|
const lookups = await Promise.all(servers.map(async server => {
|
||||||
|
try {
|
||||||
|
return { server, keys: await lookup(server, email), error: null };
|
||||||
|
} catch (error) {
|
||||||
|
return { server, keys: [], error: error.message };
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
const keysByFingerprint = new Map();
|
||||||
|
for (const result of lookups) {
|
||||||
|
for (const key of result.keys) {
|
||||||
|
const existing = keysByFingerprint.get(key.fingerprint);
|
||||||
|
if (existing) existing.sources.push(result.server.name);
|
||||||
|
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
keys: [...keysByFingerprint.values()],
|
||||||
|
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
|
||||||
|
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
|
||||||
|
id: server.id,
|
||||||
|
name: server.name,
|
||||||
|
message: error
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishVks(server, email, armoredKey, expectedFingerprint) {
|
||||||
|
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||||
|
body: JSON.stringify({ keytext: armoredKey })
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||||
|
let result;
|
||||||
|
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
|
||||||
|
if (String(result.key_fpr || '').toUpperCase() !== expectedFingerprint || !result.token || !result.status || typeof result.status !== 'object') {
|
||||||
|
throw new Error(`${server.name} returned an incomplete or mismatched upload response.`);
|
||||||
|
}
|
||||||
|
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||||
|
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
|
||||||
|
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
|
||||||
|
if (addressStatus !== 'unpublished') {
|
||||||
|
return { uploaded: true, verification: addressStatus || 'unknown' };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||||
|
body: JSON.stringify({ token: result.token, addresses: [email] })
|
||||||
|
});
|
||||||
|
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
|
||||||
|
let verified;
|
||||||
|
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
|
||||||
|
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
|
||||||
|
throw new Error('verification response did not match the uploaded key');
|
||||||
|
}
|
||||||
|
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||||
|
return { uploaded: true, verification: state || 'requested' };
|
||||||
|
} catch (error) {
|
||||||
|
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishHkp(server, armoredKey) {
|
||||||
|
const form = new URLSearchParams({ keytext: armoredKey });
|
||||||
|
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: form.toString()
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||||
|
if (!/upload successful|successfully added|key added/i.test(text)) {
|
||||||
|
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
uploaded: true,
|
||||||
|
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
|
||||||
|
message: text.trim().slice(0, 500)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
|
||||||
|
const server = normalizeCustomServer(serverInput);
|
||||||
|
const email = validateEmail(emailInput);
|
||||||
|
const armoredKey = String(armoredInput || '').trim();
|
||||||
|
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
|
||||||
|
throw new Error('Only a valid public key can be published.');
|
||||||
|
}
|
||||||
|
const keys = await parsePublicKeys(armoredKey, email);
|
||||||
|
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
|
||||||
|
throw new Error('The selected public key does not match the key and email being published.');
|
||||||
|
}
|
||||||
|
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
|
||||||
|
return publishHkp(server, keys[0].armoredKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { lookup, lookupEnabled, publish };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
BUILTIN_SERVERS,
|
||||||
|
MAX_CUSTOM_SERVERS,
|
||||||
|
createKeyServerService,
|
||||||
|
listServers,
|
||||||
|
normalizeBaseUrl,
|
||||||
|
normalizeCustomServer
|
||||||
|
};
|
||||||
@@ -109,7 +109,7 @@ function createKeyStore(storage) {
|
|||||||
name: user.user.userID?.name || '',
|
name: user.user.userID?.name || '',
|
||||||
emails,
|
emails,
|
||||||
trust: 'unknown',
|
trust: 'unknown',
|
||||||
source: ['import', 'message', 'paste'].includes(source) ? source : 'import',
|
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
|
||||||
addedAt: Date.now(),
|
addedAt: Date.now(),
|
||||||
publicKey: key.armor()
|
publicKey: key.armor()
|
||||||
};
|
};
|
||||||
@@ -193,16 +193,43 @@ function createKeyStore(storage) {
|
|||||||
|
|
||||||
async getSettings() {
|
async getSettings() {
|
||||||
const settings = (await read()).settings;
|
const settings = (await read()).settings;
|
||||||
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES };
|
return {
|
||||||
|
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
||||||
|
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
||||||
|
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
||||||
|
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
||||||
|
: []
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async setSettings({ cacheMinutes }) {
|
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
|
||||||
const minutes = Number(cacheMinutes);
|
const minutes = Number(cacheMinutes);
|
||||||
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||||
const data = await read();
|
const data = await read();
|
||||||
data.settings.cacheMinutes = Math.round(minutes);
|
data.settings.cacheMinutes = Math.round(minutes);
|
||||||
|
if (customKeyServers !== undefined) {
|
||||||
|
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
|
||||||
|
throw new Error('You can configure up to 10 valid custom key servers.');
|
||||||
|
}
|
||||||
|
data.settings.customKeyServers = customKeyServers.map(server => ({
|
||||||
|
id: String(server.id || ''),
|
||||||
|
name: String(server.name || '').slice(0, 60),
|
||||||
|
url: String(server.url || '').slice(0, 300),
|
||||||
|
protocol: String(server.protocol || '')
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if (enabledKeyServers !== undefined) {
|
||||||
|
if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
|
||||||
|
throw new Error('Choose no more than 12 valid enabled key servers.');
|
||||||
|
}
|
||||||
|
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
||||||
|
}
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return { cacheMinutes: data.settings.cacheMinutes };
|
return {
|
||||||
|
cacheMinutes: data.settings.cacheMinutes,
|
||||||
|
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
||||||
|
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async list() {
|
async list() {
|
||||||
@@ -278,6 +305,24 @@ function createKeyStore(storage) {
|
|||||||
return entry.privateKey;
|
return entry.privateKey;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
|
||||||
|
requirePassphrase(newPassphrase);
|
||||||
|
const data = await read();
|
||||||
|
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
|
||||||
|
if (keyIndex < 0) throw new Error('That key was not found.');
|
||||||
|
const entry = data.keys[keyIndex];
|
||||||
|
const privateKey = await unlock(entry.privateKey, currentPassphrase);
|
||||||
|
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
|
||||||
|
const updated = {
|
||||||
|
...data,
|
||||||
|
keys: data.keys.map((key, index) => index === keyIndex
|
||||||
|
? { ...key, privateKey: protectedKey.armor() }
|
||||||
|
: key)
|
||||||
|
};
|
||||||
|
await storage.save(updated);
|
||||||
|
return { changed: true };
|
||||||
|
},
|
||||||
|
|
||||||
async exportRevocation(fingerprint, passphrase) {
|
async exportRevocation(fingerprint, passphrase) {
|
||||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error('That key was not found.');
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
|||||||
+18
-3
@@ -1,6 +1,7 @@
|
|||||||
const openpgp = require('openpgp');
|
const openpgp = require('openpgp');
|
||||||
const { simpleParser } = require('mailparser');
|
const { simpleParser } = require('mailparser');
|
||||||
const addressParser = require('nodemailer/lib/addressparser');
|
const addressParser = require('nodemailer/lib/addressparser');
|
||||||
|
const MailComposer = require('nodemailer/lib/mail-composer');
|
||||||
const { randomBytes } = require('node:crypto');
|
const { randomBytes } = require('node:crypto');
|
||||||
|
|
||||||
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
|
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
|
||||||
@@ -131,7 +132,21 @@ function parseAddresses(value) {
|
|||||||
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
|
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
function innerEntity(text) {
|
async function innerEntity(text, attachments) {
|
||||||
|
if (attachments.length) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
new MailComposer({
|
||||||
|
text: String(text || ''),
|
||||||
|
attachments: attachments.map(file => ({
|
||||||
|
filename: file.filename,
|
||||||
|
contentType: file.contentType,
|
||||||
|
content: file.content
|
||||||
|
}))
|
||||||
|
}).compile().build((error, message) => error
|
||||||
|
? reject(error)
|
||||||
|
: resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1')));
|
||||||
|
});
|
||||||
|
}
|
||||||
const body = Buffer.from(String(text || ''), 'utf8');
|
const body = Buffer.from(String(text || ''), 'utf8');
|
||||||
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
|
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
|
||||||
}
|
}
|
||||||
@@ -252,7 +267,7 @@ function createPgpMail({ keyStore, cache }) {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
|
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
|
||||||
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) {
|
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
|
||||||
const toList = parseAddresses(to);
|
const toList = parseAddresses(to);
|
||||||
const ccList = parseAddresses(cc);
|
const ccList = parseAddresses(cc);
|
||||||
if (!toList.length) throw new Error('Add at least one recipient.');
|
if (!toList.length) throw new Error('Add at least one recipient.');
|
||||||
@@ -284,7 +299,7 @@ function createPgpMail({ keyStore, cache }) {
|
|||||||
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
|
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
|
||||||
'MIME-Version: 1.0'
|
'MIME-Version: 1.0'
|
||||||
];
|
];
|
||||||
const inner = innerEntity(text);
|
const inner = await innerEntity(text, attachments);
|
||||||
const mark = boundary();
|
const mark = boundary();
|
||||||
let body;
|
let body;
|
||||||
let contentType;
|
let contentType;
|
||||||
|
|||||||
+9
-1
@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
|||||||
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
||||||
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
||||||
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
||||||
|
listOAuthProviders: () => ipcRenderer.invoke('mail:list-oauth-providers'),
|
||||||
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
||||||
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
|
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
|
||||||
connect: details => ipcRenderer.invoke('mail:connect', details),
|
connect: details => ipcRenderer.invoke('mail:connect', details),
|
||||||
@@ -29,6 +30,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
|||||||
importKey: details => ipcRenderer.invoke('pgp:import', details),
|
importKey: details => ipcRenderer.invoke('pgp:import', details),
|
||||||
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
|
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
|
||||||
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
|
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
|
||||||
|
changePassphrase: details => ipcRenderer.invoke('pgp:change-passphrase', details),
|
||||||
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
|
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
|
||||||
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
|
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
|
||||||
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
|
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
|
||||||
@@ -40,7 +42,13 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
|||||||
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
|
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
|
||||||
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
|
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
|
||||||
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
|
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
|
||||||
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases')
|
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'),
|
||||||
|
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
|
||||||
|
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
|
||||||
|
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
|
||||||
|
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
|
||||||
|
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
|
||||||
|
publishKey: details => ipcRenderer.invoke('pgp:publish-key', details)
|
||||||
},
|
},
|
||||||
davList: () => ipcRenderer.invoke('dav:list'),
|
davList: () => ipcRenderer.invoke('dav:list'),
|
||||||
davConnect: config => ipcRenderer.invoke('dav:connect', config),
|
davConnect: config => ipcRenderer.invoke('dav:connect', config),
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
function createSecureJsonStore({ getFilePath, safeStorage, assertSecureStorage, unavailableMessage }) {
|
||||||
|
if (typeof getFilePath !== 'function') throw new TypeError('A file path provider is required.');
|
||||||
|
if (!safeStorage || typeof safeStorage.encryptStringAsync !== 'function' ||
|
||||||
|
typeof safeStorage.decryptStringAsync !== 'function' ||
|
||||||
|
typeof safeStorage.isAsyncEncryptionAvailable !== 'function') {
|
||||||
|
throw new TypeError('An asynchronous safe storage adapter is required.');
|
||||||
|
}
|
||||||
|
if (typeof assertSecureStorage !== 'function') throw new TypeError('A secure-storage check is required.');
|
||||||
|
|
||||||
|
return {
|
||||||
|
async load() {
|
||||||
|
assertSecureStorage();
|
||||||
|
const encrypted = await fs.readFile(getFilePath());
|
||||||
|
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||||
|
return JSON.parse(result);
|
||||||
|
},
|
||||||
|
|
||||||
|
async save(value) {
|
||||||
|
assertSecureStorage();
|
||||||
|
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error(unavailableMessage);
|
||||||
|
const file = getFilePath();
|
||||||
|
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(value));
|
||||||
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||||
|
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
|
||||||
|
await fs.rename(`${file}.tmp`, file);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createSecureJsonStore };
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
const MAX_DEPTH = 20;
|
||||||
|
const MAX_VALUES = 25_000;
|
||||||
|
const MAX_COLLECTION_ITEMS = 5_000;
|
||||||
|
const MAX_STRING_LENGTH = 1_000_000;
|
||||||
|
const MAX_ARMORED_KEY_LENGTH = 200_000;
|
||||||
|
|
||||||
|
const str = (max = MAX_STRING_LENGTH, options = {}) => ({ type: 'string', max, ...options });
|
||||||
|
const num = options => ({ type: 'number', ...options });
|
||||||
|
const bool = () => ({ type: 'boolean' });
|
||||||
|
const record = (fields, options = {}) => ({ type: 'object', fields, ...options });
|
||||||
|
const array = (item, maxItems = MAX_COLLECTION_ITEMS) => ({ type: 'array', item, maxItems });
|
||||||
|
|
||||||
|
const attachmentFields = {
|
||||||
|
filename: str(255),
|
||||||
|
contentType: str(200),
|
||||||
|
contentBase64: str(Infinity, { required: true })
|
||||||
|
};
|
||||||
|
const ruleFields = {
|
||||||
|
id: str(100),
|
||||||
|
senderContains: str(200),
|
||||||
|
subjectContains: str(200),
|
||||||
|
action: { type: 'enum', values: ['archive', 'move', 'label', 'flag'] },
|
||||||
|
value: str(200)
|
||||||
|
};
|
||||||
|
const davRemoteFields = {
|
||||||
|
accountId: str(256),
|
||||||
|
collectionUrl: str(4096),
|
||||||
|
objectUrl: str(4096),
|
||||||
|
etag: str(1024, { nullable: true }),
|
||||||
|
uid: str(255, { nullable: true })
|
||||||
|
};
|
||||||
|
|
||||||
|
const objectFieldSchemas = {
|
||||||
|
'mail:update-account': [null, {
|
||||||
|
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
||||||
|
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
||||||
|
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
||||||
|
reauthorizeOAuth: bool(),
|
||||||
|
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||||
|
rules: array(record(ruleFields), 50)
|
||||||
|
}],
|
||||||
|
'mail:connect': [{
|
||||||
|
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
||||||
|
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
||||||
|
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
||||||
|
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
|
||||||
|
rules: array(record(ruleFields), 50)
|
||||||
|
}],
|
||||||
|
'mail:sync-folder': [null, null, {
|
||||||
|
folder: str(256), query: str(2000), sender: str(1000), subject: str(1000),
|
||||||
|
after: str(20), before: str(20), hasAttachments: bool()
|
||||||
|
}],
|
||||||
|
'mail:create-folder': [{ name: str(100) }],
|
||||||
|
'mail:save-draft': [{
|
||||||
|
id: str(256), to: str(4000), cc: str(4000), subject: str(998), text: str(500_000),
|
||||||
|
attachments: array(record(attachmentFields))
|
||||||
|
}],
|
||||||
|
'mail:set-snooze': [{
|
||||||
|
uid: num({ integer: true, min: 1 }), folder: str(256), sourceFolder: str(256),
|
||||||
|
dueAt: num({ nullable: true }), subject: str(200)
|
||||||
|
}],
|
||||||
|
'mail:update-message': [{
|
||||||
|
uid: num({ integer: true, min: 1 }), folder: str(256),
|
||||||
|
action: { type: 'enum', values: ['star', 'unread', 'archive', 'delete', 'inbox'] }, enabled: bool()
|
||||||
|
}],
|
||||||
|
'mail:save-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
|
||||||
|
'mail:preview-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
|
||||||
|
'mail:send': [{
|
||||||
|
to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), displayName: str(80),
|
||||||
|
messageId: str(998), attachments: array(record(attachmentFields)),
|
||||||
|
pgp: record({ encrypt: bool(), sign: bool(), passphrase: str(4096, { nullable: true }) }, { nullable: true })
|
||||||
|
}],
|
||||||
|
'pgp:generate': [{ name: str(200), email: str(320), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
|
||||||
|
'pgp:import': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
|
||||||
|
'pgp:change-passphrase': [{ fingerprint: str(64), currentPassphrase: str(4096), newPassphrase: str(4096) }],
|
||||||
|
'pgp:decrypt-message': [{ folder: str(256), uid: num({ integer: true, min: 1 }), passphrase: str(4096, { nullable: true }) }],
|
||||||
|
'pgp:check-send': [{ to: str(4000), cc: str(4000), sign: bool() }],
|
||||||
|
'pgp:add-contact': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), source: { type: 'enum', values: ['import', 'message', 'paste', 'keyserver'] } }],
|
||||||
|
'pgp:set-settings': [{ cacheMinutes: num({ min: 0, max: 1440 }) }],
|
||||||
|
'pgp:set-key-server-enabled': [{ serverId: str(256), enabled: bool() }],
|
||||||
|
'pgp:add-key-server': [{ name: str(60), url: str(300), protocol: { type: 'enum', values: ['hkp', 'vks'] } }],
|
||||||
|
'pgp:find-key': [{ email: str(320) }],
|
||||||
|
'pgp:publish-key': [{ fingerprint: str(64), serverId: str(256) }],
|
||||||
|
'dav:connect': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, serverUrl: str(2048), username: str(1024), password: str(4096) }],
|
||||||
|
'dav:activate': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
|
||||||
|
'dav:remove': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
|
||||||
|
'dav:save-event': [{
|
||||||
|
title: str(120), date: str(20), time: str(20), with: str(4000), place: str(1000), notes: str(5000),
|
||||||
|
_dav: record(davRemoteFields, { nullable: true })
|
||||||
|
}],
|
||||||
|
'dav:delete-event': [davRemoteFields],
|
||||||
|
'dav:save-contact': [{
|
||||||
|
name: str(100), email: str(320), note: str(5000),
|
||||||
|
_dav: record(davRemoteFields, { nullable: true })
|
||||||
|
}],
|
||||||
|
'dav:delete-contact': [davRemoteFields]
|
||||||
|
};
|
||||||
|
|
||||||
|
const positionalEnums = {
|
||||||
|
'pgp:set-trust': { 1: ['unknown', 'trusted', 'verified'] }
|
||||||
|
};
|
||||||
|
const positionalFieldSchemas = {
|
||||||
|
'mail:select-account': { 0: str(256) },
|
||||||
|
'mail:remove-account': { 0: str(256) },
|
||||||
|
'mail:delete-draft': { 0: str(256) },
|
||||||
|
'mail:disconnect': { 0: str(256) },
|
||||||
|
'mail:open-external': { 0: str(2048) },
|
||||||
|
'pgp:export-public': { 0: str(64) },
|
||||||
|
'pgp:export-private': { 0: str(64), 1: str(4096) },
|
||||||
|
'pgp:export-revocation': { 0: str(64), 1: str(4096) },
|
||||||
|
'pgp:delete': { 0: str(64), 1: str(4096) },
|
||||||
|
'pgp:set-trust': { 0: str(64) },
|
||||||
|
'pgp:remove-contact': { 0: str(64) },
|
||||||
|
'pgp:export-contact': { 0: str(64) },
|
||||||
|
'pgp:remove-key-server': { 0: str(256) }
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'attachments', 'pgp']);
|
||||||
|
|
||||||
|
const schemas = {
|
||||||
|
'app:get-version': [],
|
||||||
|
'mail:get-account': [],
|
||||||
|
'mail:list-accounts': [],
|
||||||
|
'mail:list-oauth-providers': [],
|
||||||
|
'mail:select-account': ['string'],
|
||||||
|
'mail:remove-account': ['string'],
|
||||||
|
'mail:update-account': ['string', 'object'],
|
||||||
|
'mail:connect': ['object'],
|
||||||
|
'mail:sync-folder': ['string', 'number?', 'object?'],
|
||||||
|
'mail:list-folders': [],
|
||||||
|
'mail:create-folder': ['object'],
|
||||||
|
'mail:list-drafts': [],
|
||||||
|
'mail:save-draft': ['object'],
|
||||||
|
'mail:delete-draft': ['string'],
|
||||||
|
'mail:set-snooze': ['object'],
|
||||||
|
'mail:update-message': ['object'],
|
||||||
|
'mail:save-attachment': ['object'],
|
||||||
|
'mail:preview-attachment': ['object'],
|
||||||
|
'mail:send': ['object'],
|
||||||
|
'mail:open-external': ['string'],
|
||||||
|
'mail:sync-inbox': [],
|
||||||
|
'mail:disconnect': ['string?'],
|
||||||
|
'pgp:list': [],
|
||||||
|
'pgp:generate': ['object'],
|
||||||
|
'pgp:import': ['object'],
|
||||||
|
'pgp:export-public': ['string'],
|
||||||
|
'pgp:export-private': ['string', 'string'],
|
||||||
|
'pgp:change-passphrase': ['object'],
|
||||||
|
'pgp:export-revocation': ['string', 'string'],
|
||||||
|
'pgp:delete': ['string', 'string'],
|
||||||
|
'pgp:decrypt-message': ['object'],
|
||||||
|
'pgp:check-send': ['object'],
|
||||||
|
'pgp:contacts': [],
|
||||||
|
'pgp:add-contact': ['object'],
|
||||||
|
'pgp:set-trust': ['string', 'string'],
|
||||||
|
'pgp:remove-contact': ['string'],
|
||||||
|
'pgp:export-contact': ['string'],
|
||||||
|
'pgp:get-settings': [],
|
||||||
|
'pgp:set-settings': ['object'],
|
||||||
|
'pgp:key-servers': [],
|
||||||
|
'pgp:set-key-server-enabled': ['object'],
|
||||||
|
'pgp:add-key-server': ['object'],
|
||||||
|
'pgp:remove-key-server': ['string'],
|
||||||
|
'pgp:find-key': ['object'],
|
||||||
|
'pgp:publish-key': ['object'],
|
||||||
|
'pgp:forget-passphrases': [],
|
||||||
|
'dav:list': [],
|
||||||
|
'dav:connect': ['object'],
|
||||||
|
'dav:activate': ['object'],
|
||||||
|
'dav:remove': ['object'],
|
||||||
|
'dav:sync': ['enum:caldav,carddav'],
|
||||||
|
'dav:save-event': ['object'],
|
||||||
|
'dav:delete-event': ['object'],
|
||||||
|
'dav:save-contact': ['object'],
|
||||||
|
'dav:delete-contact': ['object']
|
||||||
|
};
|
||||||
|
|
||||||
|
function isRecord(value) {
|
||||||
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
||||||
|
const prototype = Object.getPrototypeOf(value);
|
||||||
|
return prototype === Object.prototype || prototype === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateTree(value, channel) {
|
||||||
|
let values = 0;
|
||||||
|
const ancestors = new WeakSet();
|
||||||
|
|
||||||
|
function visit(current, depth, key = '') {
|
||||||
|
values += 1;
|
||||||
|
if (values > MAX_VALUES) throw new Error(`Too many values in IPC request for ${channel}.`);
|
||||||
|
if (depth > MAX_DEPTH) throw new Error(`IPC request for ${channel} is nested too deeply.`);
|
||||||
|
if (current === null || current === undefined || typeof current === 'boolean') return;
|
||||||
|
if (typeof current === 'number') {
|
||||||
|
if (!Number.isFinite(current)) throw new Error(`Invalid number in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof current === 'string') {
|
||||||
|
const limit = key === 'armoredKey' ? MAX_ARMORED_KEY_LENGTH :
|
||||||
|
['contentBase64', 'rawBase64'].includes(key) ? Infinity : MAX_STRING_LENGTH;
|
||||||
|
if (current.length > limit) throw new Error(`String value is too large in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof current !== 'object' || (!Array.isArray(current) && !isRecord(current))) {
|
||||||
|
throw new Error(`Unsupported value in IPC request for ${channel}.`);
|
||||||
|
}
|
||||||
|
if (ancestors.has(current)) throw new Error(`Cyclic value in IPC request for ${channel}.`);
|
||||||
|
ancestors.add(current);
|
||||||
|
if (Array.isArray(current)) {
|
||||||
|
if (current.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many items in IPC request for ${channel}.`);
|
||||||
|
for (const item of current) visit(item, depth + 1);
|
||||||
|
} else {
|
||||||
|
const entries = Object.entries(current);
|
||||||
|
if (entries.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many fields in IPC request for ${channel}.`);
|
||||||
|
for (const [childKey, child] of entries) {
|
||||||
|
if (['__proto__', 'prototype', 'constructor'].includes(childKey)) {
|
||||||
|
throw new Error(`Unsafe field in IPC request for ${channel}.`);
|
||||||
|
}
|
||||||
|
visit(child, depth + 1, childKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ancestors.delete(current);
|
||||||
|
}
|
||||||
|
|
||||||
|
visit(value, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateField(value, field, channel, fieldPath) {
|
||||||
|
if (value === undefined) {
|
||||||
|
if (field.required) throw new Error(`Missing ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (value === null && field.nullable) return;
|
||||||
|
|
||||||
|
if (field.type === 'string') {
|
||||||
|
if (typeof value !== 'string') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
if (value.length > field.max) throw new Error(`The ${fieldPath} value is too large in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (field.type === 'number') {
|
||||||
|
if (typeof value !== 'number' || !Number.isFinite(value) ||
|
||||||
|
(field.integer && !Number.isInteger(value)) ||
|
||||||
|
(field.min !== undefined && value < field.min) ||
|
||||||
|
(field.max !== undefined && value > field.max)) {
|
||||||
|
throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (field.type === 'boolean') {
|
||||||
|
if (typeof value !== 'boolean') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (field.type === 'enum') {
|
||||||
|
if (!field.values.includes(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (field.type === 'array') {
|
||||||
|
if (!Array.isArray(value) || value.length > field.maxItems) {
|
||||||
|
throw new Error(`Invalid ${fieldPath} list in IPC request for ${channel}.`);
|
||||||
|
}
|
||||||
|
value.forEach((item, index) => validateField(item, field.item, channel, `${fieldPath}[${index}]`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (field.type === 'object') {
|
||||||
|
if (!isRecord(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
|
||||||
|
for (const [name, childField] of Object.entries(field.fields || {})) {
|
||||||
|
validateField(value[name], childField, channel, `${fieldPath}.${name}`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(`Unsupported validation rule for ${channel}.${fieldPath}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateIpcArguments(channel, args) {
|
||||||
|
const schema = schemas[channel];
|
||||||
|
if (!schema) throw new Error(`Unknown IPC channel: ${channel}.`);
|
||||||
|
if (!Array.isArray(args)) throw new TypeError('IPC arguments must be an array.');
|
||||||
|
const required = schema.filter(type => !type.endsWith('?')).length;
|
||||||
|
if (args.length < required || args.length > schema.length) {
|
||||||
|
throw new Error(`Invalid argument count for IPC channel ${channel}.`);
|
||||||
|
}
|
||||||
|
for (let index = 0; index < args.length; index += 1) {
|
||||||
|
const expected = schema[index].replace(/\?$/, '');
|
||||||
|
const value = args[index];
|
||||||
|
if (value === undefined && schema[index].endsWith('?')) continue;
|
||||||
|
const isEnum = expected.startsWith('enum:');
|
||||||
|
const typeIsValid = expected === 'object'
|
||||||
|
? isRecord(value)
|
||||||
|
: isEnum
|
||||||
|
? expected.slice('enum:'.length).split(',').includes(value)
|
||||||
|
: typeof value === expected;
|
||||||
|
if (!typeIsValid) {
|
||||||
|
throw new Error(`Invalid ${expected} argument ${index + 1} for IPC channel ${channel}.`);
|
||||||
|
}
|
||||||
|
validateTree(value, channel);
|
||||||
|
const fieldSchema = objectFieldSchemas[channel]?.[index];
|
||||||
|
if (fieldSchema) validateField(value, { type: 'object', fields: fieldSchema }, channel, `argument ${index + 1}`);
|
||||||
|
const enumValues = positionalEnums[channel]?.[index];
|
||||||
|
if (enumValues && !enumValues.includes(value)) throw new Error(`Invalid argument ${index + 1} for IPC channel ${channel}.`);
|
||||||
|
const positionalField = positionalFieldSchemas[channel]?.[index];
|
||||||
|
if (positionalField) validateField(value, positionalField, channel, `argument ${index + 1}`);
|
||||||
|
}
|
||||||
|
if (channel === 'mail:send') {
|
||||||
|
const unknown = Object.keys(args[0]).find(key => !sendMessageFields.has(key));
|
||||||
|
if (unknown) throw new Error(`Unsupported message field for IPC channel ${channel}.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasIpcSchema(channel) {
|
||||||
|
return Object.hasOwn(schemas, channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { hasIpcSchema, validateIpcArguments };
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
const path = require('node:path');
|
||||||
|
const { fileURLToPath } = require('node:url');
|
||||||
|
|
||||||
|
function isTrustedApplicationUrl(rawUrl, expectedFile) {
|
||||||
|
let actualFile;
|
||||||
|
try {
|
||||||
|
const url = new URL(rawUrl);
|
||||||
|
if (url.protocol !== 'file:' || url.search || url.hash) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
actualFile = fileURLToPath(url);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expected = path.resolve(expectedFile);
|
||||||
|
const actual = path.resolve(actualFile);
|
||||||
|
return process.platform === 'win32'
|
||||||
|
? actual.toLowerCase() === expected.toLowerCase()
|
||||||
|
: actual === expected;
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertTrustedIpcSender(event, expectedFile) {
|
||||||
|
const frame = event?.senderFrame;
|
||||||
|
if (!frame || !event?.sender || frame !== event.sender.mainFrame ||
|
||||||
|
!isTrustedApplicationUrl(frame.url, expectedFile)) {
|
||||||
|
throw new Error('This request must come from the application window.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { assertTrustedIpcSender, isTrustedApplicationUrl };
|
||||||
+5
-2
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<meta name="theme-color" content="#f4f5f1">
|
<meta name="theme-color" content="#f4f5f1">
|
||||||
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
|
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'">
|
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
|
||||||
<title>ep-mail</title>
|
<title>ep-mail</title>
|
||||||
<link rel="manifest" href="manifest.webmanifest">
|
<link rel="manifest" href="manifest.webmanifest">
|
||||||
<link rel="stylesheet" href="styles.css">
|
<link rel="stylesheet" href="styles.css">
|
||||||
@@ -64,13 +64,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div id="modal-root"></div>
|
<div id="modal-root"></div>
|
||||||
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
||||||
|
<script src="renderer-state.js"></script>
|
||||||
|
<script src="mail-content-security.js"></script>
|
||||||
<script src="app.js"></script>
|
<script src="app.js"></script>
|
||||||
<script src="platform-bridge.js"></script>
|
<script src="platform-bridge.js"></script>
|
||||||
|
<script src="renderer-mail-api.js"></script>
|
||||||
<script src="mail-ui.js"></script>
|
<script src="mail-ui.js"></script>
|
||||||
<script src="productivity.js"></script>
|
<script src="productivity.js"></script>
|
||||||
<script src="snooze-ui.js"></script>
|
<script src="snooze-ui.js"></script>
|
||||||
<script src="account-ui.js"></script>
|
|
||||||
<script src="dav-ui.js"></script>
|
<script src="dav-ui.js"></script>
|
||||||
|
<script src="account-ui.js"></script>
|
||||||
<script src="shortcuts.js"></script>
|
<script src="shortcuts.js"></script>
|
||||||
<script src="attachments.js"></script>
|
<script src="attachments.js"></script>
|
||||||
<script src="pgp-ui.js"></script>
|
<script src="pgp-ui.js"></script>
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
(function installMailContentSecurity(root) {
|
||||||
|
if (typeof module === 'object' && module.exports) {
|
||||||
|
module.exports = { createMailContentSecurity };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
root.epMailFeatures = root.epMailFeatures || {};
|
||||||
|
Object.defineProperty(root.epMailFeatures, 'contentSecurity', {
|
||||||
|
value: createMailContentSecurity(root),
|
||||||
|
enumerable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
function createMailContentSecurity(browserRoot) {
|
||||||
|
function escapeHtml(value) {
|
||||||
|
return String(value).replace(/[&<>"']/g, character => ({
|
||||||
|
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||||
|
})[character]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeRemoteImageUrl(value) {
|
||||||
|
if (typeof value !== 'string' || value.length > 2048) return null;
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return url.protocol === 'https:' && url.hostname && !url.username && !url.password ? url.href : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeMailHtml(value) {
|
||||||
|
const html = String(value || '').slice(0, 100000);
|
||||||
|
const inertImages = html
|
||||||
|
.replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi, '')
|
||||||
|
.replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi, '')
|
||||||
|
.replace(/<!--[\s\S]*?-->/g, '')
|
||||||
|
.replace(/<img\b[^>]*>/gi, tag => {
|
||||||
|
const source = tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
|
||||||
|
const alt = tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
|
||||||
|
const remote = source && (source[1] || source[2] || source[3] || '').trim();
|
||||||
|
const alternative = alt && (alt[1] || alt[2] || alt[3] || '');
|
||||||
|
return `<img${remote ? ` data-remote-src="${escapeHtml(remote)}"` : ''}${alternative ? ` alt="${escapeHtml(alternative)}"` : ''}>`;
|
||||||
|
})
|
||||||
|
.replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
|
||||||
|
const document = new browserRoot.DOMParser().parseFromString(inertImages, 'text/html');
|
||||||
|
const allowed = new Set(['a', 'p', 'div', 'span', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b', 'strong', 'i', 'em', 'u', 's', 'del', 'blockquote', 'pre', 'code', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'img']);
|
||||||
|
const discard = new Set(['script', 'style', 'iframe', 'frame', 'object', 'embed', 'svg', 'math', 'form', 'input', 'button', 'textarea', 'select', 'option', 'link', 'base', 'meta', 'video', 'audio', 'source', 'picture', 'track']);
|
||||||
|
let remoteImageCount = 0;
|
||||||
|
const clean = parent => {
|
||||||
|
for (const node of [...parent.childNodes]) {
|
||||||
|
if (node.nodeType !== browserRoot.Node.ELEMENT_NODE) {
|
||||||
|
if (node.nodeType !== browserRoot.Node.TEXT_NODE) node.remove();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const name = node.localName.toLowerCase();
|
||||||
|
if (discard.has(name)) { node.remove(); continue; }
|
||||||
|
if (!allowed.has(name)) { node.replaceWith(...node.childNodes); continue; }
|
||||||
|
for (const attribute of [...node.attributes]) {
|
||||||
|
const key = attribute.name.toLowerCase();
|
||||||
|
const keep = (name === 'img' && (key === 'alt' || key === 'data-remote-src')) ||
|
||||||
|
(name === 'td' || name === 'th') && ['colspan', 'rowspan'].includes(key) && /^\d{1,2}$/.test(attribute.value);
|
||||||
|
if (!keep) node.removeAttribute(attribute.name);
|
||||||
|
}
|
||||||
|
if (name === 'img') {
|
||||||
|
const url = safeRemoteImageUrl(node.getAttribute('data-remote-src'));
|
||||||
|
if (url) { node.setAttribute('data-remote-src', url); remoteImageCount += 1; }
|
||||||
|
else node.removeAttribute('data-remote-src');
|
||||||
|
}
|
||||||
|
clean(node);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
clean(document.body);
|
||||||
|
return { html: document.body.innerHTML, remoteImageCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({ safeRemoteImageUrl, sanitizeMailHtml });
|
||||||
|
}
|
||||||
|
})(typeof window === 'undefined' ? globalThis : window);
|
||||||
+435
-250
File diff suppressed because it is too large
Load Diff
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.3.6",
|
"version": "0.4.39",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.3.6",
|
"version": "0.4.39",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/core": "^8.5.2",
|
||||||
|
|||||||
+14
-3
@@ -1,9 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.3.6",
|
"version": "0.4.39",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Eternity Project mail client",
|
"description": "Eternity Project mail client",
|
||||||
"author": "Eternity Project",
|
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||||
|
"author": {
|
||||||
|
"name": "Eternity Project",
|
||||||
|
"email": "tero.huttunen@eternityproject.fi"
|
||||||
|
},
|
||||||
"desktopName": "ep-mail",
|
"desktopName": "ep-mail",
|
||||||
"main": "desktop/main.cjs",
|
"main": "desktop/main.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -38,6 +42,9 @@
|
|||||||
"platform-bridge.js",
|
"platform-bridge.js",
|
||||||
"styles.css",
|
"styles.css",
|
||||||
"branding.css",
|
"branding.css",
|
||||||
|
"renderer-state.js",
|
||||||
|
"mail-content-security.js",
|
||||||
|
"renderer-mail-api.js",
|
||||||
"app.js",
|
"app.js",
|
||||||
"mail-ui.js",
|
"mail-ui.js",
|
||||||
"productivity.js",
|
"productivity.js",
|
||||||
@@ -48,6 +55,7 @@
|
|||||||
"pgp-ui.js",
|
"pgp-ui.js",
|
||||||
"pgp-mail-ui.js",
|
"pgp-mail-ui.js",
|
||||||
"icon.svg",
|
"icon.svg",
|
||||||
|
"icon.ico",
|
||||||
"logo-ep-daylight.svg",
|
"logo-ep-daylight.svg",
|
||||||
"logo-ep-wasteland.svg",
|
"logo-ep-wasteland.svg",
|
||||||
"manifest.webmanifest",
|
"manifest.webmanifest",
|
||||||
@@ -59,6 +67,7 @@
|
|||||||
"output": "release"
|
"output": "release"
|
||||||
},
|
},
|
||||||
"win": {
|
"win": {
|
||||||
|
"icon": "icon.ico",
|
||||||
"target": [
|
"target": [
|
||||||
"nsis",
|
"nsis",
|
||||||
"portable"
|
"portable"
|
||||||
@@ -77,12 +86,14 @@
|
|||||||
"AppImage",
|
"AppImage",
|
||||||
"deb"
|
"deb"
|
||||||
],
|
],
|
||||||
|
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
|
||||||
"synopsis": "A calmer place for mail, people, and plans"
|
"synopsis": "A calmer place for mail, people, and plans"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"allowScripts": {
|
"allowScripts": {
|
||||||
"electron@44.5.1": true,
|
"electron@44.5.1": true,
|
||||||
"electron-winstaller@5.4.0": true
|
"electron-winstaller@5.4.0": true,
|
||||||
|
"esbuild@0.28.2": true
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
|
|||||||
+41
-38
@@ -1,4 +1,10 @@
|
|||||||
|
(() => {
|
||||||
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
|
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
|
||||||
|
const pgpMailUi = window.epMailFeatures.mail;
|
||||||
|
const selectPgpMailUi = pgpMailUi.select;
|
||||||
|
const selectAllPgpMailUi = pgpMailUi.selectAll;
|
||||||
|
const toastPgpMailUi = pgpMailUi.toast;
|
||||||
|
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
||||||
const pgpApi = () => window.daybreakMail?.pgp;
|
const pgpApi = () => window.daybreakMail?.pgp;
|
||||||
|
|
||||||
function pgpAskPassphrase(title, detail) {
|
function pgpAskPassphrase(title, detail) {
|
||||||
@@ -38,10 +44,10 @@ function pgpSignatureHtml(signatures, encrypted) {
|
|||||||
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
||||||
if (signature.status === 'valid') {
|
if (signature.status === 'valid') {
|
||||||
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
||||||
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
if (signature.status === 'unknown-key') {
|
if (signature.status === 'unknown-key') {
|
||||||
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
@@ -52,14 +58,14 @@ async function pgpAddAttachedKey(key) {
|
|||||||
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
||||||
try {
|
try {
|
||||||
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
||||||
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast(error.message || 'Could not add the key');
|
toastPgpMailUi(error.message || 'Could not add the key');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpRenderReaderState(message) {
|
function pgpRenderReaderState(message) {
|
||||||
const reader = $('#reader-pane');
|
const reader = selectPgpMailUi('#reader-pane');
|
||||||
const header = reader.querySelector('.reader-header');
|
const header = reader.querySelector('.reader-header');
|
||||||
if (!header) return;
|
if (!header) return;
|
||||||
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
||||||
@@ -72,11 +78,11 @@ function pgpRenderReaderState(message) {
|
|||||||
html = pgpSignatureHtml(message.pgpSignatures, false);
|
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||||
}
|
}
|
||||||
const keys = message.pgpResult?.attachedKeys || [];
|
const keys = message.pgpResult?.attachedKeys || [];
|
||||||
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
||||||
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
||||||
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
||||||
});
|
});
|
||||||
const unlock = $('#pgp-unlock');
|
const unlock = selectPgpMailUi('#pgp-unlock');
|
||||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,15 +93,15 @@ async function pgpUnlockMessage(message, interactive) {
|
|||||||
try {
|
try {
|
||||||
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast(error.message || 'Could not open this message');
|
toastPgpMailUi(error.message || 'Could not open this message');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
Object.assign(message, {
|
Object.assign(message, {
|
||||||
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
||||||
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
||||||
});
|
});
|
||||||
if (activeMessage === message.id) openMessage(message.id);
|
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
||||||
@@ -104,54 +110,49 @@ async function pgpUnlockMessage(message, interactive) {
|
|||||||
if (passphrase === null) return;
|
if (passphrase === null) return;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const text = $('#pgp-banner-text');
|
const text = selectPgpMailUi('#pgp-banner-text');
|
||||||
if (text) text.textContent = result.message;
|
if (text) text.textContent = result.message;
|
||||||
else toast(result.message);
|
else toastPgpMailUi(result.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof openMessage === 'function') {
|
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
const baseOpenMessage = openMessage;
|
|
||||||
openMessage = function (id) {
|
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = messages.find(item => item.id === id);
|
const message = pgpMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message || !pgpApi()) return;
|
if (!message || !pgpApi()) return;
|
||||||
pgpRenderReaderState(message);
|
pgpRenderReaderState(message);
|
||||||
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
||||||
message.pgpAutoTried = true;
|
message.pgpAutoTried = true;
|
||||||
void pgpUnlockMessage(message, false);
|
void pgpUnlockMessage(message, false);
|
||||||
}
|
}
|
||||||
};
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Compose: encrypt/sign options.
|
// Compose: encrypt/sign options.
|
||||||
if (typeof showCompose === 'function') {
|
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
||||||
const baseShowCompose = showCompose;
|
|
||||||
showCompose = function (reply, forward = false) {
|
|
||||||
baseShowCompose(reply, forward);
|
baseShowCompose(reply, forward);
|
||||||
const footer = $('#modal-root .compose-footer');
|
const footer = selectPgpMailUi('#modal-root .compose-footer');
|
||||||
if (!footer || !pgpApi()) return;
|
if (!footer || !pgpApi()) return;
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pgp-compose';
|
box.className = 'pgp-compose';
|
||||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
||||||
footer.prepend(box);
|
footer.prepend(box);
|
||||||
let touched = false;
|
let touched = false;
|
||||||
const encrypt = $('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
const sign = $('#pgp-sign');
|
const sign = selectPgpMailUi('#pgp-sign');
|
||||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||||
if (touched) encrypt.dataset.touched = '1';
|
if (touched) encrypt.dataset.touched = '1';
|
||||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||||
let timer = null;
|
let timer = null;
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
const to = $('#compose-to')?.value || '';
|
const to = selectPgpMailUi('#compose-to')?.value || '';
|
||||||
const cc = $('#compose-cc')?.value || '';
|
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
||||||
const hint = $('#pgp-hint');
|
const hint = selectPgpMailUi('#pgp-hint');
|
||||||
if (!hint) return;
|
if (!hint) return;
|
||||||
if (!to.trim()) { hint.textContent = ''; return; }
|
if (!to.trim()) { hint.textContent = ''; return; }
|
||||||
try {
|
try {
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
||||||
if (!$('#pgp-hint')) return;
|
if (!selectPgpMailUi('#pgp-hint')) return;
|
||||||
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
||||||
else {
|
else {
|
||||||
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
||||||
@@ -160,21 +161,20 @@ if (typeof showCompose === 'function') {
|
|||||||
} catch { hint.textContent = ''; }
|
} catch { hint.textContent = ''; }
|
||||||
};
|
};
|
||||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
||||||
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
|
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
|
||||||
sign.addEventListener('change', schedule);
|
sign.addEventListener('change', schedule);
|
||||||
schedule();
|
schedule();
|
||||||
};
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||||
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
|
async function prepareSend(to, cc) {
|
||||||
if (!pgpApi()) return null;
|
if (!pgpApi()) return null;
|
||||||
let encrypt = Boolean($('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean($('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
|
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign });
|
const status = await pgpApi().checkSend({ to, cc, sign });
|
||||||
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
||||||
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
|
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
||||||
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
||||||
if (!sign) return null;
|
if (!sign) return null;
|
||||||
} else return false;
|
} else return false;
|
||||||
@@ -188,11 +188,14 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
|
|||||||
}
|
}
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
|
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
|
||||||
if (!status.signer.unlocked) {
|
if (!status.signer.unlocked) {
|
||||||
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
||||||
if (passphrase === null) return false;
|
if (passphrase === null) return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { encrypt, sign, passphrase };
|
return { encrypt, sign, passphrase };
|
||||||
};
|
}
|
||||||
|
|
||||||
|
window.epMailFeatures.pgp = Object.freeze({ prepareSend });
|
||||||
|
})();
|
||||||
|
|||||||
@@ -1,22 +1,46 @@
|
|||||||
|
(() => {
|
||||||
// Encryption key management (desktop). Hidden where the platform has no key store yet.
|
// Encryption key management (desktop). Hidden where the platform has no key store yet.
|
||||||
|
const pgpKeyMailUi = window.epMailFeatures.mail;
|
||||||
|
const selectPgpKeyUi = pgpKeyMailUi.select;
|
||||||
|
const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
|
||||||
|
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
||||||
|
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
||||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = $('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = connectedMailAccount || {};
|
const account = window.epMailFeatures.mail.connectedAccount || {};
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||||
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||||
|
<h3 class="pgp-heading">Change a key passphrase</h3>
|
||||||
|
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
||||||
|
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
|
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||||
|
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||||
<h3 class="pgp-heading">Contact public keys</h3>
|
<h3 class="pgp-heading">Contact public keys</h3>
|
||||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||||
|
<h3 class="pgp-heading">Public key servers</h3>
|
||||||
|
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
||||||
|
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
||||||
|
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
|
<div class="pgp-actions"><button class="discard" id="pgp-find-key">Search all enabled servers</button></div>
|
||||||
|
<div id="pgp-found-keys" class="attachment-list"></div>
|
||||||
|
<label class="compose-line"><span>Publish to one server</span><select id="pgp-publish-server"></select></label>
|
||||||
|
<p class="account-note">Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.</p>
|
||||||
|
<h4 class="pgp-heading">Add a custom HTTPS server</h4>
|
||||||
|
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
|
||||||
|
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
||||||
|
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
||||||
|
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>
|
||||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||||
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
||||||
<h3 class="pgp-heading">Create a key</h3>
|
<h3 class="pgp-heading">Create a key</h3>
|
||||||
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label>
|
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
|
||||||
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label>
|
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
||||||
<p class="account-note" id="pgp-status" role="status"></p>
|
<p class="account-note" id="pgp-status" role="status"></p>
|
||||||
@@ -24,8 +48,17 @@ function openEncryptionKeys() {
|
|||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('.modal-close').onclick = close;
|
root.querySelector('.modal-close').onclick = close;
|
||||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
const status = message => { $('#pgp-status').textContent = message; };
|
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
||||||
const passphraseField = () => $('#pgp-passphrase');
|
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
||||||
|
let keyServers = [];
|
||||||
|
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
||||||
|
const updatePublishButtons = () => {
|
||||||
|
const server = selectedPublishServer();
|
||||||
|
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
||||||
|
button.disabled = !server;
|
||||||
|
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
||||||
|
});
|
||||||
|
};
|
||||||
const needPassphrase = () => {
|
const needPassphrase = () => {
|
||||||
const value = passphraseField().value;
|
const value = passphraseField().value;
|
||||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||||
@@ -33,7 +66,7 @@ function openEncryptionKeys() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function render() {
|
async function render() {
|
||||||
const list = $('#pgp-key-list');
|
const list = selectPgpKeyUi('#pgp-key-list');
|
||||||
let keys = [];
|
let keys = [];
|
||||||
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
@@ -55,6 +88,44 @@ function openEncryptionKeys() {
|
|||||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||||
];
|
];
|
||||||
|
const changePassphrase = document.createElement('button');
|
||||||
|
changePassphrase.className = 'discard';
|
||||||
|
changePassphrase.textContent = 'Change passphrase…';
|
||||||
|
changePassphrase.onclick = async () => {
|
||||||
|
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
||||||
|
if (!currentPassphrase) {
|
||||||
|
status('Enter the current passphrase for this key.');
|
||||||
|
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
||||||
|
if (newPassphrase.length < 8) {
|
||||||
|
status('Use a new passphrase of at least 8 characters.');
|
||||||
|
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
||||||
|
status('The new passphrases do not match.');
|
||||||
|
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
changePassphrase.disabled = true;
|
||||||
|
try {
|
||||||
|
await window.daybreakMail.pgp.changePassphrase({
|
||||||
|
fingerprint: key.fingerprint,
|
||||||
|
currentPassphrase,
|
||||||
|
newPassphrase
|
||||||
|
});
|
||||||
|
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
||||||
|
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||||
|
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||||
|
finally {
|
||||||
|
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
||||||
|
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
||||||
|
changePassphrase.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
row.append(changePassphrase);
|
||||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||||
actions.push(['Delete', async () => {
|
actions.push(['Delete', async () => {
|
||||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||||
@@ -75,24 +146,44 @@ function openEncryptionKeys() {
|
|||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
|
const publish = document.createElement('button');
|
||||||
|
publish.className = 'discard pgp-publish';
|
||||||
|
publish.onclick = async () => {
|
||||||
|
const server = selectedPublishServer();
|
||||||
|
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||||
|
publish.disabled = true;
|
||||||
|
try {
|
||||||
|
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||||
|
if (result.canceled) return;
|
||||||
|
if (result.warning) status(result.warning);
|
||||||
|
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
||||||
|
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
||||||
|
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
||||||
|
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
||||||
|
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||||
|
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||||
|
finally { updatePublishButtons(); }
|
||||||
|
};
|
||||||
|
row.append(publish);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
|
updatePublishButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
$('#pgp-generate').onclick = async () => {
|
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
||||||
const button = $('#pgp-generate');
|
const button = selectPgpKeyUi('#pgp-generate');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
status('Creating key…');
|
status('Creating key…');
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.generate({
|
await window.daybreakMail.pgp.generate({
|
||||||
name: $('#pgp-name').value, email: $('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
||||||
});
|
});
|
||||||
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
||||||
await render();
|
await render();
|
||||||
} catch (error) { status(error.message || 'Could not create the key.'); }
|
} catch (error) { status(error.message || 'Could not create the key.'); }
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
};
|
};
|
||||||
$('#pgp-import').onclick = async () => {
|
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
||||||
const passphrase = needPassphrase();
|
const passphrase = needPassphrase();
|
||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
@@ -102,7 +193,7 @@ function openEncryptionKeys() {
|
|||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
async function renderContacts() {
|
async function renderContacts() {
|
||||||
const list = $('#pgp-contact-list');
|
const list = selectPgpKeyUi('#pgp-contact-list');
|
||||||
let contacts = [];
|
let contacts = [];
|
||||||
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
@@ -159,28 +250,167 @@ function openEncryptionKeys() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
$('#pgp-add-contact').onclick = async () => {
|
selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addContact({});
|
const result = await window.daybreakMail.pgp.addContact({});
|
||||||
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
||||||
await renderContacts();
|
await renderContacts();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
async function renderKeyServers() {
|
||||||
$('#pgp-save-cache').onclick = async () => {
|
const list = selectPgpKeyUi('#pgp-server-list');
|
||||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
const selector = selectPgpKeyUi('#pgp-publish-server');
|
||||||
|
const selectedId = selector.value;
|
||||||
|
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||||
|
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||||
|
selector.replaceChildren();
|
||||||
|
const enabledServers = keyServers.filter(server => server.enabled);
|
||||||
|
if (!enabledServers.length) {
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = '';
|
||||||
|
option.textContent = 'No enabled servers';
|
||||||
|
selector.append(option);
|
||||||
|
} else enabledServers.forEach(server => {
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = server.id;
|
||||||
|
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||||
|
option.selected = server.id === selectedId;
|
||||||
|
selector.append(option);
|
||||||
|
});
|
||||||
|
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||||
|
selector.onchange = updatePublishButtons;
|
||||||
|
list.replaceChildren();
|
||||||
|
keyServers.forEach(server => {
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.className = 'attachment-row';
|
||||||
|
const info = document.createElement('div');
|
||||||
|
info.className = 'attachment-row-info';
|
||||||
|
const title = document.createElement('strong');
|
||||||
|
title.textContent = server.name;
|
||||||
|
const details = document.createElement('small');
|
||||||
|
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||||
|
info.append(title, details);
|
||||||
|
const enabledLabel = document.createElement('label');
|
||||||
|
enabledLabel.className = 'compose-line';
|
||||||
|
const enabledText = document.createElement('span');
|
||||||
|
enabledText.textContent = 'Use for lookup and publishing';
|
||||||
|
const enabled = document.createElement('input');
|
||||||
|
enabled.type = 'checkbox';
|
||||||
|
enabled.checked = server.enabled;
|
||||||
|
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||||
|
enabled.onchange = async () => {
|
||||||
|
enabled.disabled = true;
|
||||||
|
try {
|
||||||
|
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||||
|
await renderKeyServers();
|
||||||
|
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||||
|
} catch (error) {
|
||||||
|
enabled.checked = server.enabled;
|
||||||
|
status(error.message || `Could not update ${server.name}.`);
|
||||||
|
} finally { enabled.disabled = false; }
|
||||||
|
};
|
||||||
|
enabledLabel.append(enabledText, enabled);
|
||||||
|
row.append(info, enabledLabel);
|
||||||
|
if (!server.builtin) {
|
||||||
|
const remove = document.createElement('button');
|
||||||
|
remove.className = 'discard';
|
||||||
|
remove.textContent = 'Remove';
|
||||||
|
remove.onclick = async () => {
|
||||||
|
try {
|
||||||
|
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||||
|
await renderKeyServers();
|
||||||
|
status('Custom key server removed.');
|
||||||
|
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||||
|
};
|
||||||
|
row.append(remove);
|
||||||
|
}
|
||||||
|
list.append(row);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
||||||
|
const button = selectPgpKeyUi('#pgp-find-key');
|
||||||
|
const results = selectPgpKeyUi('#pgp-found-keys');
|
||||||
|
button.disabled = true;
|
||||||
|
results.textContent = 'Searching…';
|
||||||
|
try {
|
||||||
|
const found = await window.daybreakMail.pgp.findKey({
|
||||||
|
email: selectPgpKeyUi('#pgp-search-email').value
|
||||||
|
});
|
||||||
|
results.replaceChildren();
|
||||||
|
found.keys.forEach(key => {
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.className = 'attachment-row';
|
||||||
|
const info = document.createElement('div');
|
||||||
|
info.className = 'attachment-row-info';
|
||||||
|
const title = document.createElement('strong');
|
||||||
|
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||||
|
const meta = document.createElement('small');
|
||||||
|
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||||
|
const fingerprint = document.createElement('small');
|
||||||
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
|
info.append(title, meta, fingerprint);
|
||||||
|
const add = document.createElement('button');
|
||||||
|
add.className = 'discard';
|
||||||
|
add.textContent = 'Add to contacts…';
|
||||||
|
add.onclick = async () => {
|
||||||
|
add.disabled = true;
|
||||||
|
try {
|
||||||
|
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
|
if (result.canceled) return;
|
||||||
|
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
||||||
|
await renderContacts();
|
||||||
|
row.remove();
|
||||||
|
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||||
|
finally { add.disabled = false; }
|
||||||
|
};
|
||||||
|
row.append(info, add);
|
||||||
|
results.append(row);
|
||||||
|
});
|
||||||
|
found.errors.forEach(error => {
|
||||||
|
const warning = document.createElement('small');
|
||||||
|
warning.textContent = `${error.name}: ${error.message}`;
|
||||||
|
results.append(warning);
|
||||||
|
});
|
||||||
|
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
||||||
|
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
||||||
|
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
||||||
|
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||||
|
} catch (error) {
|
||||||
|
results.textContent = '';
|
||||||
|
status(error.message || 'Could not search the key server.');
|
||||||
|
} finally { button.disabled = false; }
|
||||||
|
};
|
||||||
|
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
||||||
|
const button = selectPgpKeyUi('#pgp-add-server');
|
||||||
|
button.disabled = true;
|
||||||
|
try {
|
||||||
|
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||||
|
name: selectPgpKeyUi('#pgp-server-name').value,
|
||||||
|
url: selectPgpKeyUi('#pgp-server-url').value,
|
||||||
|
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
||||||
|
});
|
||||||
|
if (result.canceled) return;
|
||||||
|
selectPgpKeyUi('#pgp-server-name').value = '';
|
||||||
|
selectPgpKeyUi('#pgp-server-url').value = '';
|
||||||
|
await renderKeyServers();
|
||||||
|
status('Custom key server added.');
|
||||||
|
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||||
|
finally { button.disabled = false; }
|
||||||
|
};
|
||||||
|
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||||
|
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
||||||
|
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||||
};
|
};
|
||||||
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||||
|
void renderKeyServers();
|
||||||
void renderContacts();
|
void renderContacts();
|
||||||
void render();
|
void render();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof openPreferences === 'function') {
|
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
const baseOpenPreferences = openPreferences;
|
|
||||||
openPreferences = function () {
|
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = $('#modal-root .compose-fields');
|
const fields = selectPgpKeyUi('#modal-root .compose-fields');
|
||||||
if (!fields || !pgpAvailable()) return;
|
if (!fields || !pgpAvailable()) return;
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
button.type = 'button';
|
button.type = 'button';
|
||||||
@@ -189,5 +419,5 @@ if (typeof openPreferences === 'function') {
|
|||||||
button.textContent = 'Encryption keys…';
|
button.textContent = 'Encryption keys…';
|
||||||
button.onclick = openEncryptionKeys;
|
button.onclick = openEncryptionKeys;
|
||||||
fields.append(button);
|
fields.append(button);
|
||||||
};
|
});
|
||||||
}
|
})();
|
||||||
|
|||||||
+78
-26
@@ -1,4 +1,10 @@
|
|||||||
|
(() => {
|
||||||
// Persistent profile, calendar and contact tools, plus actions for the mail UI.
|
// Persistent profile, calendar and contact tools, plus actions for the mail UI.
|
||||||
|
const productivityMailUi = window.epMailFeatures.mail;
|
||||||
|
const selectProductivityUi = productivityMailUi.select;
|
||||||
|
const selectAllProductivityUi = productivityMailUi.selectAll;
|
||||||
|
const toastProductivityUi = productivityMailUi.toast;
|
||||||
|
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
||||||
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
||||||
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
||||||
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
||||||
@@ -11,39 +17,85 @@ productWrite(productKeys.contacts, savedContacts);
|
|||||||
let savedEvents = productRead(productKeys.events, []);
|
let savedEvents = productRead(productKeys.events, []);
|
||||||
let customLabels = productRead(productKeys.labels, []);
|
let customLabels = productRead(productKeys.labels, []);
|
||||||
let snoozedIds = productRead(productKeys.snoozed, []);
|
let snoozedIds = productRead(productKeys.snoozed, []);
|
||||||
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
|
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
|
||||||
function openAccountSettings() {
|
function openAccountSettings() {
|
||||||
const root=$('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
$('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')};
|
selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
||||||
$('#profile-name').focus();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
function openPreferences() {
|
function openPreferences() {
|
||||||
const root=$('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
$('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')};
|
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Appearance saved')};
|
||||||
$('#theme-select').focus();
|
selectProductivityUi('#theme-select').focus();
|
||||||
}
|
}
|
||||||
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
|
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
|
||||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
|
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
||||||
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
|
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
|
||||||
function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
||||||
function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
|
function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
|
||||||
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
|
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
|
||||||
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
||||||
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
|
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
|
||||||
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
|
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
|
||||||
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
|
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
|
||||||
const baseMessageRenderer=renderList;
|
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
||||||
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
|
const state = productivityMailUi.state;
|
||||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
|
if (state.activeFolder === 'Drafts') {
|
||||||
|
selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
|
||||||
|
selectProductivityUi('#start-draft').onclick = () => productivityMailUi.showCompose();
|
||||||
|
selectProductivityUi('#reader-pane').innerHTML = productivityMailUi.emptyReader();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (state.activeFolder === 'Snoozed' || ['Design', 'Travel', 'Personal', ...customLabels, ...accountRuleLabels()].includes(state.activeFolder)) {
|
||||||
|
const folder = state.activeFolder;
|
||||||
|
const original = state.messages.slice();
|
||||||
|
const keep = state.messages.filter(message => folder === 'Snoozed' ? Boolean(message.snoozedUntil) : (message.tags || []).includes(folder));
|
||||||
|
state.messages.splice(0, state.messages.length, ...keep);
|
||||||
|
state.activeFolder = 'Inbox';
|
||||||
|
baseMessageRenderer();
|
||||||
|
state.activeFolder = folder;
|
||||||
|
state.messages.splice(0, state.messages.length, ...original);
|
||||||
|
if (!keep.length) selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return baseMessageRenderer();
|
||||||
|
});
|
||||||
|
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toastProductivityUi('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:productivityMailUi.state.activeFolder,filename}).then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
||||||
|
|
||||||
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
|
get events() { return savedEvents; },
|
||||||
|
set events(value) { savedEvents = value; },
|
||||||
|
get contacts() { return savedContacts; },
|
||||||
|
set contacts(value) { savedContacts = value; },
|
||||||
|
get profileName() { return profileSettings.name; },
|
||||||
|
productKeys,
|
||||||
|
productWrite,
|
||||||
|
renderCalendar,
|
||||||
|
renderContacts,
|
||||||
|
showEvent,
|
||||||
|
showContact,
|
||||||
|
addMessageLabel,
|
||||||
|
setProfileName,
|
||||||
|
openAccountSettings,
|
||||||
|
get openPreferences() { return openPreferences; },
|
||||||
|
select: selectProductivityUi,
|
||||||
|
selectAll: selectAllProductivityUi,
|
||||||
|
toast: toastProductivityUi,
|
||||||
|
escapeHtml: escapeProductivityUi,
|
||||||
|
wrapOpenPreferences(decorator) {
|
||||||
|
openPreferences = decorator(openPreferences);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
(function installMailUiApiFactory(root) {
|
||||||
|
function createMailUiApi({
|
||||||
|
state,
|
||||||
|
getConnectedAccount,
|
||||||
|
setConnectedAccount,
|
||||||
|
setPageOffset,
|
||||||
|
syncMailbox,
|
||||||
|
updateAccountCard,
|
||||||
|
getRenderList,
|
||||||
|
getOpenMessage,
|
||||||
|
getShowCompose,
|
||||||
|
baseRenderList,
|
||||||
|
emptyReader,
|
||||||
|
openMailAccount,
|
||||||
|
select,
|
||||||
|
selectAll,
|
||||||
|
toast,
|
||||||
|
escapeHtml,
|
||||||
|
getApplyTheme,
|
||||||
|
setRenderList,
|
||||||
|
setOpenMessage,
|
||||||
|
setShowCompose
|
||||||
|
}) {
|
||||||
|
return Object.freeze({
|
||||||
|
state,
|
||||||
|
get connectedAccount() { return getConnectedAccount(); },
|
||||||
|
set connectedAccount(account) { setConnectedAccount(account); },
|
||||||
|
setPageOffset,
|
||||||
|
syncMailbox,
|
||||||
|
updateAccountCard,
|
||||||
|
get renderList() { return getRenderList(); },
|
||||||
|
get openMessage() { return getOpenMessage(); },
|
||||||
|
get showCompose() { return getShowCompose(); },
|
||||||
|
baseRenderList,
|
||||||
|
emptyReader,
|
||||||
|
openMailAccount,
|
||||||
|
select,
|
||||||
|
selectAll,
|
||||||
|
toast,
|
||||||
|
escapeHtml,
|
||||||
|
get applyTheme() { return getApplyTheme(); },
|
||||||
|
wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); },
|
||||||
|
wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); },
|
||||||
|
wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof module === 'object' && module.exports) {
|
||||||
|
module.exports = { createMailUiApi };
|
||||||
|
} else {
|
||||||
|
root.epMailFeatures = root.epMailFeatures || {};
|
||||||
|
Object.defineProperty(root.epMailFeatures, 'modules', {
|
||||||
|
value: Object.freeze({ createMailUiApi }),
|
||||||
|
enumerable: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})(typeof window === 'undefined' ? globalThis : window);
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
(function installRendererState(root, createState) {
|
||||||
|
if (typeof module === 'object' && module.exports) {
|
||||||
|
module.exports = { createRendererState: createState };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
createState(root);
|
||||||
|
})(typeof window === 'undefined' ? globalThis : window, function createRendererState(root) {
|
||||||
|
const state = {
|
||||||
|
messages: [],
|
||||||
|
contacts: [],
|
||||||
|
activeMessage: 1,
|
||||||
|
activeFolder: 'Inbox',
|
||||||
|
activeView: 'mail',
|
||||||
|
query: '',
|
||||||
|
toastTimer: null,
|
||||||
|
selectedIds: new Set()
|
||||||
|
};
|
||||||
|
|
||||||
|
Object.defineProperty(root, 'epMailState', {
|
||||||
|
value: state,
|
||||||
|
enumerable: false,
|
||||||
|
configurable: false,
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
return state;
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
const { spawnSync } = require('node:child_process');
|
const { spawnSync } = require('node:child_process');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
const androidDir = path.resolve(__dirname, '..', 'android');
|
const androidDir = path.resolve(__dirname, '..', 'android');
|
||||||
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
|
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
|
||||||
@@ -12,6 +13,15 @@ const result = spawnSync(gradleWrapper, ['assembleDebug'], {
|
|||||||
if (result.error) {
|
if (result.error) {
|
||||||
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
|
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
|
} else if (result.status) {
|
||||||
|
process.exitCode = result.status;
|
||||||
} else {
|
} else {
|
||||||
process.exitCode = result.status ?? 1;
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const { version } = require(path.join(root, 'package.json'));
|
||||||
|
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk');
|
||||||
|
const releaseDir = path.join(root, 'release');
|
||||||
|
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
|
||||||
|
fs.mkdirSync(releaseDir, { recursive: true });
|
||||||
|
fs.copyFileSync(apk, target);
|
||||||
|
console.log(`APK copied to ${target}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ const assets = [
|
|||||||
'index.html',
|
'index.html',
|
||||||
'styles.css',
|
'styles.css',
|
||||||
'branding.css',
|
'branding.css',
|
||||||
|
'renderer-state.js',
|
||||||
|
'mail-content-security.js',
|
||||||
|
'renderer-mail-api.js',
|
||||||
'app.js',
|
'app.js',
|
||||||
'mail-ui.js',
|
'mail-ui.js',
|
||||||
'productivity.js',
|
'productivity.js',
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v7';
|
const CACHE='ep-mail-v11';
|
||||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
||||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
||||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||||
|
|||||||
+26
-21
@@ -1,14 +1,20 @@
|
|||||||
|
(() => {
|
||||||
// Configurable keyboard shortcuts for common mail actions.
|
// Configurable keyboard shortcuts for common mail actions.
|
||||||
|
const shortcutMailUi = window.epMailFeatures.mail;
|
||||||
|
const shortcutProductivityUi = window.epMailFeatures.productivity;
|
||||||
|
const selectShortcutUi = shortcutMailUi.select;
|
||||||
|
const toastShortcutUi = shortcutMailUi.toast;
|
||||||
|
const escapeShortcutUi = shortcutMailUi.escapeHtml;
|
||||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||||
const shortcutActions = [
|
const shortcutActions = [
|
||||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
|
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
|
||||||
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
|
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
|
||||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
|
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
|
||||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
|
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
|
||||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
|
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
|
||||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
|
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
|
||||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
|
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
|
||||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
|
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#forward')?.click() },
|
||||||
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
||||||
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
||||||
];
|
];
|
||||||
@@ -39,16 +45,17 @@ function eventShortcut(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function moveMessageSelection(step) {
|
function moveMessageSelection(step) {
|
||||||
|
const messages = shortcutMailUi.state.messages;
|
||||||
if (!messages.length) return;
|
if (!messages.length) return;
|
||||||
const index = messages.findIndex(message => message.id === activeMessage);
|
const index = messages.findIndex(message => message.id === shortcutMailUi.state.activeMessage);
|
||||||
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
||||||
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
if (next) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('keydown', event => {
|
document.addEventListener('keydown', event => {
|
||||||
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
||||||
const target = event.target;
|
const target = event.target;
|
||||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
|
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || selectShortcutUi('#modal-root')?.children.length) return;
|
||||||
const pressed = eventShortcut(event);
|
const pressed = eventShortcut(event);
|
||||||
if (!pressed) return;
|
if (!pressed) return;
|
||||||
const shortcuts = loadShortcuts();
|
const shortcuts = loadShortcuts();
|
||||||
@@ -58,18 +65,16 @@ document.addEventListener('keydown', event => {
|
|||||||
action.run();
|
action.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
if (typeof openPreferences === 'function') {
|
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
||||||
const baseOpenPreferences = openPreferences;
|
|
||||||
openPreferences = function () {
|
|
||||||
baseOpenPreferences();
|
baseOpenPreferences();
|
||||||
const fields = $('#modal-root .compose-fields');
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
const save = $('#save-appearance');
|
const save = selectShortcutUi('#save-appearance');
|
||||||
if (!fields || !save) return;
|
if (!fields || !save) return;
|
||||||
const shortcuts = loadShortcuts();
|
const shortcuts = loadShortcuts();
|
||||||
const section = document.createElement('div');
|
const section = document.createElement('div');
|
||||||
section.className = 'shortcut-settings';
|
section.className = 'shortcut-settings';
|
||||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||||
fields.append(section);
|
fields.append(section);
|
||||||
section.addEventListener('keydown', event => {
|
section.addEventListener('keydown', event => {
|
||||||
const input = event.target.closest('.shortcut-input');
|
const input = event.target.closest('.shortcut-input');
|
||||||
@@ -79,7 +84,7 @@ if (typeof openPreferences === 'function') {
|
|||||||
const combo = eventShortcut(event);
|
const combo = eventShortcut(event);
|
||||||
if (combo) input.value = combo;
|
if (combo) input.value = combo;
|
||||||
});
|
});
|
||||||
$('#reset-shortcuts').onclick = () => {
|
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
||||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
section.querySelectorAll('.shortcut-input').forEach(input => {
|
||||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||||
});
|
});
|
||||||
@@ -91,12 +96,12 @@ if (typeof openPreferences === 'function') {
|
|||||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
for (const input of section.querySelectorAll('.shortcut-input')) {
|
||||||
const value = normalizeShortcut(input.value);
|
const value = normalizeShortcut(input.value);
|
||||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||||
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||||
if (value) used.set(value, label);
|
if (value) used.set(value, label);
|
||||||
values[input.dataset.action] = value;
|
values[input.dataset.action] = value;
|
||||||
}
|
}
|
||||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||||
baseSave?.call(save, event);
|
baseSave?.call(save, event);
|
||||||
};
|
};
|
||||||
};
|
});
|
||||||
}
|
})();
|
||||||
|
|||||||
+50
-47
@@ -1,3 +1,7 @@
|
|||||||
|
(() => {
|
||||||
|
const snoozeMailUi = window.epMailFeatures.mail;
|
||||||
|
const snoozeProductivityUi = window.epMailFeatures.productivity;
|
||||||
|
|
||||||
function localDateTimeValue(date) {
|
function localDateTimeValue(date) {
|
||||||
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
||||||
return local.toISOString().slice(0, 16);
|
return local.toISOString().slice(0, 16);
|
||||||
@@ -12,12 +16,12 @@ function nextMorning(daysAhead) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openSnoozeDialog(items) {
|
function openSnoozeDialog(items) {
|
||||||
const eligible = items.filter(message => message?.uid && connectedMailAccount);
|
const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
|
||||||
if (!eligible.length) {
|
if (!eligible.length) {
|
||||||
toast('Snoozing is available for messages in a connected mailbox.');
|
snoozeMailUi.toast('Snoozing is available for messages in a connected mailbox.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const root = $('#modal-root');
|
const root = snoozeMailUi.select('#modal-root');
|
||||||
const tomorrow = nextMorning(1);
|
const tomorrow = nextMorning(1);
|
||||||
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
|
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
|
||||||
@@ -29,7 +33,7 @@ function openSnoozeDialog(items) {
|
|||||||
|
|
||||||
const schedule = async dueAt => {
|
const schedule = async dueAt => {
|
||||||
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
|
||||||
$('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
snoozeMailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const buttons = [...root.querySelectorAll('button')];
|
const buttons = [...root.querySelectorAll('button')];
|
||||||
@@ -37,7 +41,7 @@ function openSnoozeDialog(items) {
|
|||||||
try {
|
try {
|
||||||
for (const message of eligible) {
|
for (const message of eligible) {
|
||||||
const sourceFolder = message.sourceFolder ||
|
const sourceFolder = message.sourceFolder ||
|
||||||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox');
|
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.activeFolder : 'Inbox');
|
||||||
await window.daybreakMail.setSnooze({
|
await window.daybreakMail.setSnooze({
|
||||||
uid: message.uid,
|
uid: message.uid,
|
||||||
folder: sourceFolder,
|
folder: sourceFolder,
|
||||||
@@ -47,11 +51,11 @@ function openSnoozeDialog(items) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
close();
|
close();
|
||||||
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
|
||||||
selectedIds.clear();
|
snoozeMailUi.state.selectedIds.clear();
|
||||||
await syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
$('#snooze-status').textContent = error.message || 'Could not set the reminder.';
|
snoozeMailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.';
|
||||||
buttons.forEach(button => { button.disabled = false; });
|
buttons.forEach(button => { button.disabled = false; });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -59,8 +63,8 @@ function openSnoozeDialog(items) {
|
|||||||
root.querySelectorAll('[data-snooze-at]').forEach(button => {
|
root.querySelectorAll('[data-snooze-at]').forEach(button => {
|
||||||
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
|
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
|
||||||
});
|
});
|
||||||
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime());
|
snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
|
||||||
$('#snooze-custom-time').focus();
|
snoozeMailUi.select('#snooze-custom-time').focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function unsnoozeMessage(message) {
|
function unsnoozeMessage(message) {
|
||||||
@@ -70,13 +74,13 @@ function unsnoozeMessage(message) {
|
|||||||
sourceFolder,
|
sourceFolder,
|
||||||
dueAt: null
|
dueAt: null
|
||||||
}).then(async () => {
|
}).then(async () => {
|
||||||
toast('Message returned to its mailbox');
|
snoozeMailUi.toast('Message returned to its mailbox');
|
||||||
await syncMailbox(false, { offset: 0 });
|
await snoozeMailUi.syncMailbox(false, { offset: 0 });
|
||||||
}).catch(error => toast(error.message || 'Could not return the message'));
|
}).catch(error => snoozeMailUi.toast(error.message || 'Could not return the message'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function showMessageActions(message) {
|
function showMessageActions(message) {
|
||||||
const root = $('#modal-root');
|
const root = snoozeMailUi.select('#modal-root');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
|
||||||
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
|
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
|
||||||
root.querySelector('.modal-overlay').onclick = event => {
|
root.querySelector('.modal-overlay').onclick = event => {
|
||||||
@@ -84,25 +88,24 @@ function showMessageActions(message) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderListBeforeSnooze = renderList;
|
snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
|
||||||
renderList = function () {
|
if (snoozeMailUi.state.activeFolder === 'Snoozed') {
|
||||||
if (activeFolder === 'Snoozed') {
|
const originalMessages = snoozeMailUi.state.messages.slice();
|
||||||
const originalMessages = messages.slice();
|
const snoozedMessages = snoozeMailUi.state.messages.filter(message => message.snoozedUntil);
|
||||||
const snoozedMessages = messages.filter(message => message.snoozedUntil);
|
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...snoozedMessages);
|
||||||
messages.splice(0, messages.length, ...snoozedMessages);
|
|
||||||
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
|
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
|
||||||
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
|
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
|
||||||
const folder = activeFolder;
|
const folder = snoozeMailUi.state.activeFolder;
|
||||||
activeFolder = 'Inbox';
|
snoozeMailUi.state.activeFolder = 'Inbox';
|
||||||
baseMessageRenderer();
|
snoozeMailUi.baseRenderList();
|
||||||
activeFolder = folder;
|
snoozeMailUi.state.activeFolder = folder;
|
||||||
originalFlags.forEach(([message, archived, deleted]) => {
|
originalFlags.forEach(([message, archived, deleted]) => {
|
||||||
message.archived = archived;
|
message.archived = archived;
|
||||||
message.deleted = deleted;
|
message.deleted = deleted;
|
||||||
});
|
});
|
||||||
messages.splice(0, messages.length, ...originalMessages);
|
snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
|
||||||
for (const row of $$('.message')) {
|
for (const row of snoozeMailUi.selectAll('.message')) {
|
||||||
const message = messages.find(item => item.id === Number(row.dataset.id));
|
const message = snoozeMailUi.state.messages.find(item => item.id === Number(row.dataset.id));
|
||||||
if (!message?.snoozedUntil) continue;
|
if (!message?.snoozedUntil) continue;
|
||||||
const due = new Date(message.snoozedUntil);
|
const due = new Date(message.snoozedUntil);
|
||||||
row.title = `Reminder ${due.toLocaleString()}`;
|
row.title = `Reminder ${due.toLocaleString()}`;
|
||||||
@@ -111,21 +114,20 @@ renderList = function () {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
renderListBeforeSnooze();
|
return renderListBeforeSnooze();
|
||||||
};
|
});
|
||||||
|
|
||||||
const openMessageBeforeSnooze = openMessage;
|
snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
|
||||||
openMessage = function (id) {
|
|
||||||
openMessageBeforeSnooze(id);
|
openMessageBeforeSnooze(id);
|
||||||
const message = messages.find(item => item.id === id);
|
const message = snoozeMailUi.state.messages.find(item => item.id === id);
|
||||||
const tools = $('.reader-tools');
|
const tools = snoozeMailUi.select('.reader-tools');
|
||||||
if (!message || !tools) return;
|
if (!message || !tools) return;
|
||||||
const snoozed = activeFolder === 'Snoozed';
|
const snoozed = snoozeMailUi.state.activeFolder === 'Snoozed';
|
||||||
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
|
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
|
||||||
};
|
});
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
snoozeMailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
|
||||||
if (window.daybreakMail?.checkSnoozeReminders) {
|
if (window.daybreakMail?.checkSnoozeReminders) {
|
||||||
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
|
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
|
||||||
.catch(error => console.error('Could not check mail reminders:', error));
|
.catch(error => console.error('Could not check mail reminders:', error));
|
||||||
@@ -143,36 +145,37 @@ document.addEventListener('click', event => {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopImmediatePropagation();
|
event.stopImmediatePropagation();
|
||||||
if (action) {
|
if (action) {
|
||||||
const message = messages.find(item => item.id === activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
$('#modal-root').innerHTML = '';
|
snoozeMailUi.select('#modal-root').innerHTML = '';
|
||||||
if (!message) return;
|
if (!message) return;
|
||||||
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
|
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
|
||||||
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
|
else if (action.dataset.messageAction === 'label') snoozeProductivityUi.addMessageLabel(message);
|
||||||
else {
|
else {
|
||||||
const type = action.dataset.messageAction;
|
const type = action.dataset.messageAction;
|
||||||
messageAction(message, type).then(() => {
|
messageAction(message, type).then(() => {
|
||||||
if (type === 'unread') message.unread = true;
|
if (type === 'unread') message.unread = true;
|
||||||
if (type === 'inbox') message.archived = false;
|
if (type === 'inbox') message.archived = false;
|
||||||
renderList();
|
snoozeMailUi.renderList();
|
||||||
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
|
||||||
}).catch(error => toast(error.message || 'Could not update the message'));
|
}).catch(error => snoozeMailUi.toast(error.message || 'Could not update the message'));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (unsnooze) {
|
if (unsnooze) {
|
||||||
const message = messages.find(item => item.id === activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
if (message) unsnoozeMessage(message);
|
if (message) unsnoozeMessage(message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (snooze?.id === 'snooze-selected') {
|
if (snooze?.id === 'snooze-selected') {
|
||||||
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id)));
|
openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (more) {
|
if (more) {
|
||||||
const message = messages.find(item => item.id === activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
if (message) showMessageActions(message);
|
if (message) showMessageActions(message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const message = messages.find(item => item.id === activeMessage);
|
const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
|
||||||
if (message) openSnoozeDialog([message]);
|
if (message) openSnoozeDialog([message]);
|
||||||
}, true);
|
}, true);
|
||||||
|
})();
|
||||||
|
|||||||
@@ -138,5 +138,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
|||||||
.pgp-trust{margin-left:8px}
|
.pgp-trust{margin-left:8px}
|
||||||
|
|
||||||
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
|
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
|
||||||
|
.reader-body img{display:block;max-width:100%;height:auto;margin:12px 0;border-radius:6px}.reader-body table{max-width:100%;border-collapse:collapse}.reader-body th,.reader-body td{border:1px solid var(--line);padding:5px}.remote-image-notice{margin:14px 0 0;padding:12px;border:1px solid #d7a85c;border-radius:8px;background:#fff8e9;color:#664a23;font-size:10px;line-height:1.5}.remote-image-notice p{margin:0 0 8px}.remote-image-notice .reply-button{background:transparent;color:inherit;border-color:#d7a85c}body.ep-wasteland .remote-image-notice{background:#3a3022;color:#e6d1a8;border-color:#806b44}body.ep-daylight .remote-image-notice{background:#fff8e9;color:#664a23;border-color:#d7a85c}
|
||||||
|
|
||||||
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}
|
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createAccountStore } = require('../desktop/account-store.cjs');
|
||||||
|
|
||||||
|
test('account store migrates a legacy single-account record and persists its generated id', async () => {
|
||||||
|
let stored = { email: 'user@example.com', password: 'secret' };
|
||||||
|
let saves = 0;
|
||||||
|
const repository = createAccountStore({
|
||||||
|
async load() { return stored; },
|
||||||
|
async save(value) { stored = value; saves += 1; }
|
||||||
|
}, { createId: () => 'migrated-account' });
|
||||||
|
|
||||||
|
assert.deepEqual(await repository.load(), {
|
||||||
|
accounts: [{ email: 'user@example.com', password: 'secret', id: 'migrated-account' }],
|
||||||
|
activeId: 'migrated-account'
|
||||||
|
});
|
||||||
|
assert.equal(saves, 1);
|
||||||
|
assert.equal(stored.activeId, 'migrated-account');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('account store retains current account records without rewriting them', async () => {
|
||||||
|
const stored = { accounts: [{ id: 'account-1', email: 'user@example.com' }], activeId: 'account-1' };
|
||||||
|
let saves = 0;
|
||||||
|
const repository = createAccountStore({
|
||||||
|
async load() { return stored; },
|
||||||
|
async save() { saves += 1; }
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(await repository.load(), stored);
|
||||||
|
assert.equal(saves, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('account store distinguishes missing records from invalid store failures', async () => {
|
||||||
|
const missing = createAccountStore({ async load() { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); } });
|
||||||
|
const broken = createAccountStore({ async load() { throw new Error('decrypt failed'); } });
|
||||||
|
assert.equal(await missing.load(), null);
|
||||||
|
await assert.rejects(() => broken.load(), /decrypt failed/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||||
|
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
|
||||||
|
const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
|
||||||
|
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
||||||
|
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
||||||
|
|
||||||
|
test('package metadata and lockfile share one release version', () => {
|
||||||
|
assert.equal(packageLock.version, packageJson.version);
|
||||||
|
assert.equal(packageLock.packages[''].version, packageJson.version);
|
||||||
|
assert.match(packageJson.version, /^\d+\.\d+\.\d+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android version name and code derive from the canonical package version', () => {
|
||||||
|
assert.match(androidBuild, /parse\(file\("\.\.\/\.\.\/package\.json"\)\)\.version/);
|
||||||
|
assert.match(androidBuild, /versionName appVersion/);
|
||||||
|
assert.match(androidBuild, /versionCode appVersionParts\[0\] \* 10000 \+ appVersionParts\[1\] \* 100 \+ appVersionParts\[2\]/);
|
||||||
|
|
||||||
|
const parts = packageJson.version.split('.').map(Number);
|
||||||
|
const expectedCode = parts[0] * 10000 + parts[1] * 100 + parts[2];
|
||||||
|
assert.ok(Number.isSafeInteger(expectedCode) && expectedCode > 0);
|
||||||
|
assert.ok(parts[1] < 100 && parts[2] < 100, 'update the Android versionCode mapping before minor or patch reaches 100');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('release scripts and desktop artifact labels use package.json version', () => {
|
||||||
|
assert.match(buildAll, /package\.json/);
|
||||||
|
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
||||||
|
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { makeCalendarData, makeVcard } = require('../desktop/dav-codecs.cjs');
|
||||||
|
|
||||||
|
test('serializes calendar events with escaped values and stable injected identifiers', () => {
|
||||||
|
const data = makeCalendarData({
|
||||||
|
date: '2026-10-16',
|
||||||
|
title: 'Review, plan; follow-up',
|
||||||
|
place: 'Room A, west',
|
||||||
|
notes: 'First line\nSecond line',
|
||||||
|
_dav: { uid: 'event-1' }
|
||||||
|
}, { now: () => new Date('2026-10-16T12:34:56.000Z') });
|
||||||
|
|
||||||
|
assert.match(data, /UID:event-1\r\n/);
|
||||||
|
assert.match(data, /DTSTAMP:20261016T123456Z\r\n/);
|
||||||
|
assert.match(data, /DTSTART;VALUE=DATE:20261016\r\n/);
|
||||||
|
assert.match(data, /SUMMARY:Review\\, plan\\; follow-up\r\n/);
|
||||||
|
assert.match(data, /LOCATION:Room A\\, west\r\n/);
|
||||||
|
assert.match(data, /DESCRIPTION:First line\\nSecond line\r\n/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('serializes contacts with escaped fields and an injected identifier', () => {
|
||||||
|
const data = makeVcard({
|
||||||
|
name: 'Ada Example Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
note: 'Research, analysis; mathematics',
|
||||||
|
_dav: { uid: 'contact-1' }
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(data,
|
||||||
|
'BEGIN:VCARD\r\nVERSION:3.0\r\nUID:contact-1\r\nFN:Ada Example Lovelace\r\n' +
|
||||||
|
'N:Example Lovelace;Ada;;;\r\nEMAIL:ada@example.com\r\n' +
|
||||||
|
'NOTE:Research\\, analysis\\; mathematics\r\nEND:VCARD\r\n');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects DAV identifiers that can inject fields or escape resource paths', () => {
|
||||||
|
assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: 'good\r\nX-Evil: yes' } }), /identifier is invalid/);
|
||||||
|
assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: '../other' } }), /identifier is invalid/);
|
||||||
|
assert.throws(() => makeVcard({ name: 'Bad', email: 'x@example.test', _dav: { uid: 'x'.repeat(256) } }), /identifier is invalid/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { registerDavIpcHandlers } = require('../desktop/ipc/dav.cjs');
|
||||||
|
|
||||||
|
test('registers the complete DAV IPC surface through the shared boundary', () => {
|
||||||
|
const registered = [];
|
||||||
|
registerDavIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { registered.push({ channel, handler }); },
|
||||||
|
readDavStore() {},
|
||||||
|
saveDavStore() {},
|
||||||
|
davPublicConfig() {},
|
||||||
|
openDavClient() {},
|
||||||
|
activeDavConfig() {},
|
||||||
|
ICAL: {},
|
||||||
|
makeCalendarData() {},
|
||||||
|
makeVcard() {},
|
||||||
|
randomUUID() {},
|
||||||
|
assertDavObjectReference() {}
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(registered.map(item => item.channel).sort(), [
|
||||||
|
'dav:activate', 'dav:connect', 'dav:delete-contact', 'dav:delete-event',
|
||||||
|
'dav:list', 'dav:remove', 'dav:save-contact', 'dav:save-event', 'dav:sync'
|
||||||
|
]);
|
||||||
|
assert.ok(registered.every(item => typeof item.handler === 'function'));
|
||||||
|
});
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { assertDavObjectReference } = require('../desktop/dav/remote-reference.cjs');
|
||||||
|
|
||||||
|
const config = { id: 'dav-1', serverUrl: 'https://dav.example.test/' };
|
||||||
|
const collection = { url: 'https://dav.example.test/calendars/user/main/', displayName: 'Main' };
|
||||||
|
const object = { url: 'https://dav.example.test/calendars/user/main/event-1.ics', etag: '"v4"' };
|
||||||
|
const remote = {
|
||||||
|
accountId: 'dav-1',
|
||||||
|
collectionUrl: collection.url,
|
||||||
|
objectUrl: object.url,
|
||||||
|
etag: object.etag
|
||||||
|
};
|
||||||
|
|
||||||
|
test('accepts a resource verified against the configured server, collection, and current ETag', () => {
|
||||||
|
const result = assertDavObjectReference({ config, remote, collections: [collection], objects: [object] });
|
||||||
|
assert.equal(result.collection, collection);
|
||||||
|
assert.equal(result.object, object);
|
||||||
|
assert.equal(result.objectUrl, object.url);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a relative server-returned object URL within its verified collection', () => {
|
||||||
|
const result = assertDavObjectReference({
|
||||||
|
config,
|
||||||
|
remote: { ...remote, objectUrl: 'event-1.ics' },
|
||||||
|
collections: [collection],
|
||||||
|
objects: [{ url: 'event-1.ics', etag: '"v4"' }]
|
||||||
|
});
|
||||||
|
assert.equal(result.objectUrl, object.url);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects account, collection, and resource references not returned by the server', () => {
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, accountId: 'other-account' }, collections: [collection], objects: [object]
|
||||||
|
}), /does not belong/);
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, collectionUrl: 'https://dav.example.test/other/' }, collections: [collection], objects: [object]
|
||||||
|
}), /collection is not available/);
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, objectUrl: 'https://dav.example.test/calendars/user/main/unknown.ics' }, collections: [collection], objects: [object]
|
||||||
|
}), /no longer available/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects cross-origin, credential-bearing, query, traversal, and out-of-collection URLs', () => {
|
||||||
|
for (const objectUrl of [
|
||||||
|
'https://attacker.example/event.ics',
|
||||||
|
'https://user:pass@dav.example.test/calendars/user/main/event-1.ics',
|
||||||
|
'https://dav.example.test/calendars/user/main/event-1.ics?redirect=1',
|
||||||
|
'../other/event.ics',
|
||||||
|
'https://dav.example.test/calendars/user/main/',
|
||||||
|
'https://dav.example.test/calendars/user/other/event.ics'
|
||||||
|
]) {
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, objectUrl }, collections: [collection], objects: [object]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects stale ETags and ETags with unexpected types', () => {
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, etag: '"v3"' }, collections: [collection], objects: [object]
|
||||||
|
}), /changed on the server/);
|
||||||
|
assert.throws(() => assertDavObjectReference({
|
||||||
|
config, remote: { ...remote, etag: 4 }, collections: [collection], objects: [{ ...object, etag: undefined }]
|
||||||
|
}), /version is invalid/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { hasIpcSchema, validateIpcArguments } = require('../desktop/security/ipc-arguments.cjs');
|
||||||
|
|
||||||
|
test('validates supported IPC channels and their positional argument types', () => {
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{ email: 'a@example.com' }]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:list-oauth-providers', []));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:sync-folder', ['Inbox', 0, { hasAttachments: true }]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:disconnect', []));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{ to: 'a@example.com', attachments: [] }]));
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', ['not-an-object']), /Invalid object argument/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:sync-folder', ['Inbox', 'zero']), /Invalid number argument/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:open-external', [null]), /Invalid string argument/);
|
||||||
|
assert.throws(() => validateIpcArguments('pgp:set-trust', ['fingerprint']), /Invalid argument count/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:list-accounts', ['unexpected']), /Invalid argument count/);
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('dav:sync', ['carddav']));
|
||||||
|
assert.throws(() => validateIpcArguments('dav:sync', ['contacts']), /Invalid enum/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:open-external', [`https://example.test/${'x'.repeat(2048)}`]), /too large/);
|
||||||
|
assert.throws(() => validateIpcArguments('pgp:export-public', ['A'.repeat(65)]), /too large/);
|
||||||
|
assert.throws(() => validateIpcArguments('unknown:channel', []), /Unknown IPC channel/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bounds nested payload complexity without limiting attachment byte strings', () => {
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
|
||||||
|
to: 'a@example.com',
|
||||||
|
attachments: [{ filename: 'large.bin', contentBase64: 'A'.repeat(1_000_001) }]
|
||||||
|
}]));
|
||||||
|
assert.throws(() => validateIpcArguments('pgp:add-contact', [{ armoredKey: 'A'.repeat(200_001) }]), /too large/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:save-draft', [{ text: 'x'.repeat(1_000_001) }]), /too large/);
|
||||||
|
let nested = { payload: 1 };
|
||||||
|
for (let index = 0; index < 21; index += 1) nested = { child: nested };
|
||||||
|
assert.throws(() => validateIpcArguments('mail:send', [nested]), /nested too deeply/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:save-draft', [{ values: Array(5001).fill('x') }]), /Too many items/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects non-finite numbers, cycles, and prototype-sensitive fields', () => {
|
||||||
|
assert.throws(() => validateIpcArguments('mail:set-snooze', [{ uid: Infinity }]), /Invalid number/);
|
||||||
|
const cyclic = {};
|
||||||
|
cyclic.self = cyclic;
|
||||||
|
assert.throws(() => validateIpcArguments('mail:save-draft', [cyclic]), /Cyclic value/);
|
||||||
|
const unsafe = Object.create(null);
|
||||||
|
unsafe.constructor = 'unexpected';
|
||||||
|
assert.throws(() => validateIpcArguments('mail:save-draft', [unsafe]), /Unsafe field/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validates channel-specific field shapes, limits, and enums', () => {
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
|
||||||
|
email: 'user@example.test', password: 'secret', displayName: 'User',
|
||||||
|
imapHost: 'imap.example.test', smtpHost: 'smtp.example.test',
|
||||||
|
rules: [{ senderContains: 'alerts', action: 'flag', value: '' }]
|
||||||
|
}]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
}]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:update-account', ['account-1', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'microsoft', reauthorizeOAuth: true
|
||||||
|
}]));
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', [{ authMethod: 'oauth2', oauthProvider: 'other' }]), /oauthProvider/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', [{
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'unknown'
|
||||||
|
}]), /oauthProvider/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:connect', [{ rules: Array(51).fill({ action: 'flag' }) }]), /Invalid argument 1/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: '4', action: 'star' }]), /uid/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: 4, action: 'delete-anything' }]), /action/);
|
||||||
|
assert.throws(() => validateIpcArguments('pgp:add-key-server', [{ name: 'Keys', url: 'https://keys.example.test', protocol: 'ftp' }]), /protocol/);
|
||||||
|
assert.throws(() => validateIpcArguments('dav:save-event', [{ title: 'Event', _dav: { etag: 42 } }]), /_dav.etag/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('prevents renderer-supplied raw SMTP messages while accepting standard compose fields', () => {
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
|
||||||
|
to: 'friend@example.test', cc: '', subject: 'Hello', text: 'Body',
|
||||||
|
attachments: [{ filename: 'note.txt', contentBase64: 'aGVsbG8=' }],
|
||||||
|
pgp: { encrypt: true, sign: false, passphrase: null }
|
||||||
|
}]));
|
||||||
|
assert.doesNotThrow(() => validateIpcArguments('pgp:decrypt-message', [{ folder: 'Inbox', uid: 4, passphrase: null }]));
|
||||||
|
assert.throws(() => validateIpcArguments('mail:send', [{ rawBase64: 'YWJj', envelope: { to: ['victim@example.test'] } }]), /Unsupported message field/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:send', [{ pgp: { encrypt: 'true' } }]), /pgp.encrypt/);
|
||||||
|
assert.throws(() => validateIpcArguments('mail:send', [{ attachments: [{ contentBase64: 123 }] }]), /contentBase64/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every registered main-process IPC handler has a request schema', () => {
|
||||||
|
const mainPath = path.resolve(__dirname, '..', 'desktop', 'main.cjs');
|
||||||
|
const ipcDirectory = path.resolve(__dirname, '..', 'desktop', 'ipc');
|
||||||
|
const sourceFiles = [mainPath, ...fs.readdirSync(ipcDirectory)
|
||||||
|
.filter(name => name.endsWith('.cjs'))
|
||||||
|
.map(name => path.join(ipcDirectory, name))];
|
||||||
|
const channels = sourceFiles.flatMap(file => {
|
||||||
|
const source = fs.readFileSync(file, 'utf8');
|
||||||
|
return [...source.matchAll(/registerIpcHandler\('([^']+)'/g)].map(match => match[1]);
|
||||||
|
});
|
||||||
|
assert.ok(channels.length > 0);
|
||||||
|
for (const channel of channels) {
|
||||||
|
assert.equal(hasIpcSchema(channel), true, `missing IPC request schema: ${channel}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { pathToFileURL } = require('node:url');
|
||||||
|
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('../desktop/security/ipc-sender.cjs');
|
||||||
|
|
||||||
|
function eventFor(url, { subframe = false } = {}) {
|
||||||
|
const mainFrame = { url: subframe ? pathToFileURL(path.resolve('index.html')).href : url };
|
||||||
|
const senderFrame = subframe ? { url } : mainFrame;
|
||||||
|
return { sender: { mainFrame }, senderFrame };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('accepts the trusted top-level application document', () => {
|
||||||
|
const expected = path.resolve('index.html');
|
||||||
|
assert.doesNotThrow(() => assertTrustedIpcSender(
|
||||||
|
eventFor(pathToFileURL(expected).href), expected
|
||||||
|
));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects remote, different-file, query, and hash documents', () => {
|
||||||
|
const expected = path.resolve('index.html');
|
||||||
|
for (const url of [
|
||||||
|
'https://example.com/index.html',
|
||||||
|
pathToFileURL(path.resolve('other.html')).href,
|
||||||
|
`${pathToFileURL(expected).href}?debug=1`,
|
||||||
|
`${pathToFileURL(expected).href}#fragment`
|
||||||
|
]) {
|
||||||
|
assert.throws(() => assertTrustedIpcSender(eventFor(url), expected), /application window/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects subframes and missing sender-frame information', () => {
|
||||||
|
const expected = path.resolve('index.html');
|
||||||
|
const topUrl = pathToFileURL(expected).href;
|
||||||
|
assert.throws(() => assertTrustedIpcSender(eventFor(topUrl, { subframe: true }), expected), /application window/);
|
||||||
|
assert.throws(() => assertTrustedIpcSender({ sender: { mainFrame: {} } }, expected), /application window/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('trusted-navigation policy allows only the app document URL', () => {
|
||||||
|
const expected = path.resolve('index.html');
|
||||||
|
assert.equal(isTrustedApplicationUrl(pathToFileURL(expected).href, expected), true);
|
||||||
|
assert.equal(isTrustedApplicationUrl('https://example.com/', expected), false);
|
||||||
|
assert.equal(isTrustedApplicationUrl(`${pathToFileURL(expected).href}#route`, expected), false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createMessageActionService } = require('../desktop/mail/action-service.cjs');
|
||||||
|
|
||||||
|
function setup({ sourcePath = 'INBOX', usable = true } = {}) {
|
||||||
|
const calls = { actions: [], locks: [], released: 0, logout: 0, updates: 0 };
|
||||||
|
const store = { accounts: [{ id: 'account-1', snoozedMessages: [
|
||||||
|
{ uid: 7, folder: 'Inbox' }, { uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }
|
||||||
|
] }] };
|
||||||
|
const client = {
|
||||||
|
usable,
|
||||||
|
async connect() {},
|
||||||
|
async getMailboxLock(path) {
|
||||||
|
calls.locks.push(path);
|
||||||
|
return { release() { calls.released += 1; } };
|
||||||
|
},
|
||||||
|
async messageFlagsAdd(...args) { calls.actions.push(['flagsAdd', ...args]); },
|
||||||
|
async messageFlagsRemove(...args) { calls.actions.push(['flagsRemove', ...args]); },
|
||||||
|
async messageMove(...args) { calls.actions.push(['move', ...args]); },
|
||||||
|
async messageDelete(...args) { calls.actions.push(['delete', ...args]); },
|
||||||
|
async logout() { calls.logout += 1; }
|
||||||
|
};
|
||||||
|
const service = createMessageActionService({
|
||||||
|
imapClient() { return client; },
|
||||||
|
async folderPath(_client, folder) { return folder === 'Inbox' ? sourcePath : folder; },
|
||||||
|
async findSpecialMailbox(_client, specialUse, _fallbackNames, createName) {
|
||||||
|
calls.actions.push(['find', specialUse, createName]);
|
||||||
|
return specialUse === '\\Archive' ? 'Archive' : 'Trash';
|
||||||
|
},
|
||||||
|
async updateAccountStore(update) { calls.updates += 1; return update(store); }
|
||||||
|
});
|
||||||
|
return { service, calls, store };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('applies star and unread flags with UID addressing and releases the mailbox lock', async () => {
|
||||||
|
const { service, calls } = setup();
|
||||||
|
assert.deepEqual(await service.applyMessageAction({ id: 'account-1' }, { uid: 7, action: 'star', enabled: true }), { ok: true });
|
||||||
|
assert.deepEqual(calls.actions[0], ['flagsAdd', 7, ['\\Flagged'], { uid: true }]);
|
||||||
|
assert.deepEqual(calls.locks, ['INBOX']);
|
||||||
|
assert.equal(calls.released, 1);
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
assert.equal(calls.updates, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moves archived messages and removes their matching snooze entry', async () => {
|
||||||
|
const { service, calls, store } = setup();
|
||||||
|
await service.applyMessageAction({ id: 'account-1' }, { uid: 7, folder: 'Inbox', action: 'archive' });
|
||||||
|
assert.deepEqual(calls.actions, [
|
||||||
|
['find', '\\Archive', 'Archive'],
|
||||||
|
['move', 7, 'Archive', { uid: true }]
|
||||||
|
]);
|
||||||
|
assert.deepEqual(store.accounts[0].snoozedMessages, [{ uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }]);
|
||||||
|
assert.equal(calls.updates, 1);
|
||||||
|
assert.equal(calls.released, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleting in Trash deletes rather than attempting to move a message to itself', async () => {
|
||||||
|
const { service, calls } = setup({ sourcePath: 'Trash' });
|
||||||
|
await service.applyMessageAction({ id: 'account-1' }, { uid: 9, folder: 'Inbox', action: 'delete' });
|
||||||
|
assert.deepEqual(calls.actions, [
|
||||||
|
['find', '\\Trash', 'Trash'],
|
||||||
|
['delete', 9, { uid: true }]
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects invalid message identifiers and actions without opening IMAP', async () => {
|
||||||
|
const { service, calls } = setup();
|
||||||
|
await assert.rejects(() => service.applyMessageAction({}, { uid: 0, action: 'star' }), /could not be identified/);
|
||||||
|
await assert.rejects(() => service.applyMessageAction({}, { uid: 1, action: 'expunge' }), /not supported/);
|
||||||
|
assert.equal(calls.locks.length, 0);
|
||||||
|
assert.equal(calls.logout, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createAttachmentService } = require('../desktop/mail/attachment-service.cjs');
|
||||||
|
|
||||||
|
function setup({ mailboxPath = 'INBOX', item = { source: Buffer.from('message') }, attachments = [] } = {}) {
|
||||||
|
const calls = { loggedOut: 0, locksReleased: 0, saved: [], dialogOptions: [], parsedSources: [] };
|
||||||
|
const client = {
|
||||||
|
usable: true,
|
||||||
|
async connect() {},
|
||||||
|
async getMailboxLock(path) {
|
||||||
|
assert.equal(path, mailboxPath);
|
||||||
|
return { release() { calls.locksReleased += 1; } };
|
||||||
|
},
|
||||||
|
async fetchOne(uid, query, options) {
|
||||||
|
assert.equal(uid, 4);
|
||||||
|
assert.deepEqual(query, { uid: true, source: true });
|
||||||
|
assert.deepEqual(options, { uid: true });
|
||||||
|
return item;
|
||||||
|
},
|
||||||
|
async logout() { calls.loggedOut += 1; }
|
||||||
|
};
|
||||||
|
const service = createAttachmentService({
|
||||||
|
imapClient() { return client; },
|
||||||
|
async folderPath(_client, folder) { return folder === 'Missing' ? null : mailboxPath; },
|
||||||
|
async parseForAttachments(source) {
|
||||||
|
calls.parsedSources.push(source);
|
||||||
|
return { attachments };
|
||||||
|
},
|
||||||
|
async writeFile(filePath, content) { calls.saved.push({ filePath, content }); }
|
||||||
|
});
|
||||||
|
return { service, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('saves the requested attachment using a sanitized dialog default path', async () => {
|
||||||
|
const bytes = Buffer.from('contents');
|
||||||
|
const { service, calls } = setup({ attachments: [{ filename: 'reports/annual:2026.txt', content: bytes }] });
|
||||||
|
const result = await service.saveAttachment({ id: 'account-1' }, {
|
||||||
|
uid: 4, folder: 'Inbox', filename: 'reports/annual:2026.txt'
|
||||||
|
}, async options => {
|
||||||
|
calls.dialogOptions.push(options);
|
||||||
|
return { canceled: false, filePath: 'C:/exports/report.txt' };
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result, { saved: true });
|
||||||
|
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'reports_annual_2026.txt' }]);
|
||||||
|
assert.equal(calls.saved[0].filePath, 'C:/exports/report.txt');
|
||||||
|
assert.deepEqual(calls.saved[0].content, bytes);
|
||||||
|
assert.equal(calls.locksReleased, 1);
|
||||||
|
assert.equal(calls.loggedOut, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cancellation does not write attachment bytes and save falls back to the first attachment', async () => {
|
||||||
|
const { service, calls } = setup({ attachments: [{ filename: 'first.txt', content: Buffer.from('first') }] });
|
||||||
|
const result = await service.saveAttachment({ id: 'account-1' }, { uid: 4 }, async options => {
|
||||||
|
calls.dialogOptions.push(options);
|
||||||
|
return { canceled: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result, { canceled: true });
|
||||||
|
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'first.txt' }]);
|
||||||
|
assert.equal(calls.saved.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('previews supported image and text attachments with explicit size bounds', async () => {
|
||||||
|
const imageBytes = Buffer.from([1, 2, 3]);
|
||||||
|
const imageService = setup({ attachments: [{ filename: 'image.png', contentType: 'image/png', content: imageBytes }] }).service;
|
||||||
|
assert.deepEqual(await imageService.previewAttachment({}, { uid: 4, filename: 'image.png' }), {
|
||||||
|
kind: 'image', dataUrl: `data:image/png;base64,${imageBytes.toString('base64')}`
|
||||||
|
});
|
||||||
|
|
||||||
|
const largeImage = setup({ attachments: [{ filename: 'large.png', contentType: 'image/png', content: Buffer.alloc(5 * 1048576 + 1) }] }).service;
|
||||||
|
assert.deepEqual(await largeImage.previewAttachment({}, { uid: 4, filename: 'large.png' }), {
|
||||||
|
kind: 'none', reason: 'This image is too large to preview. Download it instead.'
|
||||||
|
});
|
||||||
|
|
||||||
|
const textBytes = Buffer.from('hello');
|
||||||
|
const textService = setup({ attachments: [{ filename: 'note.txt', contentType: 'text/plain; charset=utf-8', content: textBytes }] }).service;
|
||||||
|
assert.deepEqual(await textService.previewAttachment({}, { uid: 4, filename: 'note.txt' }), {
|
||||||
|
kind: 'text', text: 'hello', truncated: false
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects invalid identifiers, missing messages, folders, and attachment names', async () => {
|
||||||
|
const { service, calls } = setup({ item: null });
|
||||||
|
await assert.rejects(() => service.previewAttachment({}, { uid: 0 }), /could not be identified/);
|
||||||
|
await assert.rejects(() => service.previewAttachment({}, { uid: 4 }), /no longer available/);
|
||||||
|
assert.equal(calls.loggedOut, 1);
|
||||||
|
|
||||||
|
const missingFolder = setup().service;
|
||||||
|
await assert.rejects(() => missingFolder.previewAttachment({}, { uid: 4, folder: 'Missing' }), /folder could not be found/);
|
||||||
|
const noAttachment = setup().service;
|
||||||
|
await assert.rejects(() => noAttachment.previewAttachment({}, { uid: 4, filename: 'unknown.txt' }), /No attachment/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
|
||||||
|
|
||||||
|
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
|
||||||
|
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
|
||||||
|
const [file] = normalizeOutgoingAttachments([{
|
||||||
|
filename: 'folder\\report.bin',
|
||||||
|
contentType: 'APPLICATION/OCTET-STREAM',
|
||||||
|
size: 999,
|
||||||
|
contentBase64: bytes.toString('base64')
|
||||||
|
}]);
|
||||||
|
|
||||||
|
assert.equal(file.filename, 'report.bin');
|
||||||
|
assert.equal(file.contentType, 'application/octet-stream');
|
||||||
|
assert.equal(file.size, bytes.length);
|
||||||
|
assert.deepEqual(file.content, bytes);
|
||||||
|
const [serialized] = serializeOutgoingAttachments([file]);
|
||||||
|
assert.equal(serialized.contentBase64, bytes.toString('base64'));
|
||||||
|
assert.equal('content' in serialized, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects malformed attachment data and unsafe content types', () => {
|
||||||
|
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
|
||||||
|
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
|
||||||
|
assert.throws(() => normalizeOutgoingAttachments([{
|
||||||
|
filename: 'x',
|
||||||
|
contentType: 'text/plain\r\nBcc: bad@example.com',
|
||||||
|
contentBase64: ''
|
||||||
|
}]), /content type.*invalid/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('uses fallback names and MIME types for empty metadata', () => {
|
||||||
|
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
|
||||||
|
assert.equal(file.filename, 'attachment');
|
||||||
|
assert.equal(file.contentType, 'application/octet-stream');
|
||||||
|
assert.equal(file.size, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createMailContentSecurity } = require('../mail-content-security.js');
|
||||||
|
|
||||||
|
test('exposes an immutable mail-content security API', () => {
|
||||||
|
const api = createMailContentSecurity({});
|
||||||
|
assert.equal(Object.isFrozen(api), true);
|
||||||
|
assert.equal(typeof api.safeRemoteImageUrl, 'function');
|
||||||
|
assert.equal(typeof api.sanitizeMailHtml, 'function');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows only bounded HTTPS remote image URLs without embedded credentials', () => {
|
||||||
|
const { safeRemoteImageUrl } = createMailContentSecurity({});
|
||||||
|
assert.equal(safeRemoteImageUrl('https://images.example.test/pixel.png'), 'https://images.example.test/pixel.png');
|
||||||
|
assert.equal(safeRemoteImageUrl('HTTPs://images.example.test/pixel.png'), 'https://images.example.test/pixel.png');
|
||||||
|
assert.equal(safeRemoteImageUrl('http://images.example.test/pixel.png'), null);
|
||||||
|
assert.equal(safeRemoteImageUrl('data:image/png;base64,AAAA'), null);
|
||||||
|
assert.equal(safeRemoteImageUrl('https://user:pass@images.example.test/pixel.png'), null);
|
||||||
|
assert.equal(safeRemoteImageUrl(`https://images.example.test/${'x'.repeat(2050)}`), null);
|
||||||
|
assert.equal(safeRemoteImageUrl('not a URL'), null);
|
||||||
|
assert.equal(safeRemoteImageUrl(null), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sanitizes parsed mail DOM and keeps approved remote images inert', () => {
|
||||||
|
let parsedHtml = '';
|
||||||
|
const createElement = (localName, attributes = {}, childNodes = []) => {
|
||||||
|
const values = new Map(Object.entries(attributes));
|
||||||
|
const element = {
|
||||||
|
nodeType: 1,
|
||||||
|
localName,
|
||||||
|
childNodes,
|
||||||
|
parentNode: null,
|
||||||
|
get attributes() { return [...values].map(([name, value]) => ({ name, value })); },
|
||||||
|
getAttribute(name) { return values.get(name) ?? null; },
|
||||||
|
setAttribute(name, value) { values.set(name, String(value)); },
|
||||||
|
removeAttribute(name) { values.delete(name); },
|
||||||
|
remove() {
|
||||||
|
if (this.parentNode) this.parentNode.childNodes.splice(this.parentNode.childNodes.indexOf(this), 1);
|
||||||
|
},
|
||||||
|
get innerHTML() {
|
||||||
|
const attributes = [...values].map(([name, value]) => ` ${name}="${value}"`).join('');
|
||||||
|
if (this.localName === 'img') return `<img${attributes}>`;
|
||||||
|
const contents = childNodes.map(child => child.nodeType === 3 ? child.textContent : child.innerHTML).join('');
|
||||||
|
return `<${this.localName}${attributes}>${contents}</${this.localName}>`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (const child of childNodes) child.parentNode = element;
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
const body = {
|
||||||
|
childNodes: [],
|
||||||
|
get innerHTML() { return this.childNodes.map(child => child.innerHTML).join(''); }
|
||||||
|
};
|
||||||
|
const browserRoot = {
|
||||||
|
Node: { ELEMENT_NODE: 1, TEXT_NODE: 3 },
|
||||||
|
DOMParser: class {
|
||||||
|
parseFromString(html) {
|
||||||
|
parsedHtml = html;
|
||||||
|
const url = html.match(/data-remote-src="([^"]+)"/)?.[1] || '';
|
||||||
|
body.childNodes = [
|
||||||
|
createElement('script', {}, [{ nodeType: 3, textContent: 'alert(1)' }]),
|
||||||
|
createElement('p', { onclick: 'alert(2)' }, [{ nodeType: 3, textContent: 'Hello' }]),
|
||||||
|
createElement('img', { src: url, 'data-remote-src': url, alt: 'pixel', onerror: 'alert(3)' })
|
||||||
|
];
|
||||||
|
body.childNodes.forEach(child => { child.parentNode = body; });
|
||||||
|
return { body };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const { html, remoteImageCount } = createMailContentSecurity(browserRoot).sanitizeMailHtml(
|
||||||
|
'<p onclick="alert(2)">Hello</p><script>alert(1)</script><img src="https://images.example.test/pixel.png" onerror="alert(3)"><a href="javascript:alert(4)">link</a>'
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.doesNotMatch(parsedHtml, /<script\b|\shref\s*=|\ssrc\s*=/i);
|
||||||
|
assert.match(parsedHtml, /<img data-remote-src="https:\/\/images\.example\.test\/pixel\.png">/);
|
||||||
|
assert.equal(remoteImageCount, 1);
|
||||||
|
assert.equal(html, '<p>Hello</p><img data-remote-src="https://images.example.test/pixel.png" alt="pixel">');
|
||||||
|
assert.doesNotMatch(html, /onclick|onerror|javascript:|<script/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { extractMailContent } = require('../desktop/mail-content.cjs');
|
||||||
|
|
||||||
|
test('extracts bounded display content, links, and non-PGP attachment metadata', () => {
|
||||||
|
const result = extractMailContent({
|
||||||
|
text: 'First paragraph\r\n\r\nSecond paragraph',
|
||||||
|
html: '<a href="https://example.com/a?x=1&y=2">one</a><a href="/next">two</a>',
|
||||||
|
attachments: [
|
||||||
|
{ filename: 'signature.asc', contentType: 'application/pgp-signature', size: 20 },
|
||||||
|
{ filename: 'report.pdf', contentType: 'application/pdf', size: 1048576 }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.bodyText, 'First paragraph\n\nSecond paragraph');
|
||||||
|
assert.deepEqual(result.body, ['First paragraph', 'Second paragraph']);
|
||||||
|
assert.deepEqual(result.links, ['https://example.com/a?x=1&y=2', '/next']);
|
||||||
|
assert.deepEqual(result.attachments, [{ filename: 'report.pdf', size: 1048576 }]);
|
||||||
|
assert.equal(result.attachment, 'report.pdf');
|
||||||
|
assert.equal(result.size, '1.0 MB');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bounds text, HTML, and links and supplies an empty-body fallback', () => {
|
||||||
|
const result = extractMailContent({
|
||||||
|
text: `${'x'.repeat(20001)}\n\n${Array.from({ length: 45 }, (_, index) => `p${index}`).join('\n\n')}`,
|
||||||
|
html: `${'<a href="https://example.com">link</a>'.repeat(31)}${'h'.repeat(100001)}`
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.bodyText.length, 20000);
|
||||||
|
assert.equal(result.body.length, 1);
|
||||||
|
assert.equal(result.html.length, 100000);
|
||||||
|
assert.equal(result.links.length, 30);
|
||||||
|
|
||||||
|
const empty = extractMailContent({});
|
||||||
|
assert.deepEqual(empty.body, ['This message has no plain-text body.']);
|
||||||
|
assert.deepEqual(empty.attachments, []);
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createFolderService } = require('../desktop/mail/folders.cjs');
|
||||||
|
const { isReservedFolderName } = require('../desktop/mail-model.cjs');
|
||||||
|
|
||||||
|
function clientWith(mailboxes = []) {
|
||||||
|
const created = [];
|
||||||
|
return {
|
||||||
|
created,
|
||||||
|
async list() { return mailboxes; },
|
||||||
|
async mailboxCreate(name) {
|
||||||
|
created.push(name);
|
||||||
|
const mailbox = { path: name, name };
|
||||||
|
mailboxes.push(mailbox);
|
||||||
|
return mailbox;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const folders = createFolderService({ isReservedFolderName });
|
||||||
|
|
||||||
|
test('resolves special-use folders before provider-specific fallback names', async () => {
|
||||||
|
const client = clientWith([
|
||||||
|
{ path: 'Sent Items', specialUse: null },
|
||||||
|
{ path: 'Provider/Sent', specialUse: '\\Sent' }
|
||||||
|
]);
|
||||||
|
assert.equal(await folders.findSpecialMailbox(client, '\\Sent', ['sent', 'sent items']), 'Provider/Sent');
|
||||||
|
assert.equal(await folders.findSpecialMailbox(client, '\\Archive', ['archive']), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('creates a missing special mailbox only when requested', async () => {
|
||||||
|
const client = clientWith([]);
|
||||||
|
assert.equal(await folders.findSentMailbox(client), null);
|
||||||
|
assert.equal(client.created.length, 0);
|
||||||
|
assert.equal(await folders.findSentMailbox(client, true), 'Sent');
|
||||||
|
assert.deepEqual(client.created, ['Sent']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('maps built-in folder labels and validates custom folder paths', async () => {
|
||||||
|
const client = clientWith([
|
||||||
|
{ path: 'INBOX', name: 'INBOX' },
|
||||||
|
{ path: 'Sent Items', name: 'Sent Items' },
|
||||||
|
{ path: 'ArchiveBox', name: 'ArchiveBox' },
|
||||||
|
{ path: 'Projects/2026', name: '2026' },
|
||||||
|
{ path: 'Private', name: 'Private', flags: new Set(['\\Noselect']) }
|
||||||
|
]);
|
||||||
|
assert.equal(await folders.folderPath(client, 'Inbox'), 'INBOX');
|
||||||
|
assert.equal(await folders.folderPath(client, 'Starred'), 'INBOX');
|
||||||
|
assert.equal(await folders.folderPath(client, 'Sent'), 'Sent Items');
|
||||||
|
assert.equal(await folders.folderPath(client, 'Folder:Projects/2026'), 'Projects/2026');
|
||||||
|
await assert.rejects(() => folders.folderPath(client, 'Folder:Private'), /not available/);
|
||||||
|
await assert.rejects(() => folders.folderPath(client, 'Folder:Missing'), /not available/);
|
||||||
|
await assert.rejects(() => folders.folderPath(client, 'Unknown'), /not available/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lists sorted custom folders and excludes reserved and non-selectable mailboxes', async () => {
|
||||||
|
const client = clientWith([
|
||||||
|
{ path: 'INBOX', name: 'INBOX' },
|
||||||
|
{ path: 'Sent Items', name: 'Sent Items' },
|
||||||
|
{ path: 'Projects/Zeta', name: 'Zeta' },
|
||||||
|
{ path: 'Projects/Alpha', name: 'Alpha' },
|
||||||
|
{ path: 'Junk', name: 'Junk' },
|
||||||
|
{ path: 'NoSelect', name: 'NoSelect', flags: new Set(['\\Noselect']) },
|
||||||
|
{ path: 'Archive', name: 'Archive', specialUse: '\\Archive' }
|
||||||
|
]);
|
||||||
|
assert.deepEqual(await folders.listCustomFolders(client), [
|
||||||
|
{ name: 'Alpha', path: 'Projects/Alpha', id: 'Folder:Projects/Alpha' },
|
||||||
|
{ name: 'Zeta', path: 'Projects/Zeta', id: 'Folder:Projects/Zeta' }
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { EventEmitter } = require('node:events');
|
||||||
|
const { createIdleWatcherManager } = require('../desktop/mail/idle-watcher-manager.cjs');
|
||||||
|
|
||||||
|
function setup(accounts, { concurrency = 2, generations = new Map(accounts.map(account => [account.id, 0])) } = {}) {
|
||||||
|
const calls = { clients: [], requests: 0, loggedOut: 0, closed: 0, mailboxOpens: [], errors: [] };
|
||||||
|
const manager = createIdleWatcherManager({
|
||||||
|
async readAccountStore() { return { accounts }; },
|
||||||
|
async readAccount(accountId) { return accounts.find(account => account.id === accountId) || null; },
|
||||||
|
imapClient(account, options) {
|
||||||
|
const client = new EventEmitter();
|
||||||
|
client.usable = true;
|
||||||
|
client.connect = async () => {};
|
||||||
|
client.mailboxOpen = async (...args) => { calls.mailboxOpens.push(args); };
|
||||||
|
client.logout = async () => { calls.loggedOut += 1; client.usable = false; };
|
||||||
|
client.close = () => { calls.closed += 1; client.emit('close'); };
|
||||||
|
calls.clients.push({ account, options, client });
|
||||||
|
return client;
|
||||||
|
},
|
||||||
|
backgroundSyncGenerations: generations,
|
||||||
|
concurrency,
|
||||||
|
wait: () => new Promise(() => {}),
|
||||||
|
logError(...args) { calls.errors.push(args); }
|
||||||
|
});
|
||||||
|
manager.setRequestBackgroundSync(() => { calls.requests += 1; });
|
||||||
|
return { manager, calls, generations };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('starts only the configured number of IDLE watchers and reconciles updates', async () => {
|
||||||
|
const accounts = [
|
||||||
|
{ id: 'one', email: 'one@example.com' },
|
||||||
|
{ id: 'two', email: 'two@example.com' },
|
||||||
|
{ id: 'three', email: 'three@example.com' }
|
||||||
|
];
|
||||||
|
const { manager, calls } = setup(accounts, { concurrency: 2 });
|
||||||
|
await manager.reconcileIdleWatchers();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
|
||||||
|
assert.deepEqual(calls.clients.map(item => item.account.id), ['one', 'two']);
|
||||||
|
assert.deepEqual(calls.clients[0].options, {
|
||||||
|
autoIdleDelay: 10_000,
|
||||||
|
maxIdleTime: 25 * 60 * 1000,
|
||||||
|
socketTimeout: 30 * 60 * 1000
|
||||||
|
});
|
||||||
|
assert.deepEqual(calls.mailboxOpens, [['INBOX', { readOnly: true }], ['INBOX', { readOnly: true }]]);
|
||||||
|
|
||||||
|
const firstClient = calls.clients[0].client;
|
||||||
|
firstClient.emit('exists', { path: 'INBOX', count: 2, prevCount: 1 });
|
||||||
|
firstClient.emit('exists', { path: 'INBOX', count: 2, prevCount: 2 });
|
||||||
|
firstClient.emit('exists', { path: 'Sent', count: 3, prevCount: 2 });
|
||||||
|
firstClient.emit('flags', { path: 'INBOX' });
|
||||||
|
firstClient.emit('flags', { path: 'Sent' });
|
||||||
|
assert.equal(calls.requests, 2);
|
||||||
|
|
||||||
|
manager.stopAll();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.equal(calls.closed, 2);
|
||||||
|
assert.equal(calls.loggedOut, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops watchers when accounts are removed or their generation changes', async () => {
|
||||||
|
const accounts = [{ id: 'one', email: 'one@example.com' }, { id: 'two', email: 'two@example.com' }];
|
||||||
|
const generations = new Map([['one', 0], ['two', 0]]);
|
||||||
|
const { manager, calls } = setup(accounts, { generations });
|
||||||
|
await manager.reconcileIdleWatchers();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
generations.set('one', 1);
|
||||||
|
accounts.splice(1, 1);
|
||||||
|
await manager.reconcileIdleWatchers();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.equal(calls.closed, 2);
|
||||||
|
assert.equal(calls.loggedOut, 2);
|
||||||
|
manager.stopAll();
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { registerMailIpcHandlers } = require('../desktop/ipc/mail.cjs');
|
||||||
|
|
||||||
|
test('registers mail/account IPC handlers through the shared boundary', () => {
|
||||||
|
const registered = [];
|
||||||
|
const stub = () => {};
|
||||||
|
registerMailIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { registered.push({ channel, handler }); },
|
||||||
|
BrowserWindow: { fromWebContents: stub },
|
||||||
|
dialog: { showSaveDialog: stub, showMessageBox: stub },
|
||||||
|
shell: { openExternal: stub },
|
||||||
|
fs: { writeFile: stub, rm: stub },
|
||||||
|
credentialsPath: stub,
|
||||||
|
readAccount: stub,
|
||||||
|
readAccountStore: stub,
|
||||||
|
saveAccountStore: stub,
|
||||||
|
updateAccountStore: stub,
|
||||||
|
saveAccount: stub,
|
||||||
|
publicAccount: stub,
|
||||||
|
normalizeAccount: stub,
|
||||||
|
connectMail: stub,
|
||||||
|
requestBackgroundSync: stub,
|
||||||
|
CUSTOM_FOLDER_PREFIX: 'Folder:',
|
||||||
|
flushMailOutbox: stub,
|
||||||
|
fetchMailbox: stub,
|
||||||
|
cachedMailbox: stub,
|
||||||
|
listCustomFolders: stub,
|
||||||
|
imapClient: stub,
|
||||||
|
validFolderName: stub,
|
||||||
|
isConnectivityFailure: stub,
|
||||||
|
randomUUID: stub,
|
||||||
|
serializeOutgoingAttachments: stub,
|
||||||
|
normalizeOutgoingAttachments: stub,
|
||||||
|
sendMailSyncUpdate: stub,
|
||||||
|
applyMessageAction: stub,
|
||||||
|
mailOutbox: { queueMessageAction: stub },
|
||||||
|
pgpMail: { detect: stub, decrypt: stub, recipientStatus: stub, build: stub },
|
||||||
|
PgpError: class PgpError extends Error {},
|
||||||
|
simpleParser: stub,
|
||||||
|
folderPath: stub,
|
||||||
|
sendMailNow: stub,
|
||||||
|
pgpFailure: stub
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(registered.map(item => item.channel).sort(), [
|
||||||
|
'mail:connect', 'mail:create-folder', 'mail:delete-draft', 'mail:disconnect',
|
||||||
|
'mail:get-account', 'mail:list-accounts', 'mail:list-drafts', 'mail:list-folders', 'mail:list-oauth-providers',
|
||||||
|
'mail:open-external', 'mail:preview-attachment', 'mail:remove-account', 'mail:save-attachment',
|
||||||
|
'mail:save-draft', 'mail:select-account', 'mail:send', 'mail:set-snooze',
|
||||||
|
'mail:sync-folder', 'mail:sync-inbox', 'mail:update-account', 'mail:update-message'
|
||||||
|
]);
|
||||||
|
assert.ok(registered.every(item => typeof item.handler === 'function'));
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const {
|
||||||
|
CUSTOM_FOLDER_PREFIX,
|
||||||
|
filterMailboxMessages,
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
validFolderName
|
||||||
|
} = require('../desktop/mail-model.cjs');
|
||||||
|
|
||||||
|
const accountInput = {
|
||||||
|
email: ' user@example.com ',
|
||||||
|
password: 'secret',
|
||||||
|
imapHost: ' imap.example.com ',
|
||||||
|
smtpHost: ' smtp.example.com ',
|
||||||
|
displayName: ' User ',
|
||||||
|
rules: [{ senderContains: 'alerts', action: 'move', value: `${CUSTOM_FOLDER_PREFIX}Archive/Alerts` }]
|
||||||
|
};
|
||||||
|
|
||||||
|
test('normalizes account values and allows only supported mail rules', () => {
|
||||||
|
const account = normalizeAccount(accountInput, { createId: () => 'rule-1' });
|
||||||
|
assert.equal(account.email, 'user@example.com');
|
||||||
|
assert.equal(account.imapHost, 'imap.example.com');
|
||||||
|
assert.equal(account.smtpHost, 'smtp.example.com');
|
||||||
|
assert.equal(account.displayName, 'User');
|
||||||
|
assert.equal(account.imapPort, 143);
|
||||||
|
assert.equal(account.smtpPort, 587);
|
||||||
|
assert.equal(account.rules[0].id, 'rule-1');
|
||||||
|
assert.equal(account.rules[0].value, 'Folder:Archive/Alerts');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects invalid account fields and malformed mail rules', () => {
|
||||||
|
assert.throws(() => normalizeAccount({ ...accountInput, email: 'bad-address' }), /valid email/);
|
||||||
|
assert.throws(() => normalizeAccount({ ...accountInput, displayName: '' }), /display name/);
|
||||||
|
assert.throws(() => normalizeAccount({ ...accountInput, syncIntervalMinutes: 7 }), /sync interval/);
|
||||||
|
assert.throws(() => normalizeAccount({
|
||||||
|
...accountInput,
|
||||||
|
rules: [{ action: 'flag' }]
|
||||||
|
}), /needs a sender or subject condition/);
|
||||||
|
assert.throws(() => normalizeAccount({
|
||||||
|
...accountInput,
|
||||||
|
rules: [{ subjectContains: 'invoice', action: 'move', value: 'Unknown' }]
|
||||||
|
}), /must move messages/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizes OAuth2 accounts to provider servers without requiring a password', () => {
|
||||||
|
const google = normalizeAccount({
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(google.password, '');
|
||||||
|
assert.equal(google.authMethod, 'oauth2');
|
||||||
|
assert.equal(google.oauthProvider, 'google');
|
||||||
|
assert.equal(google.imapHost, 'imap.gmail.com');
|
||||||
|
assert.equal(google.imapPort, 993);
|
||||||
|
assert.equal(google.imapSecure, true);
|
||||||
|
assert.equal(google.smtpHost, 'smtp.gmail.com');
|
||||||
|
const untrustedEndpoints = normalizeAccount({
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User',
|
||||||
|
imapHost: 'attacker.example.test', smtpHost: 'attacker.example.test', imapPort: 143
|
||||||
|
});
|
||||||
|
assert.equal(untrustedEndpoints.imapHost, 'imap.gmail.com');
|
||||||
|
assert.equal(untrustedEndpoints.smtpHost, 'smtp.gmail.com');
|
||||||
|
assert.equal(untrustedEndpoints.imapPort, 993);
|
||||||
|
|
||||||
|
const microsoft = normalizeAccount({
|
||||||
|
email: 'user@outlook.com', authMethod: 'oauth2', oauthProvider: 'microsoft', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(microsoft.imapHost, 'outlook.office365.com');
|
||||||
|
assert.equal(microsoft.smtpHost, 'smtp.office365.com');
|
||||||
|
assert.throws(() => normalizeAccount({ email: 'user@example.test', authMethod: 'oauth2', displayName: 'User' }), /Choose Google or Microsoft/);
|
||||||
|
assert.throws(() => normalizeAccount({ email: 'user@example.test', authMethod: 'oauth', password: 'secret', displayName: 'User' }), /supported sign-in method/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('public account projection does not expose the password or private mailbox state', () => {
|
||||||
|
const account = normalizeAccount(accountInput);
|
||||||
|
const result = publicAccount({
|
||||||
|
...account,
|
||||||
|
id: 'account-1',
|
||||||
|
drafts: [{ text: 'private' }],
|
||||||
|
mailOutbox: [{ data: 'private' }]
|
||||||
|
});
|
||||||
|
assert.equal(result.id, 'account-1');
|
||||||
|
assert.equal(result.email, 'user@example.com');
|
||||||
|
assert.equal('password' in result, false);
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
assert.equal('oauthAccessToken' in result, false);
|
||||||
|
assert.equal('drafts' in result, false);
|
||||||
|
assert.equal('mailOutbox' in result, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validates folder names while allowing ordinary nested server folders as rule targets', () => {
|
||||||
|
assert.equal(validFolderName(' Receipts '), 'Receipts');
|
||||||
|
assert.throws(() => validFolderName(''), /folder name/);
|
||||||
|
assert.throws(() => validFolderName('Inbox'), /reserved/);
|
||||||
|
assert.throws(() => validFolderName('folder/name'), /cannot contain/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('filters messages by text, sender, subject, dates, and attachment presence', () => {
|
||||||
|
const messages = [
|
||||||
|
{
|
||||||
|
sender: 'Alice Example', email: 'alice@example.com', subject: 'Quarterly report',
|
||||||
|
snippet: 'Revenue update', body: ['Please review'], timestamp: Date.parse('2026-03-15T12:00:00Z'),
|
||||||
|
attachments: [{ filename: 'report.pdf' }]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sender: 'Bob Example', email: 'bob@example.com', subject: 'Lunch plans',
|
||||||
|
snippet: 'See you soon', body: [], timestamp: Date.parse('2026-03-16T12:00:00Z'), attachments: []
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.deepEqual(filterMailboxMessages(messages, { query: 'revenue review' }), [messages[0]]);
|
||||||
|
assert.deepEqual(filterMailboxMessages(messages, { sender: 'ALICE' }), [messages[0]]);
|
||||||
|
assert.deepEqual(filterMailboxMessages(messages, { subject: 'report' }), [messages[0]]);
|
||||||
|
assert.deepEqual(filterMailboxMessages(messages, { after: '2026-03-16' }), [messages[1]]);
|
||||||
|
assert.deepEqual(filterMailboxMessages(messages, { hasAttachments: true }), [messages[0]]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { normalizeAccount, publicAccount } = require('../desktop/mail-model.cjs');
|
||||||
|
const { registerMailIpcHandlers } = require('../desktop/ipc/mail.cjs');
|
||||||
|
|
||||||
|
function registerOAuthMailHandlers(overrides = {}) {
|
||||||
|
const handlers = new Map();
|
||||||
|
registerMailIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { handlers.set(channel, handler); },
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
async connectMail() { return { mailbox: 'INBOX', messages: 0 }; },
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
return {
|
||||||
|
...account,
|
||||||
|
oauthAccessToken: 'private-access-token',
|
||||||
|
oauthRefreshToken: 'private-refresh-token',
|
||||||
|
oauthAccessTokenExpiresAt: Date.now() + 3600_000
|
||||||
|
};
|
||||||
|
},
|
||||||
|
listOAuthProviders() { return [{ id: 'google', label: 'Google', configured: true }, { id: 'microsoft', label: 'Microsoft', configured: false }]; },
|
||||||
|
async saveAccount(account) { return { ...account, id: 'oauth-account' }; },
|
||||||
|
requestBackgroundSync() {},
|
||||||
|
randomUUID: () => 'generated-account-id',
|
||||||
|
...overrides
|
||||||
|
});
|
||||||
|
return handlers;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('OAuth account setup authorizes in the main process and never returns tokens to the renderer', async () => {
|
||||||
|
const calls = [];
|
||||||
|
const handlers = registerOAuthMailHandlers({
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
calls.push(['authorize', account.oauthProvider]);
|
||||||
|
return { ...account, oauthAccessToken: 'private-access-token', oauthRefreshToken: 'private-refresh-token', oauthAccessTokenExpiresAt: Date.now() + 3600_000 };
|
||||||
|
},
|
||||||
|
async connectMail(account) {
|
||||||
|
calls.push(['connect', account.authMethod, account.oauthRefreshToken]);
|
||||||
|
return { mailbox: 'INBOX', messages: 0 };
|
||||||
|
},
|
||||||
|
async saveAccount(account) {
|
||||||
|
calls.push(['save', account.oauthRefreshToken]);
|
||||||
|
return { ...account, id: 'oauth-account' };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await handlers.get('mail:connect')({}, {
|
||||||
|
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(calls.map(call => call[0]), ['authorize', 'connect', 'save']);
|
||||||
|
assert.deepEqual(calls[1], ['connect', 'oauth2', 'private-refresh-token']);
|
||||||
|
assert.equal(result.authMethod, 'oauth2');
|
||||||
|
assert.equal(result.oauthProvider, 'google');
|
||||||
|
assert.equal('oauthAccessToken' in result, false);
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
assert.equal('password' in result, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OAuth provider discovery reports configured status without exposing client credentials', async () => {
|
||||||
|
const handlers = registerOAuthMailHandlers();
|
||||||
|
assert.deepEqual(await handlers.get('mail:list-oauth-providers')(), [
|
||||||
|
{ id: 'google', label: 'Google', configured: true },
|
||||||
|
{ id: 'microsoft', label: 'Microsoft', configured: false }
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('editing an OAuth account preserves its token unless the user requests reauthorization', async () => {
|
||||||
|
const existing = {
|
||||||
|
...normalizeAccount({ email: 'user@gmail.com', displayName: 'User', authMethod: 'oauth2', oauthProvider: 'google' }),
|
||||||
|
id: 'oauth-account', oauthAccessToken: 'old-access', oauthRefreshToken: 'old-refresh', oauthAccessTokenExpiresAt: 10
|
||||||
|
};
|
||||||
|
const store = { accounts: [existing] };
|
||||||
|
let authorizations = 0;
|
||||||
|
const handlers = new Map();
|
||||||
|
registerMailIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { handlers.set(channel, handler); },
|
||||||
|
normalizeAccount,
|
||||||
|
publicAccount,
|
||||||
|
async readAccount(id) { return store.accounts.find(account => account.id === id); },
|
||||||
|
async updateAccountStore(update) { return update(store); },
|
||||||
|
async connectMail() { return { mailbox: 'INBOX', messages: 0 }; },
|
||||||
|
async authorizeOAuthAccount(account) {
|
||||||
|
authorizations += 1;
|
||||||
|
return { ...account, oauthAccessToken: 'new-access', oauthRefreshToken: 'new-refresh', oauthAccessTokenExpiresAt: Date.now() + 3600_000 };
|
||||||
|
},
|
||||||
|
requestBackgroundSync() {}
|
||||||
|
});
|
||||||
|
const event = {};
|
||||||
|
|
||||||
|
await handlers.get('mail:update-account')(event, 'oauth-account', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(authorizations, 0);
|
||||||
|
assert.equal(store.accounts[0].oauthRefreshToken, 'old-refresh');
|
||||||
|
|
||||||
|
const result = await handlers.get('mail:update-account')(event, 'oauth-account', {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', reauthorizeOAuth: true, displayName: 'User'
|
||||||
|
});
|
||||||
|
assert.equal(authorizations, 1);
|
||||||
|
assert.equal(store.accounts[0].oauthRefreshToken, 'new-refresh');
|
||||||
|
assert.equal('oauthRefreshToken' in result, false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { applyQueuedActionToCache, createMailOutboxService } = require('../desktop/mail/outbox-service.cjs');
|
||||||
|
|
||||||
|
function setup({ failSend = null, failAction = null, connectivity = () => false } = {}) {
|
||||||
|
const calls = { sends: [], actions: [], errors: [], updates: 0 };
|
||||||
|
const store = { accounts: [{
|
||||||
|
id: 'account-1',
|
||||||
|
mailOutbox: [],
|
||||||
|
mailCache: { Inbox: [{ uid: 7, subject: 'One', star: false }] }
|
||||||
|
}] };
|
||||||
|
const service = createMailOutboxService({
|
||||||
|
async sendMailNow(account, data) {
|
||||||
|
calls.sends.push([account.id, data]);
|
||||||
|
if (failSend) throw failSend;
|
||||||
|
},
|
||||||
|
async applyMessageAction(account, data) {
|
||||||
|
calls.actions.push([account.id, data]);
|
||||||
|
if (failAction) throw failAction;
|
||||||
|
},
|
||||||
|
async updateAccountStore(update) { calls.updates += 1; return update(store); },
|
||||||
|
isConnectivityFailure: connectivity,
|
||||||
|
createId: () => 'queued-action',
|
||||||
|
now: () => 12345,
|
||||||
|
logError(...args) { calls.errors.push(args); }
|
||||||
|
});
|
||||||
|
return { service, calls, store };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('flushes queued sends and actions in order and removes completed operations', async () => {
|
||||||
|
const { service, calls, store } = setup();
|
||||||
|
const account = {
|
||||||
|
id: 'account-1',
|
||||||
|
mailOutbox: [
|
||||||
|
{ id: 'send-1', type: 'send', data: { to: 'a@example.com' } },
|
||||||
|
{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
store.accounts[0].mailOutbox = structuredClone(account.mailOutbox);
|
||||||
|
|
||||||
|
await service.flushMailOutbox(account);
|
||||||
|
assert.deepEqual(calls.sends, [['account-1', { to: 'a@example.com' }]]);
|
||||||
|
assert.deepEqual(calls.actions, [['account-1', { uid: 7, action: 'star' }]]);
|
||||||
|
assert.deepEqual(store.accounts[0].mailOutbox, []);
|
||||||
|
assert.equal(calls.updates, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops at a connectivity failure and leaves the failed and later operations queued', async () => {
|
||||||
|
const networkError = Object.assign(new Error('network down'), { code: 'ECONNRESET' });
|
||||||
|
const { service, calls, store } = setup({ failSend: networkError, connectivity: error => error.code === 'ECONNRESET' });
|
||||||
|
const operations = [
|
||||||
|
{ id: 'send-1', type: 'send', data: {} },
|
||||||
|
{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }
|
||||||
|
];
|
||||||
|
store.accounts[0].mailOutbox = structuredClone(operations);
|
||||||
|
await service.flushMailOutbox({ id: 'account-1', mailOutbox: operations });
|
||||||
|
|
||||||
|
assert.deepEqual(store.accounts[0].mailOutbox, operations);
|
||||||
|
assert.equal(calls.actions.length, 0);
|
||||||
|
assert.equal(calls.errors.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('logs non-connectivity failures and stops without deleting the failed item', async () => {
|
||||||
|
const failure = new Error('invalid queued operation');
|
||||||
|
const { service, calls, store } = setup({ failAction: failure });
|
||||||
|
const operations = [{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }];
|
||||||
|
store.accounts[0].mailOutbox = structuredClone(operations);
|
||||||
|
await service.flushMailOutbox({ id: 'account-1', mailOutbox: operations });
|
||||||
|
|
||||||
|
assert.deepEqual(store.accounts[0].mailOutbox, operations);
|
||||||
|
assert.equal(calls.errors.length, 1);
|
||||||
|
assert.match(calls.errors[0][0], /action-1/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('queues an action once, updates cached message state, and moves it to its optimistic folder', async () => {
|
||||||
|
const { service, store } = setup();
|
||||||
|
const result = await service.queueMessageAction({ id: 'account-1' }, {
|
||||||
|
uid: 7, folder: 'Inbox', action: 'archive'
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result, { ok: true, queued: true });
|
||||||
|
assert.equal(store.accounts[0].mailOutbox.length, 1);
|
||||||
|
assert.deepEqual(store.accounts[0].mailOutbox[0], {
|
||||||
|
id: 'queued-action',
|
||||||
|
type: 'action',
|
||||||
|
data: { uid: 7, folder: 'Inbox', action: 'archive' },
|
||||||
|
createdAt: 12345
|
||||||
|
});
|
||||||
|
assert.equal(store.accounts[0].mailCache.Inbox.length, 0);
|
||||||
|
assert.deepEqual(store.accounts[0].mailCache.Archive[0], {
|
||||||
|
uid: 7, subject: 'One', star: false, sourceFolder: 'Archive', archived: true, deleted: false
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.queueMessageAction({ id: 'account-1' }, { uid: 7, folder: 'Inbox', action: 'archive' });
|
||||||
|
assert.equal(store.accounts[0].mailOutbox.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('optimistic flag changes update the cached record without moving it', () => {
|
||||||
|
const account = { mailCache: { Inbox: [{ uid: 2, star: false }] } };
|
||||||
|
applyQueuedActionToCache(account, { uid: 2, folder: 'Inbox', action: 'star', enabled: true });
|
||||||
|
assert.deepEqual(account.mailCache.Inbox, [{ uid: 2, star: true }]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createMailReader } = require('../desktop/mail/read-service.cjs');
|
||||||
|
|
||||||
|
function setup({ exists = 3, fetched = [], mailboxPath = 'INBOX' } = {}) {
|
||||||
|
const calls = { fetchRanges: [], cached: [], logout: 0, snoozed: [] };
|
||||||
|
const client = {
|
||||||
|
usable: true,
|
||||||
|
async connect() {},
|
||||||
|
async mailboxOpen(path, options) {
|
||||||
|
assert.equal(path, mailboxPath);
|
||||||
|
assert.deepEqual(options, { readOnly: true });
|
||||||
|
return { exists };
|
||||||
|
},
|
||||||
|
async fetchAll(range, query) {
|
||||||
|
calls.fetchRanges.push({ range, query });
|
||||||
|
return fetched.map(item => ({ ...item, flags: item.flags || new Set() }));
|
||||||
|
},
|
||||||
|
async logout() { calls.logout += 1; }
|
||||||
|
};
|
||||||
|
const reader = createMailReader({
|
||||||
|
imapClient() { return client; },
|
||||||
|
async folderPath(_client, folder) { return folder === 'Missing' ? null : mailboxPath; },
|
||||||
|
async toUiMessage(item, folder) {
|
||||||
|
return {
|
||||||
|
uid: Number(item.uid),
|
||||||
|
id: Number(item.uid),
|
||||||
|
folder,
|
||||||
|
sender: item.sender || '',
|
||||||
|
subject: item.subject || '',
|
||||||
|
snippet: item.snippet || '',
|
||||||
|
body: [],
|
||||||
|
timestamp: item.timestamp || 0,
|
||||||
|
tags: [folder]
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async cacheMailboxMessages(accountId, folder, messages) { calls.cached.push({ accountId, folder, messages }); },
|
||||||
|
async fetchSnoozedMailbox(...args) { calls.snoozed.push(args); return { folder: 'Snoozed', messages: [] }; },
|
||||||
|
filterMailboxMessages(messages, filters) {
|
||||||
|
const query = String(filters.query || '').toLowerCase();
|
||||||
|
return messages.filter(message => `${message.sender} ${message.subject} ${message.snippet}`.toLowerCase().includes(query));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { reader, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('fetches the newest page, returns newest first, caches it, and logs out', async () => {
|
||||||
|
const { reader, calls } = setup({
|
||||||
|
fetched: [
|
||||||
|
{ uid: 2, source: Buffer.from('two'), subject: 'Second' },
|
||||||
|
{ uid: 3, source: Buffer.from('three'), subject: 'Third' }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
const result = await reader.fetchMailbox({ id: 'account-1' }, 'Inbox', 0, 2);
|
||||||
|
|
||||||
|
assert.deepEqual(calls.fetchRanges.map(call => call.range), ['2:3']);
|
||||||
|
assert.deepEqual(result.messages.map(message => message.uid), [3, 2]);
|
||||||
|
assert.deepEqual({ total: result.total, start: result.start, end: result.end }, { total: 3, start: 2, end: 3 });
|
||||||
|
assert.equal(calls.cached.length, 1);
|
||||||
|
assert.equal(calls.cached[0].accountId, 'account-1');
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('filtered fetch scans the bounded recent range, excludes snoozed messages, and applies labels', async () => {
|
||||||
|
const { reader, calls } = setup({
|
||||||
|
fetched: [
|
||||||
|
{ uid: 1, source: Buffer.from('one'), sender: 'Alice', subject: 'Needle' },
|
||||||
|
{ uid: 2, source: Buffer.from('two'), sender: 'Bob', subject: 'Other' },
|
||||||
|
{ uid: 3, source: Buffer.from('three'), sender: 'Alice', subject: 'Needle' }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
const result = await reader.fetchMailbox({
|
||||||
|
id: 'account-2',
|
||||||
|
snoozedMessages: [{ uid: 3, folder: 'Inbox', dueAt: Date.now() + 60_000 }],
|
||||||
|
ruleLabels: { 'Inbox:1': ['Important'] }
|
||||||
|
}, 'Inbox', 0, 20, { query: 'needle' });
|
||||||
|
|
||||||
|
assert.deepEqual(calls.fetchRanges.map(call => call.range), ['1:3']);
|
||||||
|
assert.deepEqual(result.messages.map(message => message.uid), [1]);
|
||||||
|
assert.deepEqual(result.messages[0].tags, ['Inbox', 'Important']);
|
||||||
|
assert.deepEqual(calls.cached[0].messages.map(message => message.uid), [1, 2]);
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns an empty result for an unavailable folder and still closes the connection', async () => {
|
||||||
|
const { reader, calls } = setup({ mailboxPath: 'INBOX' });
|
||||||
|
const result = await reader.fetchMailbox({ id: 'account-3' }, 'Missing');
|
||||||
|
assert.deepEqual(result, { messages: [], total: 0 });
|
||||||
|
assert.equal(calls.fetchRanges.length, 0);
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('delegates snoozed-folder reads without opening a separate IMAP client', async () => {
|
||||||
|
const { reader, calls } = setup();
|
||||||
|
const result = await reader.fetchMailbox({ id: 'account-4' }, 'Snoozed', 5, 10);
|
||||||
|
assert.deepEqual(result, { folder: 'Snoozed', messages: [] });
|
||||||
|
assert.deepEqual(calls.snoozed, [[{ id: 'account-4' }, 5, 10]]);
|
||||||
|
assert.equal(calls.logout, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createMailSender } = require('../desktop/mail/send-service.cjs');
|
||||||
|
|
||||||
|
function makeSender({ sentMailboxFails = false, smtpFails = false } = {}) {
|
||||||
|
const calls = { smtp: [], appended: [], closed: 0, loggedOut: 0 };
|
||||||
|
const sender = createMailSender({
|
||||||
|
smtpTransport() {
|
||||||
|
return {
|
||||||
|
async sendMail(message) {
|
||||||
|
calls.smtp.push(message);
|
||||||
|
if (smtpFails) throw new Error('SMTP rejected the message.');
|
||||||
|
return { accepted: ['recipient@example.com'] };
|
||||||
|
},
|
||||||
|
close() { calls.closed += 1; }
|
||||||
|
};
|
||||||
|
},
|
||||||
|
createTransport(options) {
|
||||||
|
assert.deepEqual(options, { streamTransport: true, buffer: true, newline: 'windows' });
|
||||||
|
return {
|
||||||
|
async sendMail(message) { return { message: Buffer.from(JSON.stringify(message)) }; }
|
||||||
|
};
|
||||||
|
},
|
||||||
|
imapClient() {
|
||||||
|
return {
|
||||||
|
usable: true,
|
||||||
|
async connect() {
|
||||||
|
if (sentMailboxFails) throw new Error('IMAP unavailable.');
|
||||||
|
},
|
||||||
|
async getMailboxLock(folder) {
|
||||||
|
assert.equal(folder, 'Sent');
|
||||||
|
return { release() {} };
|
||||||
|
},
|
||||||
|
async search() { return []; },
|
||||||
|
async append(folder, content, flags) { calls.appended.push({ folder, content, flags }); },
|
||||||
|
async logout() { calls.loggedOut += 1; }
|
||||||
|
};
|
||||||
|
},
|
||||||
|
async findSentMailbox(_client, createIfMissing) {
|
||||||
|
assert.equal(createIfMissing, true);
|
||||||
|
return 'Sent';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { ...sender, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('sends a message with bounded fields and attachments, then appends a Sent copy', async () => {
|
||||||
|
const { sendMailNow, calls } = makeSender();
|
||||||
|
const result = await sendMailNow({
|
||||||
|
email: 'sender@example.com', displayName: 'Sender', signature: 'Regards'
|
||||||
|
}, {
|
||||||
|
to: ' recipient@example.com ',
|
||||||
|
subject: 'A subject',
|
||||||
|
text: 'Message body',
|
||||||
|
messageId: '<test@ep-mail.local>',
|
||||||
|
attachments: [{ filename: 'report.txt', contentBase64: Buffer.from('report').toString('base64') }]
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result, { ok: true, savedToSent: true });
|
||||||
|
assert.equal(calls.smtp.length, 1);
|
||||||
|
assert.equal(calls.smtp[0].to, 'recipient@example.com');
|
||||||
|
assert.equal(calls.smtp[0].text, 'Message body\n\nRegards');
|
||||||
|
assert.equal(calls.smtp[0].messageId, '<test@ep-mail.local>');
|
||||||
|
assert.deepEqual(calls.smtp[0].attachments[0].content, Buffer.from('report'));
|
||||||
|
assert.equal(calls.appended.length, 1);
|
||||||
|
assert.equal(calls.appended[0].folder, 'Sent');
|
||||||
|
assert.deepEqual(calls.appended[0].flags, ['\\Seen']);
|
||||||
|
assert.equal(calls.closed, 1);
|
||||||
|
assert.equal(calls.loggedOut, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reports Sent-copy failures without retrying a message accepted by SMTP', async () => {
|
||||||
|
const { sendMailNow, calls } = makeSender({ sentMailboxFails: true });
|
||||||
|
const result = await sendMailNow({ email: 'sender@example.com' }, {
|
||||||
|
to: 'recipient@example.com',
|
||||||
|
text: 'Already sent'
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result, { ok: true, savedToSent: false });
|
||||||
|
assert.equal(calls.smtp.length, 1);
|
||||||
|
assert.equal(calls.closed, 1);
|
||||||
|
assert.equal(calls.appended.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('closes SMTP transport and reports send failures', async () => {
|
||||||
|
const { sendMailNow, calls } = makeSender({ smtpFails: true });
|
||||||
|
await assert.rejects(
|
||||||
|
() => sendMailNow({ email: 'sender@example.com' }, { to: 'recipient@example.com' }),
|
||||||
|
/SMTP rejected/
|
||||||
|
);
|
||||||
|
assert.equal(calls.closed, 1);
|
||||||
|
assert.equal(calls.appended.length, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createSnoozeReminderService } = require('../desktop/mail/snooze-reminder-service.cjs');
|
||||||
|
|
||||||
|
function setup({ accounts, now = 1000, update } = {}) {
|
||||||
|
const calls = { notifications: [], updates: [], errors: [], storesRead: 0 };
|
||||||
|
const store = { accounts };
|
||||||
|
const service = createSnoozeReminderService({
|
||||||
|
async readAccountStore() { calls.storesRead += 1; return store; },
|
||||||
|
async updateAccountStore(callback) { return update ? update(callback, store) : callback(store); },
|
||||||
|
showNotification(reminder) { calls.notifications.push(reminder); },
|
||||||
|
sendMailSyncUpdate(message) { calls.updates.push(message); },
|
||||||
|
now: () => now,
|
||||||
|
logError(...args) { calls.errors.push(args); }
|
||||||
|
});
|
||||||
|
return { service, calls, store };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('removes due reminders, notifies when enabled, and sends UI updates', async () => {
|
||||||
|
const { service, calls, store } = setup({ accounts: [
|
||||||
|
{
|
||||||
|
id: 'account-1', email: 'one@example.com',
|
||||||
|
snoozedMessages: [
|
||||||
|
{ uid: 4, folder: 'Inbox', dueAt: 900, subject: 'Due' },
|
||||||
|
{ uid: 5, folder: 'Sent', dueAt: 1200, subject: 'Later' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'account-2', email: 'two@example.com', notificationsEnabled: false,
|
||||||
|
snoozedMessages: [{ uid: 6, folder: 'Archive', dueAt: 1000, subject: 'Quiet' }]
|
||||||
|
}
|
||||||
|
] });
|
||||||
|
|
||||||
|
await service.checkSnoozeReminders();
|
||||||
|
assert.deepEqual(store.accounts.map(account => account.snoozedMessages), [
|
||||||
|
[{ uid: 5, folder: 'Sent', dueAt: 1200, subject: 'Later' }],
|
||||||
|
[]
|
||||||
|
]);
|
||||||
|
assert.deepEqual(calls.notifications.map(item => item.subject), ['Due']);
|
||||||
|
assert.deepEqual(calls.updates, [
|
||||||
|
{ accountId: 'account-1', snoozeReminder: true, snoozedFolder: 'Inbox', foldersChanged: ['Snoozed', 'Inbox'] },
|
||||||
|
{ accountId: 'account-2', snoozeReminder: true, snoozedFolder: 'Archive', foldersChanged: ['Snoozed', 'Archive'] }
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not write stores when no reminders are due', async () => {
|
||||||
|
let writes = 0;
|
||||||
|
const { service, calls } = setup({
|
||||||
|
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 2000 }] }],
|
||||||
|
update: async callback => { writes += 1; return callback({ accounts: [] }); }
|
||||||
|
});
|
||||||
|
await service.checkSnoozeReminders();
|
||||||
|
assert.equal(writes, 0);
|
||||||
|
assert.equal(calls.notifications.length, 0);
|
||||||
|
assert.equal(calls.updates.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('prevents overlapping reminder sweeps', async () => {
|
||||||
|
let release;
|
||||||
|
const update = () => new Promise(resolve => { release = resolve; });
|
||||||
|
const { service, calls } = setup({
|
||||||
|
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 1, folder: 'Inbox' }] }],
|
||||||
|
update
|
||||||
|
});
|
||||||
|
const first = service.checkSnoozeReminders();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
await service.checkSnoozeReminders();
|
||||||
|
assert.equal(calls.storesRead, 1);
|
||||||
|
release([{ accountId: 'account-1', email: 'one@example.com', folder: 'Inbox', subject: 'Due', notificationsEnabled: true }]);
|
||||||
|
await first;
|
||||||
|
assert.equal(calls.updates.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reports reminder processing failures and permits a later retry', async () => {
|
||||||
|
let fail = true;
|
||||||
|
const { service, calls } = setup({
|
||||||
|
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 1, folder: 'Inbox' }] }],
|
||||||
|
update: async callback => {
|
||||||
|
if (fail) throw new Error('store write failed');
|
||||||
|
return callback({ accounts: [{ id: 'account-1', snoozedMessages: [] }] });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await service.checkSnoozeReminders();
|
||||||
|
assert.equal(calls.errors.length, 1);
|
||||||
|
fail = false;
|
||||||
|
await service.checkSnoozeReminders();
|
||||||
|
assert.equal(calls.errors.length, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createBackgroundSyncCoordinator } = require('../desktop/mail/sync-coordinator.cjs');
|
||||||
|
|
||||||
|
function setup({ accounts = [], sync, clock = 100000, concurrency = 2 } = {}) {
|
||||||
|
let now = clock;
|
||||||
|
const calls = { sync: [], updates: [], notifications: [], errors: [], reconciles: 0, active: 0, maxActive: 0 };
|
||||||
|
const generations = new Map(accounts.map(account => [account.id, 0]));
|
||||||
|
const failures = new Map();
|
||||||
|
const lastSync = new Map();
|
||||||
|
const snapshots = new Map();
|
||||||
|
const coordinator = createBackgroundSyncCoordinator({
|
||||||
|
async readAccountStore() { return { accounts }; },
|
||||||
|
async syncAccountMailboxes(account) {
|
||||||
|
calls.sync.push(account.id);
|
||||||
|
calls.active += 1;
|
||||||
|
calls.maxActive = Math.max(calls.maxActive, calls.active);
|
||||||
|
try {
|
||||||
|
return sync ? await sync(account, calls) : { newCount: 0, changedFolders: [] };
|
||||||
|
} finally {
|
||||||
|
calls.active -= 1;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
backgroundSyncGenerations: generations,
|
||||||
|
backgroundSyncFailures: failures,
|
||||||
|
lastBackgroundSyncAt: lastSync,
|
||||||
|
flagSnapshots: snapshots,
|
||||||
|
async reconcileIdleWatchers() { calls.reconciles += 1; },
|
||||||
|
sendMailSyncUpdate(update) { calls.updates.push(update); },
|
||||||
|
showNewMailNotification(account, count) { calls.notifications.push([account.id, count]); },
|
||||||
|
concurrency,
|
||||||
|
retryIntervalMs: 1000,
|
||||||
|
now: () => now,
|
||||||
|
logError(...args) { calls.errors.push(args); }
|
||||||
|
});
|
||||||
|
return { coordinator, calls, generations, failures, lastSync, snapshots, setNow(value) { now = value; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('sends sync updates and notifications only for the current account generation', async () => {
|
||||||
|
const accounts = [{ id: 'account-1', email: 'one@example.com' }];
|
||||||
|
const { coordinator, calls, generations } = setup({
|
||||||
|
accounts,
|
||||||
|
sync: async () => ({ newCount: 2, changedFolders: ['Inbox'] })
|
||||||
|
});
|
||||||
|
await coordinator.syncAccountWithBackoff(accounts[0]);
|
||||||
|
assert.deepEqual(calls.updates, [{ accountId: 'account-1', newCount: 2, foldersChanged: ['Inbox'] }]);
|
||||||
|
assert.deepEqual(calls.notifications, [['account-1', 2]]);
|
||||||
|
|
||||||
|
calls.updates.length = 0;
|
||||||
|
calls.notifications.length = 0;
|
||||||
|
const pending = coordinator.syncAccountWithBackoff(accounts[0]);
|
||||||
|
generations.set('account-1', 1);
|
||||||
|
await pending;
|
||||||
|
assert.deepEqual(calls.updates, []);
|
||||||
|
assert.deepEqual(calls.notifications, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('applies periodic account intervals and exponential retry backoff', async () => {
|
||||||
|
let attempts = 0;
|
||||||
|
const account = { id: 'account-1', email: 'one@example.com', syncIntervalMinutes: 2 };
|
||||||
|
const { coordinator, calls, failures, lastSync, setNow } = setup({
|
||||||
|
accounts: [account],
|
||||||
|
sync: async () => {
|
||||||
|
attempts += 1;
|
||||||
|
throw new Error('offline');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
lastSync.set(account.id, 99000);
|
||||||
|
await coordinator.syncAccountWithBackoff(account, true);
|
||||||
|
assert.equal(attempts, 0);
|
||||||
|
|
||||||
|
await coordinator.syncAccountWithBackoff(account);
|
||||||
|
assert.deepEqual(failures.get(account.id), { attempts: 1, retryAt: 101000 });
|
||||||
|
await coordinator.syncAccountWithBackoff(account);
|
||||||
|
assert.equal(attempts, 1);
|
||||||
|
assert.equal(calls.updates.length, 1);
|
||||||
|
assert.equal(calls.errors.length, 1);
|
||||||
|
|
||||||
|
setNow(101000);
|
||||||
|
await coordinator.syncAccountWithBackoff(account);
|
||||||
|
assert.deepEqual(failures.get(account.id), { attempts: 2, retryAt: 103000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runs account syncs in bounded concurrent batches', async () => {
|
||||||
|
const accounts = Array.from({ length: 5 }, (_, index) => ({ id: `account-${index}` }));
|
||||||
|
const { coordinator, calls } = setup({
|
||||||
|
accounts,
|
||||||
|
concurrency: 2,
|
||||||
|
sync: async (_account, state) => {
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
state.sync.push('completed');
|
||||||
|
return { newCount: 0, changedFolders: [] };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await coordinator.runBackgroundSync();
|
||||||
|
assert.ok(calls.maxActive <= 2);
|
||||||
|
assert.equal(calls.sync.filter(id => id.startsWith('account-')).length, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('account-specific requests invalidate stale state and force requests clear retry delays', () => {
|
||||||
|
const { coordinator, generations, failures, snapshots } = setup({ accounts: [] });
|
||||||
|
generations.set('account-1', 3);
|
||||||
|
failures.set('account-1', { attempts: 3, retryAt: 999999 });
|
||||||
|
failures.set('account-2', { attempts: 1, retryAt: 999999 });
|
||||||
|
snapshots.set('account-1', new Map());
|
||||||
|
coordinator.requestBackgroundSync('account-1', true);
|
||||||
|
assert.equal(generations.get('account-1'), 4);
|
||||||
|
assert.equal(failures.has('account-1'), false);
|
||||||
|
assert.equal(failures.get('account-2').retryAt, 0);
|
||||||
|
assert.equal(snapshots.has('account-1'), false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { backgroundFolderLabel, createMailboxSyncService } = require('../desktop/mail/sync-service.cjs');
|
||||||
|
|
||||||
|
function setup({ mailboxes, mailboxByPath, fetchResults = {} }) {
|
||||||
|
const calls = { fetches: [], flags: [], moves: [], locksReleased: 0, logout: 0, outbox: 0, labels: 0, saved: null, errors: [] };
|
||||||
|
const generations = new Map([['account-1', 1]]);
|
||||||
|
const snapshots = new Map();
|
||||||
|
const savedStore = { accounts: [{ id: 'account-1', ruleLabels: {} }] };
|
||||||
|
const client = {
|
||||||
|
usable: true,
|
||||||
|
async connect() {},
|
||||||
|
async list() { return mailboxes; },
|
||||||
|
async mailboxOpen(path, options) {
|
||||||
|
assert.deepEqual(options, { readOnly: true });
|
||||||
|
return mailboxByPath[path];
|
||||||
|
},
|
||||||
|
async fetchAll(range, query, options) {
|
||||||
|
calls.fetches.push({ range, query, options });
|
||||||
|
const result = fetchResults[range] || [];
|
||||||
|
return result.map(item => ({ ...item, flags: item.flags || new Set() }));
|
||||||
|
},
|
||||||
|
async getMailboxLock(path) {
|
||||||
|
calls.flags.push(['lock', path]);
|
||||||
|
return { release() { calls.locksReleased += 1; } };
|
||||||
|
},
|
||||||
|
async messageFlagsAdd(...args) { calls.flags.push(['add', ...args]); },
|
||||||
|
async messageMove(...args) { calls.moves.push(args); },
|
||||||
|
async logout() { calls.logout += 1; }
|
||||||
|
};
|
||||||
|
const service = createMailboxSyncService({
|
||||||
|
imapClient() { return client; },
|
||||||
|
async flushMailOutbox() { calls.outbox += 1; },
|
||||||
|
async updateAccountStore(update) { calls.labels += 1; return update(savedStore); },
|
||||||
|
async saveAccountSyncState(_id, generation, folders) {
|
||||||
|
calls.saved = folders;
|
||||||
|
return generations.get('account-1') === generation;
|
||||||
|
},
|
||||||
|
backgroundSyncGenerations: generations,
|
||||||
|
flagSnapshots: snapshots,
|
||||||
|
async findSpecialMailbox() { return 'Archive'; },
|
||||||
|
async folderPath(_client, folder) { return folder; },
|
||||||
|
logError(...args) { calls.errors.push(args); }
|
||||||
|
});
|
||||||
|
return { service, calls, generations, snapshots, savedStore };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('maps server special-use and fallback names to user-facing folders', () => {
|
||||||
|
assert.equal(backgroundFolderLabel({ path: 'INBOX' }), 'Inbox');
|
||||||
|
assert.equal(backgroundFolderLabel({ path: 'Provider/Sent Items' }), 'Sent');
|
||||||
|
assert.equal(backgroundFolderLabel({ path: 'Archive', specialUse: '\\Archive' }), 'Archive');
|
||||||
|
assert.equal(backgroundFolderLabel({ path: 'Projects/2026' }), 'Projects/2026');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('initializes a new mailbox cursor without reporting historical messages as new', async () => {
|
||||||
|
const { service, calls, snapshots } = setup({
|
||||||
|
mailboxes: [{ path: 'INBOX' }],
|
||||||
|
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 22, highestModseq: null } },
|
||||||
|
fetchResults: { '1:*': [{ uid: 1, flags: new Set(['\\Seen']) }, { uid: 21, flags: new Set() }] }
|
||||||
|
});
|
||||||
|
const result = await service.syncAccountMailboxes({ id: 'account-1', syncState: { folders: {} } });
|
||||||
|
|
||||||
|
assert.deepEqual(result, { newCount: 0, changedFolders: [] });
|
||||||
|
assert.deepEqual(calls.saved.INBOX, { uidValidity: '9', lastUid: 21, highestModseq: null });
|
||||||
|
assert.equal(snapshots.get('account-1').get('INBOX').flags.size, 2);
|
||||||
|
assert.equal(calls.outbox, 1);
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('detects new inbox messages, applies matching rules, persists labels, and closes the client', async () => {
|
||||||
|
const oldFlags = new Map([[1, '\\Seen']]);
|
||||||
|
const { service, calls, snapshots, savedStore } = setup({
|
||||||
|
mailboxes: [{ path: 'INBOX' }],
|
||||||
|
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 5, highestModseq: null } },
|
||||||
|
fetchResults: {
|
||||||
|
'3:4': [
|
||||||
|
{ uid: 3, envelope: { from: [{ address: 'flag@example.com' }], subject: 'Mark' } },
|
||||||
|
{ uid: 4, envelope: { from: [{ address: 'label@example.com' }], subject: 'Keep' } }
|
||||||
|
],
|
||||||
|
'1:*': [{ uid: 1, flags: new Set() }, { uid: 3, flags: new Set() }, { uid: 4, flags: new Set() }]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
snapshots.set('account-1', new Map([['INBOX', { uidValidity: '9', flags: oldFlags }]]));
|
||||||
|
const account = {
|
||||||
|
id: 'account-1',
|
||||||
|
syncState: { folders: { INBOX: { uidValidity: '9', lastUid: 2, highestModseq: null } } },
|
||||||
|
rules: [
|
||||||
|
{ id: 'flag-rule', senderContains: 'flag@', subjectContains: '', action: 'flag' },
|
||||||
|
{ id: 'label-rule', senderContains: 'label@', subjectContains: '', action: 'label', value: 'Keep' }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await service.syncAccountMailboxes(account);
|
||||||
|
assert.deepEqual(result, { newCount: 2, changedFolders: ['Inbox'] });
|
||||||
|
assert.deepEqual(calls.flags[1], ['add', 3, ['\\Flagged'], { uid: true }]);
|
||||||
|
assert.equal(calls.locksReleased, 2);
|
||||||
|
assert.equal(savedStore.accounts[0].ruleLabels['INBOX:4'][0], 'Keep');
|
||||||
|
assert.equal(calls.labels, 1);
|
||||||
|
assert.equal(calls.saved.INBOX.lastUid, 4);
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not publish a stale sync result after its account generation changes', async () => {
|
||||||
|
const { service, calls, generations } = setup({
|
||||||
|
mailboxes: [{ path: 'INBOX' }],
|
||||||
|
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 1, highestModseq: 1n } }
|
||||||
|
});
|
||||||
|
const pending = service.syncAccountMailboxes({ id: 'account-1', syncState: { folders: {} } });
|
||||||
|
generations.set('account-1', 2);
|
||||||
|
const result = await pending;
|
||||||
|
assert.deepEqual(result, { newCount: 0, changedFolders: [] });
|
||||||
|
assert.equal(calls.logout, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createOAuthTokenManager } = require('../desktop/mail/oauth-token-manager.cjs');
|
||||||
|
const { createMailConnections } = require('../desktop/mail/connection-factory.cjs');
|
||||||
|
|
||||||
|
test('uses a fresh OAuth access token without refreshing it', async () => {
|
||||||
|
let refreshes = 0;
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: { async refresh() { refreshes += 1; } },
|
||||||
|
async persistTokens() {},
|
||||||
|
now: () => 1_000
|
||||||
|
});
|
||||||
|
const account = {
|
||||||
|
id: 'account-1', authMethod: 'oauth2', oauthProvider: 'google',
|
||||||
|
oauthAccessToken: 'fresh-token', oauthRefreshToken: 'refresh-token', oauthAccessTokenExpiresAt: 120_000
|
||||||
|
};
|
||||||
|
assert.equal(await manager.getAccessToken(account), 'fresh-token');
|
||||||
|
assert.equal(refreshes, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refreshes expired OAuth tokens once and persists the encrypted-store fields', async () => {
|
||||||
|
let refreshes = 0;
|
||||||
|
const persisted = [];
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: {
|
||||||
|
async refresh(provider, refreshToken) {
|
||||||
|
refreshes += 1;
|
||||||
|
assert.equal(provider, 'microsoft');
|
||||||
|
assert.equal(refreshToken, 'old-refresh');
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
return { oauthAccessToken: 'fresh-token', oauthRefreshToken: 'new-refresh', oauthAccessTokenExpiresAt: 200_000 };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async persistTokens(id, tokens) { persisted.push({ id, tokens }); },
|
||||||
|
now: () => 1_000
|
||||||
|
});
|
||||||
|
const first = { id: 'account-2', authMethod: 'oauth2', oauthProvider: 'microsoft', oauthRefreshToken: 'old-refresh', oauthAccessTokenExpiresAt: 0 };
|
||||||
|
const second = { ...first };
|
||||||
|
|
||||||
|
assert.deepEqual(await Promise.all([manager.getAccessToken(first), manager.getAccessToken(second)]), ['fresh-token', 'fresh-token']);
|
||||||
|
assert.equal(refreshes, 1);
|
||||||
|
assert.equal(persisted.length, 1);
|
||||||
|
assert.equal(persisted[0].id, 'account-2');
|
||||||
|
assert.equal(first.oauthRefreshToken, 'new-refresh');
|
||||||
|
assert.equal(second.oauthAccessToken, 'fresh-token');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects expired OAuth accounts without a refresh token', async () => {
|
||||||
|
const manager = createOAuthTokenManager({
|
||||||
|
oauth2Service: { async refresh() { assert.fail('must not refresh without a token'); } },
|
||||||
|
async persistTokens() {},
|
||||||
|
now: () => 100_000
|
||||||
|
});
|
||||||
|
await assert.rejects(manager.getAccessToken({ authMethod: 'oauth2', oauthProvider: 'google' }), /Reconnect this OAuth2 account/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mail connection factory uses OAuth bearer tokens and TLS provider defaults', async () => {
|
||||||
|
const imapOptions = [];
|
||||||
|
const smtpOptions = [];
|
||||||
|
const manager = { async getAccessToken(account) { return `token:${account.email}`; } };
|
||||||
|
const connections = createMailConnections({
|
||||||
|
ImapFlow: class { constructor(options) { imapOptions.push(options); } },
|
||||||
|
createTransport(options) { smtpOptions.push(options); return { options }; },
|
||||||
|
oauthTokenManager: manager
|
||||||
|
});
|
||||||
|
const oauthAccount = {
|
||||||
|
authMethod: 'oauth2', oauthProvider: 'google', email: 'user@gmail.com',
|
||||||
|
imapHost: 'imap.gmail.com', imapPort: 993, imapSecure: true,
|
||||||
|
smtpHost: 'smtp.gmail.com', smtpPort: 587, smtpSecure: false,
|
||||||
|
oauthAccessTokenExpiresAt: 123456
|
||||||
|
};
|
||||||
|
|
||||||
|
await connections.imapClient(oauthAccount, { autoIdleDelay: 10 });
|
||||||
|
await connections.smtpTransport(oauthAccount);
|
||||||
|
assert.deepEqual(imapOptions[0].auth, { user: 'user@gmail.com', accessToken: 'token:user@gmail.com' });
|
||||||
|
assert.equal(imapOptions[0].secure, true);
|
||||||
|
assert.equal(imapOptions[0].doSTARTTLS, false);
|
||||||
|
assert.equal(imapOptions[0].autoIdleDelay, 10);
|
||||||
|
assert.deepEqual(smtpOptions[0].auth, {
|
||||||
|
type: 'OAuth2', user: 'user@gmail.com', accessToken: 'token:user@gmail.com', expires: 123456
|
||||||
|
});
|
||||||
|
assert.equal(smtpOptions[0].requireTLS, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mail connection factory retains password and STARTTLS behavior for existing accounts', async () => {
|
||||||
|
let imapOptions;
|
||||||
|
let smtpOptions;
|
||||||
|
const connections = createMailConnections({
|
||||||
|
ImapFlow: class { constructor(options) { imapOptions = options; } },
|
||||||
|
createTransport(options) { smtpOptions = options; return {}; },
|
||||||
|
oauthTokenManager: { async getAccessToken() { assert.fail('password accounts must not request OAuth tokens'); } }
|
||||||
|
});
|
||||||
|
const account = {
|
||||||
|
email: 'user@example.test', password: 'mail-password', imapHost: 'imap.example.test', imapPort: 143,
|
||||||
|
smtpHost: 'smtp.example.test', smtpPort: 587
|
||||||
|
};
|
||||||
|
await connections.imapClient(account);
|
||||||
|
await connections.smtpTransport(account);
|
||||||
|
assert.deepEqual(imapOptions.auth, { user: account.email, pass: account.password });
|
||||||
|
assert.equal(imapOptions.secure, false);
|
||||||
|
assert.equal(imapOptions.doSTARTTLS, true);
|
||||||
|
assert.deepEqual(smtpOptions.auth, { user: account.email, pass: account.password });
|
||||||
|
assert.equal(smtpOptions.requireTLS, true);
|
||||||
|
});
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createOAuth2Service, loadOAuthProviderConfig } = require('../desktop/mail/oauth2-service.cjs');
|
||||||
|
|
||||||
|
test('loads only externally configured OAuth client identifiers', () => {
|
||||||
|
assert.deepEqual(loadOAuthProviderConfig({}), {});
|
||||||
|
const providers = loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client.apps.example',
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET: 'google-desktop-secret',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'organizations'
|
||||||
|
});
|
||||||
|
assert.equal(providers.google.clientId, 'google-client.apps.example');
|
||||||
|
assert.equal(providers.microsoft.tenant, 'organizations');
|
||||||
|
assert.throws(() => loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'https://attacker.example'
|
||||||
|
}), /tenant ID is invalid/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('authorizes Google and Microsoft with PKCE, state validation, and loopback redirects', async () => {
|
||||||
|
const providers = loadOAuthProviderConfig({
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client',
|
||||||
|
EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET: 'google-secret',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client',
|
||||||
|
EP_MAIL_MICROSOFT_OAUTH_TENANT_ID: 'common'
|
||||||
|
});
|
||||||
|
const authorizationUrls = [];
|
||||||
|
const tokenRequests = [];
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers,
|
||||||
|
async openExternal(value) {
|
||||||
|
const authorization = new URL(value);
|
||||||
|
authorizationUrls.push(authorization);
|
||||||
|
const callback = new URL(authorization.searchParams.get('redirect_uri'));
|
||||||
|
callback.searchParams.set('code', 'authorization-code');
|
||||||
|
callback.searchParams.set('state', authorization.searchParams.get('state'));
|
||||||
|
const result = await fetch(callback);
|
||||||
|
assert.equal(result.status, 200);
|
||||||
|
},
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
tokenRequests.push({ url, body: new URLSearchParams(options.body) });
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
async json() {
|
||||||
|
return { access_token: 'access-token', refresh_token: 'refresh-token', expires_in: 3600 };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const provider of ['google', 'microsoft']) {
|
||||||
|
const tokens = await service.authorize(provider, 'user@example.test');
|
||||||
|
assert.deepEqual(Object.keys(tokens).sort(), [
|
||||||
|
'oauthAccessToken', 'oauthAccessTokenExpiresAt', 'oauthRefreshToken'
|
||||||
|
]);
|
||||||
|
assert.equal(tokens.oauthAccessToken, 'access-token');
|
||||||
|
assert.equal(tokens.oauthRefreshToken, 'refresh-token');
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(authorizationUrls.length, 2);
|
||||||
|
for (const authorization of authorizationUrls) {
|
||||||
|
assert.match(authorization.searchParams.get('code_challenge'), /^[A-Za-z0-9_-]{43}$/);
|
||||||
|
assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256');
|
||||||
|
assert.equal(authorization.searchParams.get('login_hint'), 'user@example.test');
|
||||||
|
assert.ok(authorization.searchParams.get('state').length >= 40);
|
||||||
|
assert.match(authorization.searchParams.get('redirect_uri'), /^http:\/\/(?:127\.0\.0\.1|localhost):\d+$/);
|
||||||
|
}
|
||||||
|
assert.equal(authorizationUrls[0].searchParams.get('scope'), 'https://mail.google.com/');
|
||||||
|
assert.match(authorizationUrls[1].searchParams.get('scope'), /IMAP\.AccessAsUser\.All/);
|
||||||
|
assert.match(authorizationUrls[1].searchParams.get('scope'), /SMTP\.Send/);
|
||||||
|
assert.equal(tokenRequests.length, 2);
|
||||||
|
assert.equal(tokenRequests[0].body.get('code_verifier').length, 64);
|
||||||
|
assert.equal(tokenRequests[0].body.get('client_secret'), 'google-secret');
|
||||||
|
assert.equal(tokenRequests[1].body.has('client_secret'), false);
|
||||||
|
assert.equal(tokenRequests[0].body.get('code'), 'authorization-code');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refreshes OAuth tokens and preserves the current refresh token if omitted by provider', async () => {
|
||||||
|
let posted;
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers: loadOAuthProviderConfig({ EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID: 'microsoft-client' }),
|
||||||
|
async openExternal() {},
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
posted = { url, body: new URLSearchParams(options.body) };
|
||||||
|
return { ok: true, async json() { return { access_token: 'new-access-token', expires_in: 1800 }; } };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const tokens = await service.refresh('microsoft', 'stored-refresh-token');
|
||||||
|
assert.equal(posted.body.get('grant_type'), 'refresh_token');
|
||||||
|
assert.equal(posted.body.get('refresh_token'), 'stored-refresh-token');
|
||||||
|
assert.equal(tokens.oauthAccessToken, 'new-access-token');
|
||||||
|
assert.equal(tokens.oauthRefreshToken, 'stored-refresh-token');
|
||||||
|
assert.ok(tokens.oauthAccessTokenExpiresAt > Date.now());
|
||||||
|
await assert.rejects(service.refresh('microsoft', ''), /Reconnect this Microsoft account/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects a loopback callback with an invalid OAuth state before exchanging its code', async () => {
|
||||||
|
let tokenRequests = 0;
|
||||||
|
const service = createOAuth2Service({
|
||||||
|
providers: loadOAuthProviderConfig({ EP_MAIL_GOOGLE_OAUTH_CLIENT_ID: 'google-client' }),
|
||||||
|
async openExternal(value) {
|
||||||
|
const authorization = new URL(value);
|
||||||
|
const callback = new URL(authorization.searchParams.get('redirect_uri'));
|
||||||
|
callback.searchParams.set('code', 'attacker-code');
|
||||||
|
callback.searchParams.set('state', 'wrong-state');
|
||||||
|
const response = await fetch(callback);
|
||||||
|
assert.equal(response.status, 400);
|
||||||
|
},
|
||||||
|
async fetchImpl() {
|
||||||
|
tokenRequests += 1;
|
||||||
|
throw new Error('must not exchange an untrusted code');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await assert.rejects(service.authorize('google', 'user@gmail.com'), /state validation failed/);
|
||||||
|
assert.equal(tokenRequests, 0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { registerPgpIpcHandlers } = require('../desktop/ipc/pgp.cjs');
|
||||||
|
|
||||||
|
function registerWith(overrides = {}) {
|
||||||
|
const handlers = new Map();
|
||||||
|
registerPgpIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { handlers.set(channel, handler); },
|
||||||
|
BrowserWindow: { fromWebContents: () => ({}) },
|
||||||
|
dialog: {
|
||||||
|
async showOpenDialog() { return { canceled: true, filePaths: [] }; },
|
||||||
|
async showSaveDialog() { return { canceled: true, filePath: '' }; },
|
||||||
|
async showMessageBox() { return { response: 0 }; }
|
||||||
|
},
|
||||||
|
fs: {}, openpgp: {}, pgpKeys: {}, pgpCache: {}, pgpMail: {},
|
||||||
|
PgpError: class PgpError extends Error {},
|
||||||
|
pgpKeyServers: {}, listServers() { return []; }, MAX_CUSTOM_SERVERS: 10,
|
||||||
|
normalizeCustomServer() {}, randomUUID() { return 'test-id'; },
|
||||||
|
readAccount() { return null; }, imapClient() {}, folderPath() {}, simpleParser() {}, extractMailContent() {},
|
||||||
|
...overrides
|
||||||
|
});
|
||||||
|
return handlers;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('registers the complete OpenPGP IPC surface through the shared boundary', () => {
|
||||||
|
const registered = [];
|
||||||
|
registerPgpIpcHandlers({
|
||||||
|
registerIpcHandler(channel, handler) { registered.push({ channel, handler }); },
|
||||||
|
BrowserWindow: {},
|
||||||
|
dialog: {},
|
||||||
|
fs: {},
|
||||||
|
openpgp: {},
|
||||||
|
pgpKeys: {},
|
||||||
|
pgpCache: {},
|
||||||
|
pgpMail: {},
|
||||||
|
PgpError: class PgpError extends Error {},
|
||||||
|
pgpKeyServers: {},
|
||||||
|
listServers() {},
|
||||||
|
MAX_CUSTOM_SERVERS: 10,
|
||||||
|
normalizeCustomServer() {},
|
||||||
|
randomUUID() {},
|
||||||
|
readAccount() {},
|
||||||
|
imapClient() {},
|
||||||
|
folderPath() {},
|
||||||
|
simpleParser() {},
|
||||||
|
extractMailContent() {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const channels = registered.map(item => item.channel).sort();
|
||||||
|
assert.deepEqual(channels, [
|
||||||
|
'pgp:add-contact', 'pgp:add-key-server', 'pgp:change-passphrase', 'pgp:check-send',
|
||||||
|
'pgp:contacts', 'pgp:decrypt-message', 'pgp:delete', 'pgp:export-contact',
|
||||||
|
'pgp:export-private', 'pgp:export-public', 'pgp:export-revocation', 'pgp:find-key',
|
||||||
|
'pgp:forget-passphrases', 'pgp:generate', 'pgp:get-settings', 'pgp:import',
|
||||||
|
'pgp:key-servers', 'pgp:list', 'pgp:publish-key', 'pgp:remove-contact',
|
||||||
|
'pgp:remove-key-server', 'pgp:set-key-server-enabled', 'pgp:set-settings', 'pgp:set-trust'
|
||||||
|
]);
|
||||||
|
assert.ok(registered.every(item => typeof item.handler === 'function'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native cancellation blocks replacing an existing contact key', async () => {
|
||||||
|
const dialogs = [];
|
||||||
|
let added = false;
|
||||||
|
const handlers = registerWith({
|
||||||
|
dialog: {
|
||||||
|
async showMessageBox(_window, options) { dialogs.push(options); return { response: 0 }; }
|
||||||
|
},
|
||||||
|
openpgp: {
|
||||||
|
async readKey() {
|
||||||
|
return { getFingerprint: () => 'A'.repeat(40), getUserIDs: () => ['Alice <alice@example.test>'] };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
pgpKeys: {
|
||||||
|
async listContacts() { return [{ name: 'Alice', emails: ['alice@example.test'], fingerprint: 'B'.repeat(40) }]; },
|
||||||
|
async addContact() { added = true; }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await assert.rejects(
|
||||||
|
handlers.get('pgp:add-contact')({ sender: {} }, { armoredKey: 'new-public-key', source: 'message' }),
|
||||||
|
/Key replacement cancelled/
|
||||||
|
);
|
||||||
|
assert.equal(added, false);
|
||||||
|
assert.equal(dialogs.length, 1);
|
||||||
|
assert.deepEqual(dialogs[0].buttons, ['Cancel', 'Replace key']);
|
||||||
|
assert.match(dialogs[0].detail, /A{4} A{4}/);
|
||||||
|
assert.match(dialogs[0].detail, /B{4} B{4}/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native confirmation is required before raising contact-key trust', async () => {
|
||||||
|
let response = 0;
|
||||||
|
let trustChanges = 0;
|
||||||
|
const fingerprint = 'C'.repeat(40);
|
||||||
|
const handlers = registerWith({
|
||||||
|
dialog: { async showMessageBox() { return { response }; } },
|
||||||
|
pgpKeys: {
|
||||||
|
async listContacts() { return [{ name: 'Carol', emails: ['carol@example.test'], fingerprint }]; },
|
||||||
|
async setTrust(id, level) { trustChanges += 1; return { fingerprint: id, trust: level }; }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await assert.rejects(handlers.get('pgp:set-trust')({ sender: {} }, fingerprint, 'verified'), /Trust change cancelled/);
|
||||||
|
assert.equal(trustChanges, 0);
|
||||||
|
response = 1;
|
||||||
|
assert.deepEqual(await handlers.get('pgp:set-trust')({ sender: {} }, fingerprint, 'verified'), { fingerprint, trust: 'verified' });
|
||||||
|
assert.equal(trustChanges, 1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const openpgp = require('openpgp');
|
||||||
|
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
|
||||||
|
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||||
|
|
||||||
|
const email = 'ada@example.org';
|
||||||
|
|
||||||
|
function memoryStore() {
|
||||||
|
let data = null;
|
||||||
|
return {
|
||||||
|
async load() { return data && JSON.parse(JSON.stringify(data)); },
|
||||||
|
async save(value) { data = JSON.parse(JSON.stringify(value)); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function makeKey() {
|
||||||
|
const generated = await openpgp.generateKey({
|
||||||
|
type: 'ecc',
|
||||||
|
curve: 'curve25519Legacy',
|
||||||
|
userIDs: [{ name: 'Ada Lovelace', email }],
|
||||||
|
passphrase: 'correct horse battery',
|
||||||
|
format: 'armored'
|
||||||
|
});
|
||||||
|
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
|
||||||
|
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('validates custom HTTPS key server configuration', () => {
|
||||||
|
assert.deepEqual(normalizeCustomServer({
|
||||||
|
id: 'custom',
|
||||||
|
name: 'Internal server',
|
||||||
|
url: 'https://keys.example.org/openpgp',
|
||||||
|
protocol: 'hkp'
|
||||||
|
}), {
|
||||||
|
id: 'custom',
|
||||||
|
name: 'Internal server',
|
||||||
|
url: 'https://keys.example.org/openpgp/',
|
||||||
|
protocol: 'hkp',
|
||||||
|
builtin: false
|
||||||
|
});
|
||||||
|
assert.throws(() => normalizeCustomServer({ name: 'Plain HTTP', url: 'http://keys.example.org', protocol: 'hkp' }), /HTTPS/);
|
||||||
|
assert.throws(() => normalizeCustomServer({ name: 'Credential URL', url: 'https://user:pass@keys.example.org', protocol: 'vks' }), /credentials/);
|
||||||
|
assert.throws(() => normalizeCustomServer({ name: 'Query URL', url: 'https://keys.example.org/?token=x', protocol: 'vks' }), /query/);
|
||||||
|
assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('all built-in and custom key servers start disabled', () => {
|
||||||
|
const servers = listServers([{
|
||||||
|
id: 'custom',
|
||||||
|
name: 'Internal server',
|
||||||
|
url: 'https://keys.example.org',
|
||||||
|
protocol: 'hkp'
|
||||||
|
}]);
|
||||||
|
assert.equal(servers.length, 3);
|
||||||
|
assert.ok(servers.every(server => server.enabled === false));
|
||||||
|
const enabled = listServers([], ['openpgp-vks']);
|
||||||
|
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
||||||
|
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('VKS lookup returns only valid keys matching the requested address', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
let requestedUrl;
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
requestedUrl = new URL(url);
|
||||||
|
assert.equal(options.redirect, 'error');
|
||||||
|
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const found = await service.lookup({
|
||||||
|
id: 'openpgp-vks',
|
||||||
|
name: 'keys.openpgp.org',
|
||||||
|
url: 'https://keys.openpgp.org',
|
||||||
|
protocol: 'vks'
|
||||||
|
}, email);
|
||||||
|
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
|
||||||
|
assert.equal(found.length, 1);
|
||||||
|
assert.equal(found[0].fingerprint, key.fingerprint);
|
||||||
|
assert.deepEqual(found[0].emails, [email]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
let requestedUrl;
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl(url) {
|
||||||
|
requestedUrl = new URL(url);
|
||||||
|
return new Response(`not a key\n${key.armoredKey}`, { status: 200 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const server = { id: 'custom', name: 'Example', url: 'https://keys.example.org/base/', protocol: 'hkp' };
|
||||||
|
const found = await service.lookup(server, email);
|
||||||
|
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
|
||||||
|
assert.equal(requestedUrl.searchParams.get('op'), 'get');
|
||||||
|
assert.equal(requestedUrl.searchParams.get('search'), email);
|
||||||
|
assert.equal(found.length, 1);
|
||||||
|
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
const requested = [];
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl(url) {
|
||||||
|
const target = new URL(url);
|
||||||
|
requested.push(target.hostname);
|
||||||
|
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
|
||||||
|
return new Response(key.armoredKey, { status: 200 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const results = await service.lookupEnabled([
|
||||||
|
{ id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true },
|
||||||
|
{ id: 'two', name: 'Second', url: 'https://second.example.org', protocol: 'vks', enabled: true },
|
||||||
|
{ id: 'bad', name: 'Offline', url: 'https://broken.example.org', protocol: 'hkp', enabled: true },
|
||||||
|
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||||
|
], email);
|
||||||
|
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
|
||||||
|
assert.equal(results.keys.length, 1);
|
||||||
|
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
|
||||||
|
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
|
||||||
|
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
|
||||||
|
await assert.rejects(() => service.lookupEnabled([
|
||||||
|
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||||
|
], email), /Enable at least one key server/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('VKS publication uploads only the public key and requests email verification', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
const calls = [];
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
calls.push({ url: new URL(url), options });
|
||||||
|
if (calls.length === 1) {
|
||||||
|
return Response.json({
|
||||||
|
key_fpr: key.fingerprint,
|
||||||
|
token: 'temporary-upload-token',
|
||||||
|
status: { [email]: 'unpublished' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const result = await service.publish({
|
||||||
|
id: 'openpgp-vks',
|
||||||
|
name: 'keys.openpgp.org',
|
||||||
|
url: 'https://keys.openpgp.org',
|
||||||
|
protocol: 'vks'
|
||||||
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
|
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
|
||||||
|
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
|
||||||
|
assert.equal(result.verification, 'pending');
|
||||||
|
const upload = JSON.parse(calls[0].options.body);
|
||||||
|
assert.equal(upload.keytext, key.armoredKey);
|
||||||
|
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
|
||||||
|
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HKP publication posts armored public material only', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
let requestInfo;
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl(url, options) {
|
||||||
|
requestInfo = { url: new URL(url), options };
|
||||||
|
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const result = await service.publish({
|
||||||
|
id: 'mailvelope-hkp',
|
||||||
|
name: 'keys.mailvelope.com',
|
||||||
|
url: 'https://keys.mailvelope.com',
|
||||||
|
protocol: 'hkp'
|
||||||
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
|
assert.equal(requestInfo.url.pathname, '/pks/add');
|
||||||
|
assert.equal(requestInfo.options.headers['content-type'], 'application/x-www-form-urlencoded');
|
||||||
|
assert.equal(new URLSearchParams(requestInfo.options.body).get('keytext'), key.armoredKey);
|
||||||
|
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
|
||||||
|
assert.equal(result.verification, 'check-email');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
const keyStore = createKeyStore(memoryStore());
|
||||||
|
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
|
assert.equal(added.contact.trust, 'unknown');
|
||||||
|
assert.equal(added.contact.source, 'keyserver');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lookup rejects oversized responses and HTTP failures', async () => {
|
||||||
|
const server = { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks' };
|
||||||
|
const tooLarge = createKeyServerService({
|
||||||
|
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
|
||||||
|
});
|
||||||
|
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
|
||||||
|
const failure = createKeyServerService({
|
||||||
|
async fetchImpl() { return new Response('', { status: 503 }); }
|
||||||
|
});
|
||||||
|
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
|
||||||
|
const invalid = createKeyServerService({
|
||||||
|
async fetchImpl() { return new Response('<html>unexpected response</html>', { status: 200 }); }
|
||||||
|
});
|
||||||
|
await assert.rejects(() => invalid.lookup(server, email), /did not contain an OpenPGP public key/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('VKS verification failure reports that the key upload already succeeded', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
let calls = 0;
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl() {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) {
|
||||||
|
return Response.json({
|
||||||
|
key_fpr: key.fingerprint,
|
||||||
|
token: 'temporary-upload-token',
|
||||||
|
status: { [email]: 'unpublished' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw new Error('network unavailable');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const result = await service.publish({
|
||||||
|
id: 'openpgp-vks',
|
||||||
|
name: 'keys.openpgp.org',
|
||||||
|
url: 'https://keys.openpgp.org',
|
||||||
|
protocol: 'vks'
|
||||||
|
}, email, key.armoredKey, key.fingerprint);
|
||||||
|
assert.equal(result.uploaded, true);
|
||||||
|
assert.equal(result.verification, 'request-failed');
|
||||||
|
assert.match(result.warning, /key was uploaded/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('publication rejects a fingerprint that does not match the public key', async () => {
|
||||||
|
const key = await makeKey();
|
||||||
|
const service = createKeyServerService({
|
||||||
|
async fetchImpl() { throw new Error('unexpected network request'); }
|
||||||
|
});
|
||||||
|
await assert.rejects(() => service.publish({
|
||||||
|
id: 'mailvelope-hkp',
|
||||||
|
name: 'keys.mailvelope.com',
|
||||||
|
url: 'https://keys.mailvelope.com',
|
||||||
|
protocol: 'hkp'
|
||||||
|
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
|
||||||
|
});
|
||||||
@@ -43,6 +43,52 @@ test('export requires the right passphrase and round-trips through import', asyn
|
|||||||
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
|
||||||
|
const storage = memoryStore();
|
||||||
|
const keys = createKeyStore(storage);
|
||||||
|
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||||
|
const original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
|
||||||
|
const newPassphrase = 'new passphrase securely';
|
||||||
|
|
||||||
|
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
|
||||||
|
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
|
||||||
|
assert.deepEqual((await storage.load()).keys[0], original);
|
||||||
|
|
||||||
|
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
|
||||||
|
const changed = (await storage.load()).keys[0];
|
||||||
|
assert.equal(changed.fingerprint, original.fingerprint);
|
||||||
|
assert.equal(changed.publicKey, original.publicKey);
|
||||||
|
assert.equal(changed.name, original.name);
|
||||||
|
assert.equal(changed.email, original.email);
|
||||||
|
assert.equal(changed.accountId, original.accountId);
|
||||||
|
assert.equal(changed.createdAt, original.createdAt);
|
||||||
|
assert.equal(changed.algorithm, original.algorithm);
|
||||||
|
assert.equal(changed.revocationCertificate, original.revocationCertificate);
|
||||||
|
assert.notEqual(changed.privateKey, original.privateKey);
|
||||||
|
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
|
||||||
|
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
|
||||||
|
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
|
||||||
|
let data = null;
|
||||||
|
let failSave = false;
|
||||||
|
const storage = {
|
||||||
|
load: async () => data,
|
||||||
|
save: async value => {
|
||||||
|
if (failSave) throw new Error('Storage unavailable.');
|
||||||
|
data = JSON.parse(JSON.stringify(value));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const keys = createKeyStore(storage);
|
||||||
|
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||||
|
const original = JSON.parse(JSON.stringify(data.keys[0]));
|
||||||
|
failSave = true;
|
||||||
|
|
||||||
|
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
|
||||||
|
assert.deepEqual(data.keys[0], original);
|
||||||
|
});
|
||||||
|
|
||||||
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
|
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
|
||||||
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
|
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
|
||||||
const keys = createKeyStore(memoryStore());
|
const keys = createKeyStore(memoryStore());
|
||||||
|
|||||||
+38
-3
@@ -75,6 +75,29 @@ test('encrypts to several recipients and each can decrypt', async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('encrypts and signs outgoing attachments with the message body', async () => {
|
||||||
|
const alice = await actor('Alice', 'alice@example.com');
|
||||||
|
const bob = await actor('Bob', 'bob@example.com');
|
||||||
|
await exchange(alice, bob);
|
||||||
|
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
|
||||||
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
||||||
|
encrypt: true,
|
||||||
|
sign: true,
|
||||||
|
passphrase: alice.passphrase,
|
||||||
|
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
|
||||||
|
}));
|
||||||
|
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
|
||||||
|
|
||||||
|
const parsed = await simpleParser(raw);
|
||||||
|
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||||
|
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
|
||||||
|
assert.equal(decrypted.parsed.attachments.length, 1);
|
||||||
|
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
|
||||||
|
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
|
||||||
|
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
|
||||||
|
assert.equal(decrypted.signatures[0].status, 'valid');
|
||||||
|
});
|
||||||
|
|
||||||
test('detects tampered and corrupted encrypted messages', async () => {
|
test('detects tampered and corrupted encrypted messages', async () => {
|
||||||
const alice = await actor('Alice', 'alice@example.com');
|
const alice = await actor('Alice', 'alice@example.com');
|
||||||
const bob = await actor('Bob', 'bob@example.com');
|
const bob = await actor('Bob', 'bob@example.com');
|
||||||
@@ -112,10 +135,16 @@ test('signs without encrypting and verifies PGP/MIME signatures', async () => {
|
|||||||
const alice = await actor('Alice', 'alice@example.com');
|
const alice = await actor('Alice', 'alice@example.com');
|
||||||
const bob = await actor('Bob', 'bob@example.com');
|
const bob = await actor('Bob', 'bob@example.com');
|
||||||
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
|
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
|
||||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase }));
|
const attachment = Buffer.from('signed attachment data');
|
||||||
|
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
|
||||||
|
sign: true,
|
||||||
|
passphrase: alice.passphrase,
|
||||||
|
attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }]
|
||||||
|
}));
|
||||||
const parsed = await simpleParser(raw);
|
const parsed = await simpleParser(raw);
|
||||||
assert.equal(detect(parsed), 'signed-mime');
|
assert.equal(detect(parsed), 'signed-mime');
|
||||||
assert.match(parsed.text, /Top secret/);
|
assert.match(parsed.text, /Top secret/);
|
||||||
|
assert.deepEqual(parsed.attachments[0].content, attachment);
|
||||||
const [signature] = await bob.mail.verifySigned(parsed, raw);
|
const [signature] = await bob.mail.verifySigned(parsed, raw);
|
||||||
assert.equal(signature.status, 'valid');
|
assert.equal(signature.status, 'valid');
|
||||||
const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1');
|
const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1');
|
||||||
@@ -166,9 +195,15 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a
|
|||||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
||||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
||||||
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
||||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10 });
|
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] });
|
||||||
await alice.keyStore.setSettings({ cacheMinutes: 0 });
|
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
||||||
|
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
|
||||||
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
||||||
|
await alice.keyStore.setSettings({ cacheMinutes: 5 });
|
||||||
|
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
|
||||||
|
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
|
||||||
|
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
|
||||||
|
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, []);
|
||||||
await alice.keyStore.removeContact(contact.fingerprint);
|
await alice.keyStore.removeContact(contact.fingerprint);
|
||||||
assert.equal((await alice.keyStore.listContacts()).length, 0);
|
assert.equal((await alice.keyStore.listContacts()).length, 0);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
|
||||||
|
|
||||||
|
test('renderer bootstrap loads shared state and mail security before the application', () => {
|
||||||
|
const html = read('index.html');
|
||||||
|
const state = html.indexOf('<script src="renderer-state.js"></script>');
|
||||||
|
const contentSecurity = html.indexOf('<script src="mail-content-security.js"></script>');
|
||||||
|
const mailApi = html.indexOf('<script src="renderer-mail-api.js"></script>');
|
||||||
|
const app = html.indexOf('<script src="app.js"></script>');
|
||||||
|
const platformBridge = html.indexOf('<script src="platform-bridge.js"></script>');
|
||||||
|
const mailUi = html.indexOf('<script src="mail-ui.js"></script>');
|
||||||
|
const productivity = html.indexOf('<script src="productivity.js"></script>');
|
||||||
|
const davUi = html.indexOf('<script src="dav-ui.js"></script>');
|
||||||
|
const accountUi = html.indexOf('<script src="account-ui.js"></script>');
|
||||||
|
assert.ok(state >= 0 && contentSecurity > state && app > contentSecurity && mailApi > platformBridge && mailUi > mailApi);
|
||||||
|
assert.ok(productivity > mailUi && davUi > productivity && accountUi > davUi);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('core app shell uses the namespaced renderer state', () => {
|
||||||
|
const app = read('app.js');
|
||||||
|
assert.match(app, /^\(\(\) => \{/);
|
||||||
|
assert.match(app, /window\.epMailShell = Object\.freeze/);
|
||||||
|
assert.match(app, /const state = window\.epMailState/);
|
||||||
|
assert.doesNotMatch(app, /^\s*(?:const|let|var)\s+(?:messages|contacts|activeMessage|activeFolder|activeView|query|toastTimer|selectedIds)\b/m);
|
||||||
|
assert.match(app, /window\.epMailFeatures\.contentSecurity/);
|
||||||
|
assert.doesNotMatch(app, /epMailMailContentSecurity/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mail content security API is registered in the shared feature namespace', () => {
|
||||||
|
const window = {};
|
||||||
|
vm.runInNewContext(read('mail-content-security.js'), { window });
|
||||||
|
assert.equal(typeof window.epMailFeatures.contentSecurity.safeRemoteImageUrl, 'function');
|
||||||
|
assert.equal(typeof window.epMailFeatures.contentSecurity.sanitizeMailHtml, 'function');
|
||||||
|
assert.equal(Object.hasOwn(window, 'epMailMailContentSecurity'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('desktop, Android web generation, and offline cache include renderer support modules', () => {
|
||||||
|
const buildFiles = require(path.join(root, 'package.json')).build.files;
|
||||||
|
const androidAssets = read('scripts/prepare-android-web.cjs');
|
||||||
|
const worker = read('service-worker.js');
|
||||||
|
for (const file of ['renderer-state.js', 'mail-content-security.js', 'renderer-mail-api.js']) {
|
||||||
|
assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`);
|
||||||
|
assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`);
|
||||||
|
assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('classic renderer scripts have no duplicate global lexical declarations', () => {
|
||||||
|
const html = read('index.html');
|
||||||
|
const scripts = [...html.matchAll(/<script src="([^"]+)"/g)].map(match => match[1]);
|
||||||
|
const source = scripts.map(script => read(script)).join('\n');
|
||||||
|
assert.doesNotThrow(() => new vm.Script(source, { filename: 'renderer-classic-scripts.js' }));
|
||||||
|
});
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const { createMailUiApi } = require('../renderer-mail-api.js');
|
||||||
|
|
||||||
|
test('mail feature API exposes explicit state and account/sync UI actions', () => {
|
||||||
|
const calls = [];
|
||||||
|
let connectedAccount = { id: 'first' };
|
||||||
|
const state = { activeFolder: 'Inbox' };
|
||||||
|
const methods = {
|
||||||
|
setPageOffset: value => calls.push(['offset', value]),
|
||||||
|
syncMailbox: (...args) => calls.push(['sync', ...args]),
|
||||||
|
updateAccountCard: value => calls.push(['card', value]),
|
||||||
|
getRenderList: () => () => calls.push(['render']),
|
||||||
|
getOpenMessage: () => () => calls.push(['open']),
|
||||||
|
getShowCompose: () => () => calls.push(['compose']),
|
||||||
|
baseRenderList: () => calls.push(['base-render']),
|
||||||
|
emptyReader: () => '<empty>',
|
||||||
|
openMailAccount: value => calls.push(['open-account', value]),
|
||||||
|
select: selector => selector,
|
||||||
|
selectAll: selector => [selector],
|
||||||
|
toast: value => calls.push(['toast', value]),
|
||||||
|
setRenderList: renderer => { calls.push(['set-render-list', renderer]); },
|
||||||
|
setOpenMessage: renderer => { calls.push(['set-open-message', renderer]); },
|
||||||
|
setShowCompose: renderer => { calls.push(['set-show-compose', renderer]); }
|
||||||
|
};
|
||||||
|
const api = createMailUiApi({
|
||||||
|
state,
|
||||||
|
getConnectedAccount: () => connectedAccount,
|
||||||
|
setConnectedAccount: value => { connectedAccount = value; },
|
||||||
|
...methods
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(api.state, state);
|
||||||
|
assert.equal(api.connectedAccount.id, 'first');
|
||||||
|
api.connectedAccount = { id: 'second' };
|
||||||
|
assert.equal(connectedAccount.id, 'second');
|
||||||
|
api.setPageOffset(0);
|
||||||
|
api.syncMailbox(false, { offset: 0 });
|
||||||
|
api.updateAccountCard(api.connectedAccount);
|
||||||
|
api.renderList();
|
||||||
|
api.openMessage(1);
|
||||||
|
api.showCompose();
|
||||||
|
api.baseRenderList();
|
||||||
|
assert.equal(api.emptyReader(), '<empty>');
|
||||||
|
assert.equal(api.select('selector'), 'selector');
|
||||||
|
assert.deepEqual(api.selectAll('selector'), ['selector']);
|
||||||
|
api.wrapRenderList(base => () => { calls.push(['wrapped-render']); return base(); });
|
||||||
|
api.wrapOpenMessage(base => () => { calls.push(['wrapped-open']); return base(); });
|
||||||
|
api.wrapShowCompose(base => () => { calls.push(['wrapped-compose']); return base(); });
|
||||||
|
api.openMailAccount();
|
||||||
|
assert.deepEqual(calls.map(call => call[0]), [
|
||||||
|
'offset', 'sync', 'card', 'render', 'open', 'compose', 'base-render', 'set-render-list', 'set-open-message', 'set-show-compose', 'open-account'
|
||||||
|
]);
|
||||||
|
assert.equal(Object.isFrozen(api), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('browser mail API factory is registered under the shared feature namespace', () => {
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const source = fs.readFileSync(path.join(root, 'renderer-mail-api.js'), 'utf8');
|
||||||
|
const window = {};
|
||||||
|
vm.runInNewContext(source, { window });
|
||||||
|
assert.equal(typeof window.epMailFeatures.modules.createMailUiApi, 'function');
|
||||||
|
assert.equal(Object.isFrozen(window.epMailFeatures.modules), true);
|
||||||
|
assert.equal(Object.hasOwn(window, 'epMailUiModules'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('account and snooze UI consume the explicit mail API instead of selected legacy globals', () => {
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const accountUi = fs.readFileSync(path.join(root, 'account-ui.js'), 'utf8');
|
||||||
|
const snoozeUi = fs.readFileSync(path.join(root, 'snooze-ui.js'), 'utf8');
|
||||||
|
const attachmentUi = fs.readFileSync(path.join(root, 'attachments.js'), 'utf8');
|
||||||
|
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
|
||||||
|
const pgpUi = fs.readFileSync(path.join(root, 'pgp-ui.js'), 'utf8');
|
||||||
|
const davUi = fs.readFileSync(path.join(root, 'dav-ui.js'), 'utf8');
|
||||||
|
const appShell = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
|
||||||
|
const mailUi = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
|
||||||
|
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
||||||
|
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
||||||
|
assert.match(accountUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(attachmentUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(snoozeUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(attachmentUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(pgpMailUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(pgpMailUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(pgpMailUi, /window\.epMailFeatures\.pgp = Object\.freeze/);
|
||||||
|
assert.doesNotMatch(pgpMailUi, /(?<!\.)\besc\s*\(/);
|
||||||
|
assert.match(pgpUi, /window\.epMailFeatures\.mail\.connectedAccount/);
|
||||||
|
assert.match(pgpUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(accountUi, /const accountDavUi = window\.epMailFeatures\.dav/);
|
||||||
|
assert.match(accountUi, /accountDavUi\.openManager/);
|
||||||
|
assert.doesNotMatch(accountUi, /(?<!\.)\b(?:esc|toast)\s*\(|(?<!\.)\$\(/);
|
||||||
|
assert.match(davUi, /window\.epMailFeatures\.dav = Object\.freeze/);
|
||||||
|
assert.match(davUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(appShell, /window\.epMailShell = Object\.freeze/);
|
||||||
|
assert.match(mailUi, /appShell\.wrapOpenMessage/);
|
||||||
|
assert.match(mailUi, /appShell\.wrapShowCompose/);
|
||||||
|
assert.match(mailUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(mailUi, /window\.epMailFeatures\.modules\.createMailUiApi/);
|
||||||
|
assert.match(mailUi, /window\.epMailFeatures\.mail = mailUiApi/);
|
||||||
|
assert.doesNotMatch(mailUi, /(?<!\.)\bopenPreferences\s*\(|(?<!\.)\bquery\s*=/);
|
||||||
|
assert.match(shortcutsUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(shortcutsUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(shortcutsUi, /window\.epMailFeatures\.productivity/);
|
||||||
|
assert.doesNotMatch(accountUi, /\bconnectedMailAccount\b|\bmailPageOffset\b|(?<!\.)\bsyncMailbox\s*\(/);
|
||||||
|
assert.doesNotMatch(snoozeUi, /\bconnectedMailAccount\b|(?<!\.)\bactiveFolder\b|(?<!\.)\bselectedIds\b|(?<!\.)\bsyncMailbox\s*\(/);
|
||||||
|
assert.doesNotMatch(attachmentUi, /\bconnectedMailAccount\b|(?<!\.)\bactiveFolder\b|(?<!\.)\bmessages\.find/);
|
||||||
|
assert.doesNotMatch(pgpMailUi, /(?<!\.)\bmessages\.find|(?<!\.)\bactiveMessage\b|window\.pgpPrepareSend/);
|
||||||
|
assert.doesNotMatch(pgpUi, /\bconnectedMailAccount\b/);
|
||||||
|
assert.match(productivityUi, /window\.epMailFeatures\.productivity/);
|
||||||
|
assert.match(productivityUi, /^\(\(\) => \{/);
|
||||||
|
assert.match(productivityUi, /window\.epMailFeatures\.productivity = Object\.freeze/);
|
||||||
|
assert.match(productivityUi, /addMessageLabel,/);
|
||||||
|
assert.match(snoozeUi, /snoozeProductivityUi\.addMessageLabel/);
|
||||||
|
assert.doesNotMatch(snoozeUi, /(?<!\.)\baddMessageLabel\s*\(/);
|
||||||
|
assert.doesNotMatch(shortcutsUi, /(?<!\.)\bactiveMessage\b|(?<!\.)\bopenMessage\s*\(/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const { createRendererState } = require('../renderer-state.js');
|
||||||
|
|
||||||
|
test('creates namespaced shared renderer state without legacy globals', () => {
|
||||||
|
const root = {};
|
||||||
|
const state = createRendererState(root);
|
||||||
|
|
||||||
|
assert.equal(root.epMailState, state);
|
||||||
|
assert.deepEqual(state.messages, []);
|
||||||
|
assert.deepEqual(state.contacts, []);
|
||||||
|
for (const key of Object.keys(state)) assert.equal(Object.hasOwn(root, key), false, `${key} must stay namespaced`);
|
||||||
|
assert.equal(state.activeFolder, 'Inbox');
|
||||||
|
assert.equal(state.activeView, 'mail');
|
||||||
|
assert.equal(state.activeMessage, 1);
|
||||||
|
assert.equal(state.query, '');
|
||||||
|
assert.ok(state.selectedIds instanceof Set);
|
||||||
|
|
||||||
|
state.activeFolder = 'Archive';
|
||||||
|
assert.equal(state.activeFolder, 'Archive');
|
||||||
|
state.query = 'from:alice';
|
||||||
|
assert.equal(state.query, 'from:alice');
|
||||||
|
vm.createContext(root);
|
||||||
|
vm.runInContext('epMailState.messages.push({ id: 1 }); epMailState.activeFolder = "Sent"; epMailState.selectedIds.add(5);', root);
|
||||||
|
assert.equal(state.messages.length, 1);
|
||||||
|
assert.equal(state.messages[0].id, 1);
|
||||||
|
assert.equal(state.activeFolder, 'Sent');
|
||||||
|
assert.equal(state.selectedIds.has(5), true);
|
||||||
|
assert.equal(root.epMailState, state);
|
||||||
|
assert.equal(Object.getOwnPropertyDescriptor(root, 'epMailState').writable, false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const os = require('node:os');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { createSecureJsonStore } = require('../desktop/secure-json-store.cjs');
|
||||||
|
|
||||||
|
async function withStore(run, { available = true, assertSecureStorage = () => {} } = {}) {
|
||||||
|
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ep-mail-store-'));
|
||||||
|
const file = path.join(directory, 'nested', 'store.enc');
|
||||||
|
const safeStorage = {
|
||||||
|
async isAsyncEncryptionAvailable() { return available; },
|
||||||
|
async encryptStringAsync(value) { return Buffer.from(value, 'utf8'); },
|
||||||
|
async decryptStringAsync(value) { return { result: Buffer.from(value).toString('utf8') }; }
|
||||||
|
};
|
||||||
|
const store = createSecureJsonStore({
|
||||||
|
getFilePath: () => file,
|
||||||
|
safeStorage,
|
||||||
|
assertSecureStorage,
|
||||||
|
unavailableMessage: 'Secure storage unavailable.'
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await run({ directory, file, store });
|
||||||
|
} finally {
|
||||||
|
await fs.rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('secure JSON store round-trips data and creates its parent directory', async () => {
|
||||||
|
await withStore(async ({ file, store }) => {
|
||||||
|
const value = { accounts: [{ email: 'user@example.com' }] };
|
||||||
|
await store.save(value);
|
||||||
|
assert.deepEqual(await store.load(), value);
|
||||||
|
assert.equal(await fs.readFile(`${file}.tmp`).then(() => true, () => false), false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secure JSON store checks the OS storage policy before reads and writes', async () => {
|
||||||
|
let checks = 0;
|
||||||
|
const assertSecureStorage = () => {
|
||||||
|
checks += 1;
|
||||||
|
if (checks > 0) throw new Error('Insecure backend.');
|
||||||
|
};
|
||||||
|
await withStore(async ({ store }) => {
|
||||||
|
await assert.rejects(() => store.save({}), /Insecure backend/);
|
||||||
|
await assert.rejects(() => store.load(), /Insecure backend/);
|
||||||
|
}, { assertSecureStorage });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secure JSON store refuses writes when asynchronous encryption is unavailable', async () => {
|
||||||
|
await withStore(async ({ file, store }) => {
|
||||||
|
await assert.rejects(() => store.save({ secret: true }), /Secure storage unavailable/);
|
||||||
|
await assert.rejects(() => fs.access(file), { code: 'ENOENT' });
|
||||||
|
}, { available: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secure JSON store reports missing files to the caller', async () => {
|
||||||
|
await withStore(async ({ store }) => {
|
||||||
|
await assert.rejects(() => store.load(), { code: 'ENOENT' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const generated = path.join(root, 'www');
|
||||||
|
const webAssetExtensions = new Set(['.css', '.html', '.js', '.svg', '.webmanifest']);
|
||||||
|
|
||||||
|
test('generated www web assets match their root source files', async () => {
|
||||||
|
const entries = await fs.readdir(root, { withFileTypes: true });
|
||||||
|
const assets = entries
|
||||||
|
.filter(entry => entry.isFile() && webAssetExtensions.has(path.extname(entry.name)))
|
||||||
|
.map(entry => entry.name);
|
||||||
|
|
||||||
|
assert.ok(assets.length > 0, 'expected root web assets to be present');
|
||||||
|
|
||||||
|
for (const asset of assets) {
|
||||||
|
const sourcePath = path.join(root, asset);
|
||||||
|
const generatedPath = path.join(generated, asset);
|
||||||
|
const [source, output] = await Promise.all([
|
||||||
|
fs.readFile(sourcePath),
|
||||||
|
fs.readFile(generatedPath).catch(error => {
|
||||||
|
if (error.code === 'ENOENT') {
|
||||||
|
assert.fail(`generated web asset is missing: www/${asset}`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(output, source, `www/${asset} is stale; rebuild Android web assets`);
|
||||||
|
}
|
||||||
|
});
|
||||||
+13
-8
@@ -1,26 +1,31 @@
|
|||||||
|
(() => {
|
||||||
|
const accountMailUi = window.epMailFeatures.mail;
|
||||||
|
const accountDavUi = window.epMailFeatures.dav;
|
||||||
|
|
||||||
async function openAccountManager(){
|
async function openAccountManager(){
|
||||||
const root=$('#modal-root');
|
const root=accountMailUi.select('#modal-root');
|
||||||
try{
|
try{
|
||||||
const data=await window.daybreakMail.listAccounts();
|
const data=await window.daybreakMail.listAccounts();
|
||||||
const accounts=data.accounts||[];
|
const accounts=data.accounts||[];
|
||||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
|
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${accountMailUi.escapeHtml(account.displayName||account.email)}</strong><small>${accountMailUi.escapeHtml(account.email)} · ${accountMailUi.escapeHtml(account.imapHost)} · ${accountMailUi.escapeHtml(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${accountMailUi.escapeHtml(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${accountMailUi.escapeHtml(account.id)}">Edit</button><button class="discard" data-remove-account="${accountMailUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
|
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
|
||||||
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()};
|
root.querySelector('#add-mail-account').onclick=()=>{close();accountMailUi.openMailAccount()};
|
||||||
root.onclick=async event=>{
|
root.onclick=async event=>{
|
||||||
const switchButton=event.target.closest('[data-switch-account]');
|
const switchButton=event.target.closest('[data-switch-account]');
|
||||||
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
|
if(switchButton){switchButton.disabled=true;try{accountMailUi.connectedAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));accountMailUi.select('#sidebar-title').textContent='Inbox';accountMailUi.select('#crumb-current').textContent='Inbox';accountMailUi.updateAccountCard(accountMailUi.connectedAccount);close();await accountMailUi.syncMailbox(true,{offset:0})}catch(error){accountMailUi.toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
|
||||||
const davButton=event.target.closest('[data-open-dav]');
|
const davButton=event.target.closest('[data-open-dav]');
|
||||||
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
|
if(davButton){close();accountDavUi.openManager(davButton.dataset.openDav);return}
|
||||||
const editButton=event.target.closest('[data-edit-account]');
|
const editButton=event.target.closest('[data-edit-account]');
|
||||||
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
||||||
};
|
};
|
||||||
}catch(error){toast(error.message||'Could not load mail accounts')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
||||||
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
|
||||||
|
})();
|
||||||
|
|||||||
+53
-13
@@ -1,17 +1,57 @@
|
|||||||
|
(() => {
|
||||||
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
|
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
|
||||||
const messages = [];
|
const state = window.epMailState;
|
||||||
const contacts=[];
|
|
||||||
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
|
|
||||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||||
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||||||
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
|
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
||||||
function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)}
|
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
|
||||||
|
function openMessage(id){
|
||||||
|
state.activeMessage=id;
|
||||||
|
const m=state.messages.find(x=>x.id===id);
|
||||||
|
if(!m)return;
|
||||||
|
m.unread=false;
|
||||||
|
renderList();
|
||||||
|
let safeHtml={html:'',remoteImageCount:0};
|
||||||
|
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
|
||||||
|
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
||||||
|
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
||||||
|
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
||||||
|
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
||||||
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
|
image.removeAttribute('data-remote-src');
|
||||||
|
if(url)image.src=url;
|
||||||
|
});
|
||||||
|
$('.remote-image-notice')?.remove();
|
||||||
|
});
|
||||||
|
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
|
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
|
$('#forward').onclick=()=>showCompose(m,true);
|
||||||
|
}
|
||||||
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
|
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
|
||||||
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
|
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(state.toastTimer);state.toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
|
||||||
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
|
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;state.messages.unshift({id:Date.now(),initials:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me'),email:(window.epMailFeatures.mail.connectedAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
|
||||||
function switchView(view){activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';}
|
function switchView(view){state.activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';if(view==='calendar')window.epMailFeatures.productivity.renderCalendar();if(view==='contacts')window.epMailFeatures.productivity.renderContacts();}
|
||||||
function renderCalendar(){}
|
$$('.folder').forEach(b=>b.onclick=()=>{state.activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=state.activeFolder;$('#crumb-current').textContent=state.activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{state.query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';state.query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=state.messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>state.selectedIds.has(m.id));visible.forEach(m=>all?state.selectedIds.delete(m.id):state.selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.archived=true);state.selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.deleted=true);state.selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(state.activeMessage);
|
||||||
function showEvent(){}
|
|
||||||
function renderContacts(){}
|
window.epMailShell = Object.freeze({
|
||||||
function showContact(){}
|
state,
|
||||||
$$('.folder').forEach(b=>b.onclick=()=>{activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);if(b.dataset.view==='calendar')renderCalendar();if(b.dataset.view==='contacts')renderContacts()});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>selectedIds.has(m.id));visible.forEach(m=>all?selectedIds.delete(m.id):selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.archived=true);selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.deleted=true);selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(activeMessage);
|
select: $,
|
||||||
|
selectAll: $$,
|
||||||
|
escapeHtml: esc,
|
||||||
|
toast,
|
||||||
|
switchView,
|
||||||
|
applyTheme,
|
||||||
|
baseRenderList: renderList,
|
||||||
|
get renderList() { return renderList; },
|
||||||
|
get openMessage() { return openMessage; },
|
||||||
|
get showCompose() { return showCompose; },
|
||||||
|
emptyReader,
|
||||||
|
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
||||||
|
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
||||||
|
wrapShowCompose(decorator) { showCompose = decorator(showCompose); }
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
+24
-21
@@ -1,4 +1,9 @@
|
|||||||
|
(() => {
|
||||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||||
|
const attachmentMailUi = window.epMailFeatures.mail;
|
||||||
|
const selectAttachmentUi = attachmentMailUi.select;
|
||||||
|
const selectAllAttachmentUi = attachmentMailUi.selectAll;
|
||||||
|
const toastAttachmentUi = attachmentMailUi.toast;
|
||||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
let attachmentItems = [];
|
let attachmentItems = [];
|
||||||
|
|
||||||
@@ -45,20 +50,18 @@ async function previewAttachment(target, details) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function downloadAttachment(details) {
|
function downloadAttachment(details) {
|
||||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
|
||||||
window.daybreakMail.saveAttachment(details)
|
window.daybreakMail.saveAttachment(details)
|
||||||
.then(result => { if (result.saved) toast('Attachment saved'); })
|
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
|
||||||
.catch(error => toast(error.message || 'Could not save attachment'));
|
.catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add a Preview button to each attachment in the reader.
|
// Add a Preview button to each attachment in the reader.
|
||||||
if (typeof openMessage === 'function') {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
const baseOpenMessage = openMessage;
|
|
||||||
openMessage = function (id) {
|
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid) return;
|
||||||
$$('#reader-pane .attachment').forEach(row => {
|
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
||||||
const download = row.querySelector('.download');
|
const download = row.querySelector('.download');
|
||||||
if (!download || row.querySelector('.preview-attachment')) return;
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
const button = document.createElement('button');
|
const button = document.createElement('button');
|
||||||
@@ -73,12 +76,11 @@ if (typeof openMessage === 'function') {
|
|||||||
panel = document.createElement('div');
|
panel = document.createElement('div');
|
||||||
panel.className = 'attachment-preview';
|
panel.className = 'attachment-preview';
|
||||||
row.after(panel);
|
row.after(panel);
|
||||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || attachmentMailUi.state.activeFolder, filename: download.dataset.filename });
|
||||||
});
|
});
|
||||||
download.before(button);
|
download.before(button);
|
||||||
});
|
});
|
||||||
};
|
});
|
||||||
}
|
|
||||||
|
|
||||||
async function collectAttachments() {
|
async function collectAttachments() {
|
||||||
const items = [];
|
const items = [];
|
||||||
@@ -103,16 +105,16 @@ async function collectAttachments() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openAttachmentsView() {
|
async function openAttachmentsView() {
|
||||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
|
||||||
const root = $('#modal-root');
|
const root = selectAttachmentUi('#modal-root');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('.modal-close').onclick = close;
|
root.querySelector('.modal-close').onclick = close;
|
||||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
const list = $('#attachment-list');
|
const list = selectAttachmentUi('#attachment-list');
|
||||||
const render = () => {
|
const render = () => {
|
||||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
|
||||||
const type = $('#attachment-type').value;
|
const type = selectAttachmentUi('#attachment-type').value;
|
||||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
@@ -146,16 +148,17 @@ async function openAttachmentsView() {
|
|||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
$('#attachment-search').oninput = render;
|
selectAttachmentUi('#attachment-search').oninput = render;
|
||||||
$('#attachment-type').onchange = render;
|
selectAttachmentUi('#attachment-type').onchange = render;
|
||||||
try {
|
try {
|
||||||
attachmentItems = await collectAttachments();
|
attachmentItems = await collectAttachments();
|
||||||
if ($('#attachment-list')) render();
|
if (selectAttachmentUi('#attachment-list')) render();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
});
|
});
|
||||||
|
})();
|
||||||
|
|||||||
+25
-15
@@ -1,38 +1,48 @@
|
|||||||
|
(() => {
|
||||||
|
const davProductivityUi = window.epMailFeatures.productivity;
|
||||||
|
const selectDavUi = davProductivityUi.select;
|
||||||
|
|
||||||
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
|
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
|
||||||
async function syncDav(type, uploadLocal=false){
|
async function syncDav(type, uploadLocal=false){
|
||||||
try{
|
try{
|
||||||
const localOnly=type==='caldav'?savedEvents.filter(item=>!item._dav):savedContacts.filter(item=>!item._dav);
|
const localOnly=type==='caldav'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.filter(item=>!item._dav);
|
||||||
const result=await window.daybreakMail.davSync(type);
|
const result=await window.daybreakMail.davSync(type);
|
||||||
if(type==='caldav'){
|
if(type==='caldav'){
|
||||||
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){toast(`Could not upload “${event.title}”: ${error.message}`)}}
|
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){davProductivityUi.toast(`Could not upload “${event.title}”: ${error.message}`)}}
|
||||||
savedEvents=[...localOnly,...result.items];
|
davProductivityUi.events=[...localOnly,...result.items];
|
||||||
productWrite(productKeys.events,savedEvents);renderCalendar();toast(`Synced ${result.items.length} calendar events`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.toast(`Synced ${result.items.length} calendar events`);
|
||||||
}else{
|
}else{
|
||||||
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){toast(`Could not upload “${contact.name}”: ${error.message}`)}}
|
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){davProductivityUi.toast(`Could not upload “${contact.name}”: ${error.message}`)}}
|
||||||
savedContacts=[...localOnly,...result.items];
|
davProductivityUi.contacts=[...localOnly,...result.items];
|
||||||
productWrite(productKeys.contacts,savedContacts);renderContacts();toast(`Synced ${result.items.length} contacts`);
|
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
|
||||||
}
|
}
|
||||||
}catch(error){toast(error.message||`Could not sync ${davTypeName(type)}`)}
|
}catch(error){davProductivityUi.toast(error.message||`Could not sync ${davTypeName(type)}`)}
|
||||||
}
|
}
|
||||||
async function openDavManager(type){
|
async function openDavManager(type){
|
||||||
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
||||||
try{
|
try{
|
||||||
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
|
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
|
||||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.username)}</strong><small>${esc(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>esc(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${esc(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${esc(account.id)}">Remove</button></div></div>`).join('');
|
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${davProductivityUi.escapeHtml(account.username)}</strong><small>${davProductivityUi.escapeHtml(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>davProductivityUi.escapeHtml(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${davProductivityUi.escapeHtml(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${davProductivityUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
|
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
|
||||||
root.onclick=async event=>{
|
root.onclick=async event=>{
|
||||||
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){toast(error.message)}return}
|
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){davProductivityUi.toast(error.message)}return}
|
||||||
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){savedEvents=savedEvents.filter(item=>!item._dav);productWrite(productKeys.events,savedEvents);renderCalendar()}else{savedContacts=savedContacts.filter(item=>!item._dav);productWrite(productKeys.contacts,savedContacts);renderContacts()}await openDavManager(type)}catch(error){toast(error.message)} }
|
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){davProductivityUi.events=davProductivityUi.events.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar()}else{davProductivityUi.contacts=davProductivityUi.contacts.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts()}await openDavManager(type)}catch(error){davProductivityUi.toast(error.message)} }
|
||||||
};
|
};
|
||||||
}catch(error){toast(error.message||`Could not load ${label} servers`)}
|
}catch(error){davProductivityUi.toast(error.message||`Could not load ${label} servers`)}
|
||||||
}
|
}
|
||||||
function showDavConnect(type){
|
function showDavConnect(type){
|
||||||
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test & connect</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test & connect</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
|
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
|
||||||
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
|
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();davProductivityUi.toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
|
||||||
root.querySelector('#dav-server-url').focus();
|
root.querySelector('#dav-server-url').focus();
|
||||||
}
|
}
|
||||||
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
|
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
|
||||||
|
|
||||||
|
window.epMailFeatures.dav = Object.freeze({
|
||||||
|
openManager: openDavManager,
|
||||||
|
sync: syncDav
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|||||||
+5
-2
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<meta name="theme-color" content="#f4f5f1">
|
<meta name="theme-color" content="#f4f5f1">
|
||||||
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
|
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
|
||||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'">
|
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
|
||||||
<title>ep-mail</title>
|
<title>ep-mail</title>
|
||||||
<link rel="manifest" href="manifest.webmanifest">
|
<link rel="manifest" href="manifest.webmanifest">
|
||||||
<link rel="stylesheet" href="styles.css">
|
<link rel="stylesheet" href="styles.css">
|
||||||
@@ -64,13 +64,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div id="modal-root"></div>
|
<div id="modal-root"></div>
|
||||||
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
||||||
|
<script src="renderer-state.js"></script>
|
||||||
|
<script src="mail-content-security.js"></script>
|
||||||
<script src="app.js"></script>
|
<script src="app.js"></script>
|
||||||
<script src="platform-bridge.js"></script>
|
<script src="platform-bridge.js"></script>
|
||||||
|
<script src="renderer-mail-api.js"></script>
|
||||||
<script src="mail-ui.js"></script>
|
<script src="mail-ui.js"></script>
|
||||||
<script src="productivity.js"></script>
|
<script src="productivity.js"></script>
|
||||||
<script src="snooze-ui.js"></script>
|
<script src="snooze-ui.js"></script>
|
||||||
<script src="account-ui.js"></script>
|
|
||||||
<script src="dav-ui.js"></script>
|
<script src="dav-ui.js"></script>
|
||||||
|
<script src="account-ui.js"></script>
|
||||||
<script src="shortcuts.js"></script>
|
<script src="shortcuts.js"></script>
|
||||||
<script src="attachments.js"></script>
|
<script src="attachments.js"></script>
|
||||||
<script src="pgp-ui.js"></script>
|
<script src="pgp-ui.js"></script>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user